/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Diff of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 695 by persson, Sat Jul 16 19:36:23 2005 UTC revision 2985 by schoenebeck, Tue Sep 20 22:13:37 2016 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26  #include <iostream>  #include "helper.h"
   
 namespace gig {  
   
 // *************** progress_t ***************  
 // *  
27    
28      progress_t::progress_t() {  #include <algorithm>
29          callback    = NULL;  #include <math.h>
30          custom      = NULL;  #include <iostream>
31          __range_min = 0.0f;  #include <assert.h>
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
32    
33      // private helper function to divide a progress into subprogresses  /// libgig's current file format version (for extending the original Giga file
34      static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  /// format with libgig's own custom data / custom features).
35          if (pParentProgress && pParentProgress->callback) {  #define GIG_FILE_EXT_VERSION    2
36              const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
37              pSubProgress->callback    = pParentProgress->callback;  /// Initial size of the sample buffer which is used for decompression of
38              pSubProgress->custom      = pParentProgress->custom;  /// compressed sample wave streams - this value should always be bigger than
39              pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  /// the biggest sample piece expected to be read by the sampler engine,
40              pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  /// otherwise the buffer size will be raised at runtime and thus the buffer
41          }  /// reallocated which is time consuming and unefficient.
42      }  #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
43    
44    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
45    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
46    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
47    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
48    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
49    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
50    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
51    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
52    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
53    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
54    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
55    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
56    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
57    
58    namespace gig {
59    
60  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decompression ***************
61  // *  // *
62    
63  namespace {  namespace {
# Line 87  namespace { Line 85  namespace {
85          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
86      }      }
87    
88        inline void store24(unsigned char* pDst, int x)
89        {
90            pDst[0] = x;
91            pDst[1] = x >> 8;
92            pDst[2] = x >> 16;
93        }
94    
95      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
96                        int srcStep, int dstStep,                        int srcStep, int dstStep,
97                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
98                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
99                        unsigned long copysamples)                        file_offset_t copysamples)
100      {      {
101          switch (compressionmode) {          switch (compressionmode) {
102              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 126  namespace { Line 131  namespace {
131      }      }
132    
133      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
134                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
136                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
137      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
138          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
139    
140  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
141          y    = get24(params);                   \          y    = get24(params);                   \
# Line 149  namespace { Line 151  namespace {
151    
152  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
153          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
154          *pDst = y >> shift;                     \          store24(pDst, y << truncatedBits);      \
155          pDst += dstStep          pDst += dstStep
156    
157          switch (compressionmode) {          switch (compressionmode) {
158              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
159                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
160                  while (copysamples) {                  while (copysamples) {
161                      *pDst = get24(pSrc) >> shift;                      store24(pDst, get24(pSrc) << truncatedBits);
162                      pDst += dstStep;                      pDst += dstStep;
163                      pSrc += 3;                      pSrc += 3;
164                      copysamples--;                      copysamples--;
# Line 226  namespace { Line 228  namespace {
228  }  }
229    
230    
231    
232    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
233    // *
234    
235        static uint32_t* __initCRCTable() {
236            static uint32_t res[256];
237    
238            for (int i = 0 ; i < 256 ; i++) {
239                uint32_t c = i;
240                for (int j = 0 ; j < 8 ; j++) {
241                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
242                }
243                res[i] = c;
244            }
245            return res;
246        }
247    
248        static const uint32_t* __CRCTable = __initCRCTable();
249    
250        /**
251         * Initialize a CRC variable.
252         *
253         * @param crc - variable to be initialized
254         */
255        inline static void __resetCRC(uint32_t& crc) {
256            crc = 0xffffffff;
257        }
258    
259        /**
260         * Used to calculate checksums of the sample data in a gig file. The
261         * checksums are stored in the 3crc chunk of the gig file and
262         * automatically updated when a sample is written with Sample::Write().
263         *
264         * One should call __resetCRC() to initialize the CRC variable to be
265         * used before calling this function the first time.
266         *
267         * After initializing the CRC variable one can call this function
268         * arbitrary times, i.e. to split the overall CRC calculation into
269         * steps.
270         *
271         * Once the whole data was processed by __calculateCRC(), one should
272         * call __encodeCRC() to get the final CRC result.
273         *
274         * @param buf     - pointer to data the CRC shall be calculated of
275         * @param bufSize - size of the data to be processed
276         * @param crc     - variable the CRC sum shall be stored to
277         */
278        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
279            for (int i = 0 ; i < bufSize ; i++) {
280                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281            }
282        }
283    
284        /**
285         * Returns the final CRC result.
286         *
287         * @param crc - variable previously passed to __calculateCRC()
288         */
289        inline static uint32_t __encodeCRC(const uint32_t& crc) {
290            return crc ^ 0xffffffff;
291        }
292    
293    
294    
295    // *************** Other Internal functions  ***************
296    // *
297    
298        static split_type_t __resolveSplitType(dimension_t dimension) {
299            return (
300                dimension == dimension_layer ||
301                dimension == dimension_samplechannel ||
302                dimension == dimension_releasetrigger ||
303                dimension == dimension_keyboard ||
304                dimension == dimension_roundrobin ||
305                dimension == dimension_random ||
306                dimension == dimension_smartmidi ||
307                dimension == dimension_roundrobinkeyboard
308            ) ? split_type_bit : split_type_normal;
309        }
310    
311        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
312            return (dimension_definition.split_type == split_type_normal)
313            ? int(128.0 / dimension_definition.zones) : 0;
314        }
315    
316    
317    
318  // *************** Sample ***************  // *************** Sample ***************
319  // *  // *
320    
321      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
322      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
323    
324      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
325         *
326         * Load an existing sample or create a new one. A 'wave' list chunk must
327         * be given to this constructor. In case the given 'wave' list chunk
328         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
329         * format and sample data will be loaded from there, otherwise default
330         * values will be used and those chunks will be created when
331         * File::Save() will be called later on.
332         *
333         * @param pFile          - pointer to gig::File where this sample is
334         *                         located (or will be located)
335         * @param waveList       - pointer to 'wave' list chunk which is (or
336         *                         will be) associated with this sample
337         * @param WavePoolOffset - offset of this sample data from wave pool
338         *                         ('wvpl') list chunk
339         * @param fileNo         - number of an extension file where this sample
340         *                         is located, 0 otherwise
341         */
342        Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343            static const DLS::Info::string_length_t fixedStringLengths[] = {
344                { CHUNK_ID_INAM, 64 },
345                { 0, 0 }
346            };
347            pInfo->SetFixedStringLengths(fixedStringLengths);
348          Instances++;          Instances++;
349          FileNo = fileNo;          FileNo = fileNo;
350    
351          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          __resetCRC(crc);
352          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");  
353          SampleGroup = _3gix->ReadInt16();          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
354            if (pCk3gix) {
355          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              uint16_t iSampleGroup = pCk3gix->ReadInt16();
356          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              pGroup = pFile->GetGroup(iSampleGroup);
357          Manufacturer      = smpl->ReadInt32();          } else { // '3gix' chunk missing
358          Product           = smpl->ReadInt32();              // by default assigned to that mandatory "Default Group"
359          SamplePeriod      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
360          MIDIUnityNote     = smpl->ReadInt32();          }
361          FineTune          = smpl->ReadInt32();  
362          smpl->Read(&SMPTEFormat, 1, 4);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
363          SMPTEOffset       = smpl->ReadInt32();          if (pCkSmpl) {
364          Loops             = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
365          smpl->ReadInt32(); // manufByt              Product       = pCkSmpl->ReadInt32();
366          LoopID            = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
367          smpl->Read(&LoopType, 1, 4);              MIDIUnityNote = pCkSmpl->ReadInt32();
368          LoopStart         = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
369          LoopEnd           = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
370          LoopFraction      = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
371          LoopPlayCount     = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
372                pCkSmpl->ReadInt32(); // manufByt
373                LoopID        = pCkSmpl->ReadInt32();
374                pCkSmpl->Read(&LoopType, 1, 4);
375                LoopStart     = pCkSmpl->ReadInt32();
376                LoopEnd       = pCkSmpl->ReadInt32();
377                LoopFraction  = pCkSmpl->ReadInt32();
378                LoopPlayCount = pCkSmpl->ReadInt32();
379            } else { // 'smpl' chunk missing
380                // use default values
381                Manufacturer  = 0;
382                Product       = 0;
383                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
384                MIDIUnityNote = 60;
385                FineTune      = 0;
386                SMPTEFormat   = smpte_format_no_offset;
387                SMPTEOffset   = 0;
388                Loops         = 0;
389                LoopID        = 0;
390                LoopType      = loop_type_normal;
391                LoopStart     = 0;
392                LoopEnd       = 0;
393                LoopFraction  = 0;
394                LoopPlayCount = 0;
395            }
396    
397          FrameTable                 = NULL;          FrameTable                 = NULL;
398          SamplePos                  = 0;          SamplePos                  = 0;
# Line 287  namespace { Line 423  namespace {
423          }          }
424          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
425    
426          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
427        }
428    
429        /**
430         * Make a (semi) deep copy of the Sample object given by @a orig (without
431         * the actual waveform data) and assign it to this object.
432         *
433         * Discussion: copying .gig samples is a bit tricky. It requires three
434         * steps:
435         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
436         *    its new sample waveform data size.
437         * 2. Saving the file (done by File::Save()) so that it gains correct size
438         *    and layout for writing the actual wave form data directly to disc
439         *    in next step.
440         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
441         *
442         * @param orig - original Sample object to be copied from
443         */
444        void Sample::CopyAssignMeta(const Sample* orig) {
445            // handle base classes
446            DLS::Sample::CopyAssignCore(orig);
447            
448            // handle actual own attributes of this class
449            Manufacturer = orig->Manufacturer;
450            Product = orig->Product;
451            SamplePeriod = orig->SamplePeriod;
452            MIDIUnityNote = orig->MIDIUnityNote;
453            FineTune = orig->FineTune;
454            SMPTEFormat = orig->SMPTEFormat;
455            SMPTEOffset = orig->SMPTEOffset;
456            Loops = orig->Loops;
457            LoopID = orig->LoopID;
458            LoopType = orig->LoopType;
459            LoopStart = orig->LoopStart;
460            LoopEnd = orig->LoopEnd;
461            LoopSize = orig->LoopSize;
462            LoopFraction = orig->LoopFraction;
463            LoopPlayCount = orig->LoopPlayCount;
464            
465            // schedule resizing this sample to the given sample's size
466            Resize(orig->GetSize());
467        }
468    
469        /**
470         * Should be called after CopyAssignMeta() and File::Save() sequence.
471         * Read more about it in the discussion of CopyAssignMeta(). This method
472         * copies the actual waveform data by disk streaming.
473         *
474         * @e CAUTION: this method is currently not thread safe! During this
475         * operation the sample must not be used for other purposes by other
476         * threads!
477         *
478         * @param orig - original Sample object to be copied from
479         */
480        void Sample::CopyAssignWave(const Sample* orig) {
481            const int iReadAtOnce = 32*1024;
482            char* buf = new char[iReadAtOnce * orig->FrameSize];
483            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484            file_offset_t restorePos = pOrig->GetPos();
485            pOrig->SetPos(0);
486            SetPos(0);
487            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                               n = pOrig->Read(buf, iReadAtOnce))
489            {
490                Write(buf, n);
491            }
492            pOrig->SetPos(restorePos);
493            delete [] buf;
494        }
495    
496        /**
497         * Apply sample and its settings to the respective RIFF chunks. You have
498         * to call File::Save() to make changes persistent.
499         *
500         * Usually there is absolutely no need to call this method explicitly.
501         * It will be called automatically when File::Save() was called.
502         *
503         * @param pProgress - callback function for progress notification
504         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505         *                        was provided yet
506         * @throws gig::Exception if there is any invalid sample setting
507         */
508        void Sample::UpdateChunks(progress_t* pProgress) {
509            // first update base class's chunks
510            DLS::Sample::UpdateChunks(pProgress);
511    
512            // make sure 'smpl' chunk exists
513            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
514            if (!pCkSmpl) {
515                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
516                memset(pCkSmpl->LoadChunkData(), 0, 60);
517            }
518            // update 'smpl' chunk
519            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
520            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
521            store32(&pData[0], Manufacturer);
522            store32(&pData[4], Product);
523            store32(&pData[8], SamplePeriod);
524            store32(&pData[12], MIDIUnityNote);
525            store32(&pData[16], FineTune);
526            store32(&pData[20], SMPTEFormat);
527            store32(&pData[24], SMPTEOffset);
528            store32(&pData[28], Loops);
529    
530            // we skip 'manufByt' for now (4 bytes)
531    
532            store32(&pData[36], LoopID);
533            store32(&pData[40], LoopType);
534            store32(&pData[44], LoopStart);
535            store32(&pData[48], LoopEnd);
536            store32(&pData[52], LoopFraction);
537            store32(&pData[56], LoopPlayCount);
538    
539            // make sure '3gix' chunk exists
540            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
541            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
542            // determine appropriate sample group index (to be stored in chunk)
543            uint16_t iSampleGroup = 0; // 0 refers to default sample group
544            File* pFile = static_cast<File*>(pParent);
545            if (pFile->pGroups) {
546                std::list<Group*>::iterator iter = pFile->pGroups->begin();
547                std::list<Group*>::iterator end  = pFile->pGroups->end();
548                for (int i = 0; iter != end; i++, iter++) {
549                    if (*iter == pGroup) {
550                        iSampleGroup = i;
551                        break; // found
552                    }
553                }
554            }
555            // update '3gix' chunk
556            pData = (uint8_t*) pCk3gix->LoadChunkData();
557            store16(&pData[0], iSampleGroup);
558    
559            // if the library user toggled the "Compressed" attribute from true to
560            // false, then the EWAV chunk associated with compressed samples needs
561            // to be deleted
562            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
563            if (ewav && !Compressed) {
564                pWaveList->DeleteSubChunk(ewav);
565            }
566      }      }
567    
568      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 310  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 329  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 345  namespace { Line 620  namespace {
620    
621          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 388  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 447  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729            SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
732          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 488  namespace { Line 764  namespace {
764          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
765          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
766          RAMCache.Size   = 0;          RAMCache.Size   = 0;
767            RAMCache.NullExtensionSize = 0;
768        }
769    
770        /** @brief Resize sample.
771         *
772         * Resizes the sample's wave form data, that is the actual size of
773         * sample wave data possible to be written for this sample. This call
774         * will return immediately and just schedule the resize operation. You
775         * should call File::Save() to actually perform the resize operation(s)
776         * "physically" to the file. As this can take a while on large files, it
777         * is recommended to call Resize() first on all samples which have to be
778         * resized and finally to call File::Save() to perform all those resize
779         * operations in one rush.
780         *
781         * The actual size (in bytes) is dependant to the current FrameSize
782         * value. You may want to set FrameSize before calling Resize().
783         *
784         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
785         * enlarged samples before calling File::Save() as this might exceed the
786         * current sample's boundary!
787         *
788         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
789         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
790         * other formats will fail!
791         *
792         * @param NewSize - new sample wave data size in sample points (must be
793         *                  greater than zero)
794         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
795         * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
796         * @throws gig::Exception if existing sample is compressed
797         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
798         *      DLS::Sample::FormatTag, File::Save()
799         */
800        void Sample::Resize(file_offset_t NewSize) {
801            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
802            DLS::Sample::Resize(NewSize);
803      }      }
804    
805      /**      /**
# Line 511  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 529  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 545  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 579  namespace { Line 891  namespace {
891       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
892       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
893       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
894         * @param pDimRgn          dimension region with looping information
895       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
900          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901            file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
905    
906          if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined          if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
907    
908              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
909                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
910    
911                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
912                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
913    
914                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
915                              // determine the end position within the loop first,                          do {
916                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
917                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
918                              // backward playback  
919                                if (!pPlaybackState->reverse) { // forward playback
920                              unsigned long swapareastart       = totalreadsamples;                                  do {
921                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
922                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
923                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
924                                        totalreadsamples += readsamples;
925                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
926                                            pPlaybackState->reverse = true;
927                              // read samples for backward playback                                          break;
928                              do {                                      }
929                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
930                                  samplestoreadinloop -= readsamples;                              }
931                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
932    
933                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
934                                    // determine the end position within the loop first,
935                                    // read forward from that 'end' and finally after
936                                    // reading, swap all sample frames so it reflects
937                                    // backward playback
938    
939                                    file_offset_t swapareastart       = totalreadsamples;
940                                    file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                    file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                    file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                    SetPos(reverseplaybackend);
945    
946                                    // read samples for backward playback
947                                    do {
948                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
949                                        samplestoreadinloop -= readsamples;
950                                        samplestoread       -= readsamples;
951                                        totalreadsamples    += readsamples;
952                                    } while (samplestoreadinloop && readsamples);
953    
954                                    SetPos(reverseplaybackend); // pretend we really read backwards
955    
956                                    if (reverseplaybackend == loop.LoopStart) {
957                                        pPlaybackState->loop_cycles_left--;
958                                        pPlaybackState->reverse = false;
959                                    }
960    
961                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
962                                  pPlaybackState->loop_cycles_left--;                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
963                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
964                              }                              }
965                            } while (samplestoread && readsamples);
966                            break;
967                        }
968    
969                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
970                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
971                          }                          if (!pPlaybackState->reverse) do {
972                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
973                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
974                  }                              samplestoread    -= readsamples;
975                                totalreadsamples += readsamples;
976                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
977                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
978                      if (!pPlaybackState->reverse) do {                                  break;
979                          samplestoloopend  = this->LoopEnd - GetPos();                              }
980                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
981    
982                      if (!samplestoread) break;                          if (!samplestoread) break;
983    
984                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
985                      // determine the end position within the loop first,                          // determine the end position within the loop first,
986                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
987                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                      // backward playback                          // backward playback
989    
990                      unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
993                                                                                : samplestoread;                                                                                    : samplestoread;
994                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
998                      // read samples for backward playback                          // read samples for backward playback
999                      do {                          do {
1000                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1001                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1002                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
1003                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1004                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1005                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1006                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1007                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1008                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1009                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1010                          }                              }
1011                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1012    
1013                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1014    
1015                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1016                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1017                      break;                          break;
1018                  }                      }
1019    
1020                  default: case loop_type_normal: {                      default: case loop_type_normal: {
1021                      do {                          do {
1022                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1023                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1024                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
1025                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1026                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1027                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1028                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1029                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1030                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1031                          }                              }
1032                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1033                      break;                          break;
1034                        }
1035                  }                  }
1036              }              }
1037          }          }
# Line 741  namespace { Line 1061  namespace {
1061       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
1062       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
1063       *       *
1064         * For 16 bit samples, the data in the buffer will be int16_t
1065         * (using native endianness). For 24 bit, the buffer will
1066         * contain three bytes per sample, little-endian.
1067         *
1068       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1069       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1070       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
1078                  // 24 bit sample. For now just truncate to 16 bit.                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
                 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);  
                 int16_t* pDst = static_cast<int16_t*>(pBuffer);  
                 if (Channels == 2) { // Stereo  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;  
                 }  
                 else { // Mono  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return pDst - static_cast<int16_t*>(pBuffer);  
                 }  
1079              }              }
1080              else { // 16 bit              else { // 16 bit
1081                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 782  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 801  namespace { Line 1105  namespace {
1105    
1106              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1107              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1108                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 882  namespace { Line 1187  namespace {
1187                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1188                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1189    
1190                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1191                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1192                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1193                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1194                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1195                          }                          }
1196                          else { // Mono                          else { // Mono
1197                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1198                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1199                              pDst += copysamples;                              pDst24 += copysamples * 3;
1200                          }                          }
1201                      }                      }
1202                      else { // 16 bit                      else { // 16 bit
# Line 933  namespace { Line 1238  namespace {
1238          }          }
1239      }      }
1240    
1241        /** @brief Write sample wave data.
1242         *
1243         * Writes \a SampleCount number of sample points from the buffer pointed
1244         * by \a pBuffer and increments the position within the sample. Use this
1245         * method to directly write the sample data to disk, i.e. if you don't
1246         * want or cannot load the whole sample data into RAM.
1247         *
1248         * You have to Resize() the sample to the desired size and call
1249         * File::Save() <b>before</b> using Write().
1250         *
1251         * Note: there is currently no support for writing compressed samples.
1252         *
1253         * For 16 bit samples, the data in the source buffer should be
1254         * int16_t (using native endianness). For 24 bit, the buffer
1255         * should contain three bytes per sample, little-endian.
1256         *
1257         * @param pBuffer     - source buffer
1258         * @param SampleCount - number of sample points to write
1259         * @throws DLS::Exception if current sample size is too small
1260         * @throws gig::Exception if sample is compressed
1261         * @see DLS::LoadSampleData()
1262         */
1263        file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1265    
1266            // if this is the first write in this sample, reset the
1267            // checksum calculator
1268            if (pCkData->GetPos() == 0) {
1269                __resetCRC(crc);
1270            }
1271            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1272            file_offset_t res;
1273            if (BitDepth == 24) {
1274                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275            } else { // 16 bit
1276                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1277                                    : pCkData->Write(pBuffer, SampleCount, 2);
1278            }
1279            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1280    
1281            // if this is the last write, update the checksum chunk in the
1282            // file
1283            if (pCkData->GetPos() == pCkData->GetSize()) {
1284                File* pFile = static_cast<File*>(GetParent());
1285                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1286            }
1287            return res;
1288        }
1289    
1290      /**      /**
1291       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1292       * with Sample::Read(). If you are using more than one streaming thread       * with Sample::Read(). If you are using more than one streaming thread
# Line 949  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1310          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 975  namespace { Line 1329  namespace {
1329          }          }
1330      }      }
1331    
1332        /**
1333         * Returns pointer to the Group this Sample belongs to. In the .gig
1334         * format a sample always belongs to one group. If it wasn't explicitly
1335         * assigned to a certain group, it will be automatically assigned to a
1336         * default group.
1337         *
1338         * @returns Sample's Group (never NULL)
1339         */
1340        Group* Sample::GetGroup() const {
1341            return pGroup;
1342        }
1343    
1344        /**
1345         * Checks the integrity of this sample's raw audio wave data. Whenever a
1346         * Sample's raw wave data is intentionally modified (i.e. by calling
1347         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1348         * is calculated and stored/updated for this sample, along to the sample's
1349         * meta informations.
1350         *
1351         * Now by calling this method the current raw audio wave data is checked
1352         * against the already stored CRC32 check sum in order to check whether the
1353         * sample data had been damaged unintentionally for some reason. Since by
1354         * calling this method always the entire raw audio wave data has to be
1355         * read, verifying all samples this way may take a long time accordingly.
1356         * And that's also the reason why the sample integrity is not checked by
1357         * default whenever a gig file is loaded. So this method must be called
1358         * explicitly to fulfill this task.
1359         *
1360         * @returns true if sample is OK or false if the sample is damaged
1361         * @throws Exception if no checksum had been stored to disk for this
1362         *         sample yet, or on I/O issues
1363         */
1364        bool Sample::VerifyWaveData() {
1365            File* pFile = static_cast<File*>(GetParent());
1366            const uint32_t referenceCRC = pFile->GetSampleChecksum(this);
1367            uint32_t crc = CalculateWaveDataChecksum();
1368            return crc == referenceCRC;
1369        }
1370    
1371        uint32_t Sample::CalculateWaveDataChecksum() {
1372            const size_t sz = 20*1024; // 20kB buffer size
1373            std::vector<uint8_t> buffer(sz);
1374            buffer.resize(sz);
1375    
1376            const size_t n = sz / FrameSize;
1377            SetPos(0);
1378            uint32_t crc = 0;
1379            __resetCRC(crc);
1380            while (true) {
1381                file_offset_t nRead = Read(&buffer[0], n);
1382                if (nRead <= 0) break;
1383                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1384            }
1385            __encodeCRC(crc);
1386            return crc;
1387        }
1388    
1389      Sample::~Sample() {      Sample::~Sample() {
1390          Instances--;          Instances--;
1391          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 991  namespace { Line 1402  namespace {
1402  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1403  // *  // *
1404    
1405      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1406      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1407    
1408      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1409          Instances++;          Instances++;
1410    
1411          memcpy(&Crossfade, &SamplerOptions, 4);          pSample = NULL;
1412            pRegion = pParent;
1413    
1414            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1415            else memset(&Crossfade, 0, 4);
1416    
1417          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1418    
1419          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1420          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1421          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1422          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1423          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1424          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1425          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1426          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1427          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1428          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1429          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1430          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1431          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1432          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1433          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1434          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1435          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1436          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1437          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1438          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1439          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1440          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1441          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1442          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1443          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1444          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1445          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1446          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1447          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1448          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1449          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1450          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1451          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1452          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1453          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1454          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1455          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1456          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1457          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1458          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1459          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1460          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1461          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1462          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1463          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1464          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1465          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1466          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1467          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1468          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1469          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1470          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1471              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1472              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1473          }                  VelocityResponseDepth = velocityresponse;
1474          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1475              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1476              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1477          }              } else if (velocityresponse < 15) {
1478          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1479              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1480              VelocityResponseDepth = velocityresponse - 10;              } else {
1481                    VelocityResponseCurve = curve_type_unknown;
1482                    VelocityResponseDepth = 0;
1483                }
1484                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1485                if (releasevelocityresponse < 5) {
1486                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1487                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1488                } else if (releasevelocityresponse < 10) {
1489                    ReleaseVelocityResponseCurve = curve_type_linear;
1490                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1491                } else if (releasevelocityresponse < 15) {
1492                    ReleaseVelocityResponseCurve = curve_type_special;
1493                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1494                } else {
1495                    ReleaseVelocityResponseCurve = curve_type_unknown;
1496                    ReleaseVelocityResponseDepth = 0;
1497                }
1498                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1499                AttenuationControllerThreshold = _3ewa->ReadInt8();
1500                _3ewa->ReadInt32(); // unknown
1501                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1502                _3ewa->ReadInt16(); // unknown
1503                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1504                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1505                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1506                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1507                else                                       DimensionBypass = dim_bypass_ctrl_none;
1508                uint8_t pan = _3ewa->ReadUint8();
1509                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1510                SelfMask = _3ewa->ReadInt8() & 0x01;
1511                _3ewa->ReadInt8(); // unknown
1512                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1513                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1514                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1515                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1516                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1517                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1518                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1519                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1520                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1521                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1522                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1523                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1524                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1525                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1526                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1527                                                            : vcf_res_ctrl_none;
1528                uint16_t eg3depth = _3ewa->ReadUint16();
1529                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1530                                            : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1531                _3ewa->ReadInt16(); // unknown
1532                ChannelOffset = _3ewa->ReadUint8() / 4;
1533                uint8_t regoptions = _3ewa->ReadUint8();
1534                MSDecode           = regoptions & 0x01; // bit 0
1535                SustainDefeat      = regoptions & 0x02; // bit 1
1536                _3ewa->ReadInt16(); // unknown
1537                VelocityUpperLimit = _3ewa->ReadInt8();
1538                _3ewa->ReadInt8(); // unknown
1539                _3ewa->ReadInt16(); // unknown
1540                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1541                _3ewa->ReadInt8(); // unknown
1542                _3ewa->ReadInt8(); // unknown
1543                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1544                uint8_t vcfcutoff = _3ewa->ReadUint8();
1545                VCFEnabled = vcfcutoff & 0x80; // bit 7
1546                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1547                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1548                uint8_t vcfvelscale = _3ewa->ReadUint8();
1549                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1550                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1551                _3ewa->ReadInt8(); // unknown
1552                uint8_t vcfresonance = _3ewa->ReadUint8();
1553                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1554                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1555                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1556                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1557                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1558                uint8_t vcfvelocity = _3ewa->ReadUint8();
1559                VCFVelocityDynamicRange = vcfvelocity % 5;
1560                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1561                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1562                if (VCFType == vcf_type_lowpass) {
1563                    if (lfo3ctrl & 0x40) // bit 6
1564                        VCFType = vcf_type_lowpassturbo;
1565                }
1566                if (_3ewa->RemainingBytes() >= 8) {
1567                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1568                } else {
1569                    memset(DimensionUpperLimits, 0, 8);
1570                }
1571            } else { // '3ewa' chunk does not exist yet
1572                // use default values
1573                LFO3Frequency                   = 1.0;
1574                EG3Attack                       = 0.0;
1575                LFO1InternalDepth               = 0;
1576                LFO3InternalDepth               = 0;
1577                LFO1ControlDepth                = 0;
1578                LFO3ControlDepth                = 0;
1579                EG1Attack                       = 0.0;
1580                EG1Decay1                       = 0.005;
1581                EG1Sustain                      = 1000;
1582                EG1Release                      = 0.3;
1583                EG1Controller.type              = eg1_ctrl_t::type_none;
1584                EG1Controller.controller_number = 0;
1585                EG1ControllerInvert             = false;
1586                EG1ControllerAttackInfluence    = 0;
1587                EG1ControllerDecayInfluence     = 0;
1588                EG1ControllerReleaseInfluence   = 0;
1589                EG2Controller.type              = eg2_ctrl_t::type_none;
1590                EG2Controller.controller_number = 0;
1591                EG2ControllerInvert             = false;
1592                EG2ControllerAttackInfluence    = 0;
1593                EG2ControllerDecayInfluence     = 0;
1594                EG2ControllerReleaseInfluence   = 0;
1595                LFO1Frequency                   = 1.0;
1596                EG2Attack                       = 0.0;
1597                EG2Decay1                       = 0.005;
1598                EG2Sustain                      = 1000;
1599                EG2Release                      = 0.3;
1600                LFO2ControlDepth                = 0;
1601                LFO2Frequency                   = 1.0;
1602                LFO2InternalDepth               = 0;
1603                EG1Decay2                       = 0.0;
1604                EG1InfiniteSustain              = true;
1605                EG1PreAttack                    = 0;
1606                EG2Decay2                       = 0.0;
1607                EG2InfiniteSustain              = true;
1608                EG2PreAttack                    = 0;
1609                VelocityResponseCurve           = curve_type_nonlinear;
1610                VelocityResponseDepth           = 3;
1611                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1612                ReleaseVelocityResponseDepth    = 3;
1613                VelocityResponseCurveScaling    = 32;
1614                AttenuationControllerThreshold  = 0;
1615                SampleStartOffset               = 0;
1616                PitchTrack                      = true;
1617                DimensionBypass                 = dim_bypass_ctrl_none;
1618                Pan                             = 0;
1619                SelfMask                        = true;
1620                LFO3Controller                  = lfo3_ctrl_modwheel;
1621                LFO3Sync                        = false;
1622                InvertAttenuationController     = false;
1623                AttenuationController.type      = attenuation_ctrl_t::type_none;
1624                AttenuationController.controller_number = 0;
1625                LFO2Controller                  = lfo2_ctrl_internal;
1626                LFO2FlipPhase                   = false;
1627                LFO2Sync                        = false;
1628                LFO1Controller                  = lfo1_ctrl_internal;
1629                LFO1FlipPhase                   = false;
1630                LFO1Sync                        = false;
1631                VCFResonanceController          = vcf_res_ctrl_none;
1632                EG3Depth                        = 0;
1633                ChannelOffset                   = 0;
1634                MSDecode                        = false;
1635                SustainDefeat                   = false;
1636                VelocityUpperLimit              = 0;
1637                ReleaseTriggerDecay             = 0;
1638                EG1Hold                         = false;
1639                VCFEnabled                      = false;
1640                VCFCutoff                       = 0;
1641                VCFCutoffController             = vcf_cutoff_ctrl_none;
1642                VCFCutoffControllerInvert       = false;
1643                VCFVelocityScale                = 0;
1644                VCFResonance                    = 0;
1645                VCFResonanceDynamic             = false;
1646                VCFKeyboardTracking             = false;
1647                VCFKeyboardTrackingBreakpoint   = 0;
1648                VCFVelocityDynamicRange         = 0x04;
1649                VCFVelocityCurve                = curve_type_linear;
1650                VCFType                         = vcf_type_lowpass;
1651                memset(DimensionUpperLimits, 127, 8);
1652          }          }
1653          else {  
1654              VelocityResponseCurve = curve_type_unknown;          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1655              VelocityResponseDepth = 0;                                                       VelocityResponseDepth,
1656                                                         VelocityResponseCurveScaling);
1657    
1658            pVelocityReleaseTable = GetReleaseVelocityTable(
1659                                        ReleaseVelocityResponseCurve,
1660                                        ReleaseVelocityResponseDepth
1661                                    );
1662    
1663            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1664                                                          VCFVelocityDynamicRange,
1665                                                          VCFVelocityScale,
1666                                                          VCFCutoffController);
1667    
1668            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1669            VelocityTable = 0;
1670        }
1671    
1672        /*
1673         * Constructs a DimensionRegion by copying all parameters from
1674         * another DimensionRegion
1675         */
1676        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1677            Instances++;
1678            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1679            *this = src; // default memberwise shallow copy of all parameters
1680            pParentList = _3ewl; // restore the chunk pointer
1681    
1682            // deep copy of owned structures
1683            if (src.VelocityTable) {
1684                VelocityTable = new uint8_t[128];
1685                for (int k = 0 ; k < 128 ; k++)
1686                    VelocityTable[k] = src.VelocityTable[k];
1687            }
1688            if (src.pSampleLoops) {
1689                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1690                for (int k = 0 ; k < src.SampleLoops ; k++)
1691                    pSampleLoops[k] = src.pSampleLoops[k];
1692          }          }
1693          uint8_t releasevelocityresponse = _3ewa->ReadUint8();      }
1694          if (releasevelocityresponse < 5) {      
1695              ReleaseVelocityResponseCurve = curve_type_nonlinear;      /**
1696              ReleaseVelocityResponseDepth = releasevelocityresponse;       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1697          }       * and assign it to this object.
1698          else if (releasevelocityresponse < 10) {       *
1699              ReleaseVelocityResponseCurve = curve_type_linear;       * Note that all sample pointers referenced by @a orig are simply copied as
1700              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;       * memory address. Thus the respective samples are shared, not duplicated!
1701          }       *
1702          else if (releasevelocityresponse < 15) {       * @param orig - original DimensionRegion object to be copied from
1703              ReleaseVelocityResponseCurve = curve_type_special;       */
1704              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;      void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1705            CopyAssign(orig, NULL);
1706        }
1707    
1708        /**
1709         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1710         * and assign it to this object.
1711         *
1712         * @param orig - original DimensionRegion object to be copied from
1713         * @param mSamples - crosslink map between the foreign file's samples and
1714         *                   this file's samples
1715         */
1716        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1717            // delete all allocated data first
1718            if (VelocityTable) delete [] VelocityTable;
1719            if (pSampleLoops) delete [] pSampleLoops;
1720            
1721            // backup parent list pointer
1722            RIFF::List* p = pParentList;
1723            
1724            gig::Sample* pOriginalSample = pSample;
1725            gig::Region* pOriginalRegion = pRegion;
1726            
1727            //NOTE: copy code copied from assignment constructor above, see comment there as well
1728            
1729            *this = *orig; // default memberwise shallow copy of all parameters
1730            
1731            // restore members that shall not be altered
1732            pParentList = p; // restore the chunk pointer
1733            pRegion = pOriginalRegion;
1734            
1735            // only take the raw sample reference reference if the
1736            // two DimensionRegion objects are part of the same file
1737            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1738                pSample = pOriginalSample;
1739            }
1740            
1741            if (mSamples && mSamples->count(orig->pSample)) {
1742                pSample = mSamples->find(orig->pSample)->second;
1743            }
1744    
1745            // deep copy of owned structures
1746            if (orig->VelocityTable) {
1747                VelocityTable = new uint8_t[128];
1748                for (int k = 0 ; k < 128 ; k++)
1749                    VelocityTable[k] = orig->VelocityTable[k];
1750            }
1751            if (orig->pSampleLoops) {
1752                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1753                for (int k = 0 ; k < orig->SampleLoops ; k++)
1754                    pSampleLoops[k] = orig->pSampleLoops[k];
1755          }          }
1756          else {      }
1757              ReleaseVelocityResponseCurve = curve_type_unknown;  
1758              ReleaseVelocityResponseDepth = 0;      /**
1759         * Updates the respective member variable and updates @c SampleAttenuation
1760         * which depends on this value.
1761         */
1762        void DimensionRegion::SetGain(int32_t gain) {
1763            DLS::Sampler::SetGain(gain);
1764            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1765        }
1766    
1767        /**
1768         * Apply dimension region settings to the respective RIFF chunks. You
1769         * have to call File::Save() to make changes persistent.
1770         *
1771         * Usually there is absolutely no need to call this method explicitly.
1772         * It will be called automatically when File::Save() was called.
1773         *
1774         * @param pProgress - callback function for progress notification
1775         */
1776        void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1777            // first update base class's chunk
1778            DLS::Sampler::UpdateChunks(pProgress);
1779    
1780            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1781            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1782            pData[12] = Crossfade.in_start;
1783            pData[13] = Crossfade.in_end;
1784            pData[14] = Crossfade.out_start;
1785            pData[15] = Crossfade.out_end;
1786    
1787            // make sure '3ewa' chunk exists
1788            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1789            if (!_3ewa) {
1790                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1791                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1792                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1793          }          }
1794          VelocityResponseCurveScaling = _3ewa->ReadUint8();          pData = (uint8_t*) _3ewa->LoadChunkData();
1795          AttenuationControllerThreshold = _3ewa->ReadInt8();  
1796          _3ewa->ReadInt32(); // unknown          // update '3ewa' chunk with DimensionRegion's current settings
1797          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1798          _3ewa->ReadInt16(); // unknown          const uint32_t chunksize = _3ewa->GetNewSize();
1799          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          store32(&pData[0], chunksize); // unknown, always chunk size?
1800          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1801          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1802          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          store32(&pData[4], lfo3freq);
1803          else                                       DimensionBypass = dim_bypass_ctrl_none;  
1804          uint8_t pan = _3ewa->ReadUint8();          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1805          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit          store32(&pData[8], eg3attack);
1806          SelfMask = _3ewa->ReadInt8() & 0x01;  
1807          _3ewa->ReadInt8(); // unknown          // next 2 bytes unknown
1808          uint8_t lfo3ctrl = _3ewa->ReadUint8();  
1809          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          store16(&pData[14], LFO1InternalDepth);
1810          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
1811          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          // next 2 bytes unknown
1812          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
1813          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          store16(&pData[18], LFO3InternalDepth);
1814          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
1815          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7          // next 2 bytes unknown
1816          LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
1817          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6          store16(&pData[22], LFO1ControlDepth);
1818          uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
1819          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits          // next 2 bytes unknown
1820          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
1821          LFO1Sync               = lfo1ctrl & 0x40; // bit 6          store16(&pData[26], LFO3ControlDepth);
1822          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
1823                                                      : vcf_res_ctrl_none;          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1824          uint16_t eg3depth = _3ewa->ReadUint16();          store32(&pData[28], eg1attack);
1825          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
1826                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1827          _3ewa->ReadInt16(); // unknown          store32(&pData[32], eg1decay1);
1828          ChannelOffset = _3ewa->ReadUint8() / 4;  
1829          uint8_t regoptions = _3ewa->ReadUint8();          // next 2 bytes unknown
1830          MSDecode           = regoptions & 0x01; // bit 0  
1831          SustainDefeat      = regoptions & 0x02; // bit 1          store16(&pData[38], EG1Sustain);
1832          _3ewa->ReadInt16(); // unknown  
1833          VelocityUpperLimit = _3ewa->ReadInt8();          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1834          _3ewa->ReadInt8(); // unknown          store32(&pData[40], eg1release);
1835          _3ewa->ReadInt16(); // unknown  
1836          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1837          _3ewa->ReadInt8(); // unknown          pData[44] = eg1ctl;
1838          _3ewa->ReadInt8(); // unknown  
1839          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7          const uint8_t eg1ctrloptions =
1840          uint8_t vcfcutoff = _3ewa->ReadUint8();              (EG1ControllerInvert ? 0x01 : 0x00) |
1841          VCFEnabled = vcfcutoff & 0x80; // bit 7              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1842          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1843          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1844          VCFVelocityScale = _3ewa->ReadUint8();          pData[45] = eg1ctrloptions;
1845          _3ewa->ReadInt8(); // unknown  
1846          uint8_t vcfresonance = _3ewa->ReadUint8();          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1847          VCFResonance = vcfresonance & 0x7f; // lower 7 bits          pData[46] = eg2ctl;
1848          VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
1849          uint8_t vcfbreakpoint         = _3ewa->ReadUint8();          const uint8_t eg2ctrloptions =
1850          VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7              (EG2ControllerInvert ? 0x01 : 0x00) |
1851          VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1852          uint8_t vcfvelocity = _3ewa->ReadUint8();              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1853          VCFVelocityDynamicRange = vcfvelocity % 5;              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1854          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);          pData[47] = eg2ctrloptions;
1855          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
1856          if (VCFType == vcf_type_lowpass) {          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1857              if (lfo3ctrl & 0x40) // bit 6          store32(&pData[48], lfo1freq);
1858                  VCFType = vcf_type_lowpassturbo;  
1859            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1860            store32(&pData[52], eg2attack);
1861    
1862            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1863            store32(&pData[56], eg2decay1);
1864    
1865            // next 2 bytes unknown
1866    
1867            store16(&pData[62], EG2Sustain);
1868    
1869            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1870            store32(&pData[64], eg2release);
1871    
1872            // next 2 bytes unknown
1873    
1874            store16(&pData[70], LFO2ControlDepth);
1875    
1876            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1877            store32(&pData[72], lfo2freq);
1878    
1879            // next 2 bytes unknown
1880    
1881            store16(&pData[78], LFO2InternalDepth);
1882    
1883            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1884            store32(&pData[80], eg1decay2);
1885    
1886            // next 2 bytes unknown
1887    
1888            store16(&pData[86], EG1PreAttack);
1889    
1890            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1891            store32(&pData[88], eg2decay2);
1892    
1893            // next 2 bytes unknown
1894    
1895            store16(&pData[94], EG2PreAttack);
1896    
1897            {
1898                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1899                uint8_t velocityresponse = VelocityResponseDepth;
1900                switch (VelocityResponseCurve) {
1901                    case curve_type_nonlinear:
1902                        break;
1903                    case curve_type_linear:
1904                        velocityresponse += 5;
1905                        break;
1906                    case curve_type_special:
1907                        velocityresponse += 10;
1908                        break;
1909                    case curve_type_unknown:
1910                    default:
1911                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1912                }
1913                pData[96] = velocityresponse;
1914          }          }
1915    
1916          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          {
1917                                                       VelocityResponseDepth,              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1918                                                       VelocityResponseCurveScaling);              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1919                switch (ReleaseVelocityResponseCurve) {
1920                    case curve_type_nonlinear:
1921                        break;
1922                    case curve_type_linear:
1923                        releasevelocityresponse += 5;
1924                        break;
1925                    case curve_type_special:
1926                        releasevelocityresponse += 10;
1927                        break;
1928                    case curve_type_unknown:
1929                    default:
1930                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1931                }
1932                pData[97] = releasevelocityresponse;
1933            }
1934    
1935            pData[98] = VelocityResponseCurveScaling;
1936    
1937            pData[99] = AttenuationControllerThreshold;
1938    
1939            // next 4 bytes unknown
1940    
1941            store16(&pData[104], SampleStartOffset);
1942    
1943            // next 2 bytes unknown
1944    
1945            {
1946                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1947                switch (DimensionBypass) {
1948                    case dim_bypass_ctrl_94:
1949                        pitchTrackDimensionBypass |= 0x10;
1950                        break;
1951                    case dim_bypass_ctrl_95:
1952                        pitchTrackDimensionBypass |= 0x20;
1953                        break;
1954                    case dim_bypass_ctrl_none:
1955                        //FIXME: should we set anything here?
1956                        break;
1957                    default:
1958                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1959                }
1960                pData[108] = pitchTrackDimensionBypass;
1961            }
1962    
1963            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1964            pData[109] = pan;
1965    
1966            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1967            pData[110] = selfmask;
1968    
1969            // next byte unknown
1970    
1971            {
1972                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1973                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1974                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1975                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1976                pData[112] = lfo3ctrl;
1977            }
1978    
1979            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1980            pData[113] = attenctl;
1981    
1982            {
1983                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1984                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1985                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1986                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1987                pData[114] = lfo2ctrl;
1988            }
1989    
1990            {
1991                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1992                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1993                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1994                if (VCFResonanceController != vcf_res_ctrl_none)
1995                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1996                pData[115] = lfo1ctrl;
1997            }
1998    
1999            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2000                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2001            store16(&pData[116], eg3depth);
2002    
2003            // next 2 bytes unknown
2004    
2005            const uint8_t channeloffset = ChannelOffset * 4;
2006            pData[120] = channeloffset;
2007    
2008            {
2009                uint8_t regoptions = 0;
2010                if (MSDecode)      regoptions |= 0x01; // bit 0
2011                if (SustainDefeat) regoptions |= 0x02; // bit 1
2012                pData[121] = regoptions;
2013            }
2014    
2015            // next 2 bytes unknown
2016    
2017            pData[124] = VelocityUpperLimit;
2018    
2019            // next 3 bytes unknown
2020    
2021            pData[128] = ReleaseTriggerDecay;
2022    
2023            // next 2 bytes unknown
2024    
2025            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2026            pData[131] = eg1hold;
2027    
2028            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2029                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
2030            pData[132] = vcfcutoff;
2031    
2032            pData[133] = VCFCutoffController;
2033    
2034            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2035                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
2036            pData[134] = vcfvelscale;
2037    
2038            // next byte unknown
2039    
2040          curve_type_t curveType = ReleaseVelocityResponseCurve;          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2041          uint8_t depth = ReleaseVelocityResponseDepth;                                       (VCFResonance & 0x7f); /* lower 7 bits */
2042            pData[136] = vcfresonance;
2043    
2044            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2045                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2046            pData[137] = vcfbreakpoint;
2047    
2048            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2049                                        VCFVelocityCurve * 5;
2050            pData[138] = vcfvelocity;
2051    
2052            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2053            pData[139] = vcftype;
2054    
2055            if (chunksize >= 148) {
2056                memcpy(&pData[140], DimensionUpperLimits, 8);
2057            }
2058        }
2059    
2060        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2061            curve_type_t curveType = releaseVelocityResponseCurve;
2062            uint8_t depth = releaseVelocityResponseDepth;
2063          // this models a strange behaviour or bug in GSt: two of the          // this models a strange behaviour or bug in GSt: two of the
2064          // velocity response curves for release time are not used even          // velocity response curves for release time are not used even
2065          // if specified, instead another curve is chosen.          // if specified, instead another curve is chosen.
   
2066          if ((curveType == curve_type_nonlinear && depth == 0) ||          if ((curveType == curve_type_nonlinear && depth == 0) ||
2067              (curveType == curve_type_special   && depth == 4)) {              (curveType == curve_type_special   && depth == 4)) {
2068              curveType = curve_type_nonlinear;              curveType = curve_type_nonlinear;
2069              depth = 3;              depth = 3;
2070          }          }
2071          pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);          return GetVelocityTable(curveType, depth, 0);
2072        }
2073    
2074          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));      double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2075                                                        uint8_t vcfVelocityDynamicRange,
2076                                                        uint8_t vcfVelocityScale,
2077                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2078        {
2079            curve_type_t curveType = vcfVelocityCurve;
2080            uint8_t depth = vcfVelocityDynamicRange;
2081            // even stranger GSt: two of the velocity response curves for
2082            // filter cutoff are not used, instead another special curve
2083            // is chosen. This curve is not used anywhere else.
2084            if ((curveType == curve_type_nonlinear && depth == 0) ||
2085                (curveType == curve_type_special   && depth == 4)) {
2086                curveType = curve_type_special;
2087                depth = 5;
2088            }
2089            return GetVelocityTable(curveType, depth,
2090                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2091                                        ? vcfVelocityScale : 0);
2092      }      }
2093    
2094      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
# Line 1187  namespace { Line 2106  namespace {
2106          return table;          return table;
2107      }      }
2108    
2109        Region* DimensionRegion::GetParent() const {
2110            return pRegion;
2111        }
2112    
2113    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2114    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2115    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2116    //#pragma GCC diagnostic push
2117    //#pragma GCC diagnostic error "-Wswitch"
2118    
2119      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2120          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2121          switch (EncodedController) {          switch (EncodedController) {
# Line 1298  namespace { Line 2227  namespace {
2227                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2228                  break;                  break;
2229    
2230                // format extension (these controllers are so far only supported by
2231                // LinuxSampler & gigedit) they will *NOT* work with
2232                // Gigasampler/GigaStudio !
2233                case _lev_ctrl_CC3_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 3;
2236                    break;
2237                case _lev_ctrl_CC6_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 6;
2240                    break;
2241                case _lev_ctrl_CC7_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 7;
2244                    break;
2245                case _lev_ctrl_CC8_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 8;
2248                    break;
2249                case _lev_ctrl_CC9_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 9;
2252                    break;
2253                case _lev_ctrl_CC10_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 10;
2256                    break;
2257                case _lev_ctrl_CC11_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 11;
2260                    break;
2261                case _lev_ctrl_CC14_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 14;
2264                    break;
2265                case _lev_ctrl_CC15_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 15;
2268                    break;
2269                case _lev_ctrl_CC20_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 20;
2272                    break;
2273                case _lev_ctrl_CC21_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 21;
2276                    break;
2277                case _lev_ctrl_CC22_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 22;
2280                    break;
2281                case _lev_ctrl_CC23_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 23;
2284                    break;
2285                case _lev_ctrl_CC24_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 24;
2288                    break;
2289                case _lev_ctrl_CC25_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 25;
2292                    break;
2293                case _lev_ctrl_CC26_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 26;
2296                    break;
2297                case _lev_ctrl_CC27_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 27;
2300                    break;
2301                case _lev_ctrl_CC28_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 28;
2304                    break;
2305                case _lev_ctrl_CC29_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 29;
2308                    break;
2309                case _lev_ctrl_CC30_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 30;
2312                    break;
2313                case _lev_ctrl_CC31_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 31;
2316                    break;
2317                case _lev_ctrl_CC68_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 68;
2320                    break;
2321                case _lev_ctrl_CC69_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 69;
2324                    break;
2325                case _lev_ctrl_CC70_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 70;
2328                    break;
2329                case _lev_ctrl_CC71_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 71;
2332                    break;
2333                case _lev_ctrl_CC72_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 72;
2336                    break;
2337                case _lev_ctrl_CC73_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 73;
2340                    break;
2341                case _lev_ctrl_CC74_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 74;
2344                    break;
2345                case _lev_ctrl_CC75_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 75;
2348                    break;
2349                case _lev_ctrl_CC76_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 76;
2352                    break;
2353                case _lev_ctrl_CC77_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 77;
2356                    break;
2357                case _lev_ctrl_CC78_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 78;
2360                    break;
2361                case _lev_ctrl_CC79_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 79;
2364                    break;
2365                case _lev_ctrl_CC84_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 84;
2368                    break;
2369                case _lev_ctrl_CC85_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 85;
2372                    break;
2373                case _lev_ctrl_CC86_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 86;
2376                    break;
2377                case _lev_ctrl_CC87_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 87;
2380                    break;
2381                case _lev_ctrl_CC89_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 89;
2384                    break;
2385                case _lev_ctrl_CC90_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 90;
2388                    break;
2389                case _lev_ctrl_CC96_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 96;
2392                    break;
2393                case _lev_ctrl_CC97_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 97;
2396                    break;
2397                case _lev_ctrl_CC102_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 102;
2400                    break;
2401                case _lev_ctrl_CC103_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 103;
2404                    break;
2405                case _lev_ctrl_CC104_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 104;
2408                    break;
2409                case _lev_ctrl_CC105_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 105;
2412                    break;
2413                case _lev_ctrl_CC106_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 106;
2416                    break;
2417                case _lev_ctrl_CC107_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 107;
2420                    break;
2421                case _lev_ctrl_CC108_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 108;
2424                    break;
2425                case _lev_ctrl_CC109_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 109;
2428                    break;
2429                case _lev_ctrl_CC110_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 110;
2432                    break;
2433                case _lev_ctrl_CC111_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 111;
2436                    break;
2437                case _lev_ctrl_CC112_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 112;
2440                    break;
2441                case _lev_ctrl_CC113_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 113;
2444                    break;
2445                case _lev_ctrl_CC114_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 114;
2448                    break;
2449                case _lev_ctrl_CC115_EXT:
2450                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2451                    decodedcontroller.controller_number = 115;
2452                    break;
2453                case _lev_ctrl_CC116_EXT:
2454                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2455                    decodedcontroller.controller_number = 116;
2456                    break;
2457                case _lev_ctrl_CC117_EXT:
2458                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2459                    decodedcontroller.controller_number = 117;
2460                    break;
2461                case _lev_ctrl_CC118_EXT:
2462                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2463                    decodedcontroller.controller_number = 118;
2464                    break;
2465                case _lev_ctrl_CC119_EXT:
2466                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2467                    decodedcontroller.controller_number = 119;
2468                    break;
2469    
2470              // unknown controller type              // unknown controller type
2471              default:              default:
2472                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2473          }          }
2474          return decodedcontroller;          return decodedcontroller;
2475      }      }
2476        
2477    // see above (diagnostic push not supported prior GCC 4.6)
2478    //#pragma GCC diagnostic pop
2479    
2480        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2481            _lev_ctrl_t encodedcontroller;
2482            switch (DecodedController.type) {
2483                // special controller
2484                case leverage_ctrl_t::type_none:
2485                    encodedcontroller = _lev_ctrl_none;
2486                    break;
2487                case leverage_ctrl_t::type_velocity:
2488                    encodedcontroller = _lev_ctrl_velocity;
2489                    break;
2490                case leverage_ctrl_t::type_channelaftertouch:
2491                    encodedcontroller = _lev_ctrl_channelaftertouch;
2492                    break;
2493    
2494                // ordinary MIDI control change controller
2495                case leverage_ctrl_t::type_controlchange:
2496                    switch (DecodedController.controller_number) {
2497                        case 1:
2498                            encodedcontroller = _lev_ctrl_modwheel;
2499                            break;
2500                        case 2:
2501                            encodedcontroller = _lev_ctrl_breath;
2502                            break;
2503                        case 4:
2504                            encodedcontroller = _lev_ctrl_foot;
2505                            break;
2506                        case 12:
2507                            encodedcontroller = _lev_ctrl_effect1;
2508                            break;
2509                        case 13:
2510                            encodedcontroller = _lev_ctrl_effect2;
2511                            break;
2512                        case 16:
2513                            encodedcontroller = _lev_ctrl_genpurpose1;
2514                            break;
2515                        case 17:
2516                            encodedcontroller = _lev_ctrl_genpurpose2;
2517                            break;
2518                        case 18:
2519                            encodedcontroller = _lev_ctrl_genpurpose3;
2520                            break;
2521                        case 19:
2522                            encodedcontroller = _lev_ctrl_genpurpose4;
2523                            break;
2524                        case 5:
2525                            encodedcontroller = _lev_ctrl_portamentotime;
2526                            break;
2527                        case 64:
2528                            encodedcontroller = _lev_ctrl_sustainpedal;
2529                            break;
2530                        case 65:
2531                            encodedcontroller = _lev_ctrl_portamento;
2532                            break;
2533                        case 66:
2534                            encodedcontroller = _lev_ctrl_sostenutopedal;
2535                            break;
2536                        case 67:
2537                            encodedcontroller = _lev_ctrl_softpedal;
2538                            break;
2539                        case 80:
2540                            encodedcontroller = _lev_ctrl_genpurpose5;
2541                            break;
2542                        case 81:
2543                            encodedcontroller = _lev_ctrl_genpurpose6;
2544                            break;
2545                        case 82:
2546                            encodedcontroller = _lev_ctrl_genpurpose7;
2547                            break;
2548                        case 83:
2549                            encodedcontroller = _lev_ctrl_genpurpose8;
2550                            break;
2551                        case 91:
2552                            encodedcontroller = _lev_ctrl_effect1depth;
2553                            break;
2554                        case 92:
2555                            encodedcontroller = _lev_ctrl_effect2depth;
2556                            break;
2557                        case 93:
2558                            encodedcontroller = _lev_ctrl_effect3depth;
2559                            break;
2560                        case 94:
2561                            encodedcontroller = _lev_ctrl_effect4depth;
2562                            break;
2563                        case 95:
2564                            encodedcontroller = _lev_ctrl_effect5depth;
2565                            break;
2566    
2567                        // format extension (these controllers are so far only
2568                        // supported by LinuxSampler & gigedit) they will *NOT*
2569                        // work with Gigasampler/GigaStudio !
2570                        case 3:
2571                            encodedcontroller = _lev_ctrl_CC3_EXT;
2572                            break;
2573                        case 6:
2574                            encodedcontroller = _lev_ctrl_CC6_EXT;
2575                            break;
2576                        case 7:
2577                            encodedcontroller = _lev_ctrl_CC7_EXT;
2578                            break;
2579                        case 8:
2580                            encodedcontroller = _lev_ctrl_CC8_EXT;
2581                            break;
2582                        case 9:
2583                            encodedcontroller = _lev_ctrl_CC9_EXT;
2584                            break;
2585                        case 10:
2586                            encodedcontroller = _lev_ctrl_CC10_EXT;
2587                            break;
2588                        case 11:
2589                            encodedcontroller = _lev_ctrl_CC11_EXT;
2590                            break;
2591                        case 14:
2592                            encodedcontroller = _lev_ctrl_CC14_EXT;
2593                            break;
2594                        case 15:
2595                            encodedcontroller = _lev_ctrl_CC15_EXT;
2596                            break;
2597                        case 20:
2598                            encodedcontroller = _lev_ctrl_CC20_EXT;
2599                            break;
2600                        case 21:
2601                            encodedcontroller = _lev_ctrl_CC21_EXT;
2602                            break;
2603                        case 22:
2604                            encodedcontroller = _lev_ctrl_CC22_EXT;
2605                            break;
2606                        case 23:
2607                            encodedcontroller = _lev_ctrl_CC23_EXT;
2608                            break;
2609                        case 24:
2610                            encodedcontroller = _lev_ctrl_CC24_EXT;
2611                            break;
2612                        case 25:
2613                            encodedcontroller = _lev_ctrl_CC25_EXT;
2614                            break;
2615                        case 26:
2616                            encodedcontroller = _lev_ctrl_CC26_EXT;
2617                            break;
2618                        case 27:
2619                            encodedcontroller = _lev_ctrl_CC27_EXT;
2620                            break;
2621                        case 28:
2622                            encodedcontroller = _lev_ctrl_CC28_EXT;
2623                            break;
2624                        case 29:
2625                            encodedcontroller = _lev_ctrl_CC29_EXT;
2626                            break;
2627                        case 30:
2628                            encodedcontroller = _lev_ctrl_CC30_EXT;
2629                            break;
2630                        case 31:
2631                            encodedcontroller = _lev_ctrl_CC31_EXT;
2632                            break;
2633                        case 68:
2634                            encodedcontroller = _lev_ctrl_CC68_EXT;
2635                            break;
2636                        case 69:
2637                            encodedcontroller = _lev_ctrl_CC69_EXT;
2638                            break;
2639                        case 70:
2640                            encodedcontroller = _lev_ctrl_CC70_EXT;
2641                            break;
2642                        case 71:
2643                            encodedcontroller = _lev_ctrl_CC71_EXT;
2644                            break;
2645                        case 72:
2646                            encodedcontroller = _lev_ctrl_CC72_EXT;
2647                            break;
2648                        case 73:
2649                            encodedcontroller = _lev_ctrl_CC73_EXT;
2650                            break;
2651                        case 74:
2652                            encodedcontroller = _lev_ctrl_CC74_EXT;
2653                            break;
2654                        case 75:
2655                            encodedcontroller = _lev_ctrl_CC75_EXT;
2656                            break;
2657                        case 76:
2658                            encodedcontroller = _lev_ctrl_CC76_EXT;
2659                            break;
2660                        case 77:
2661                            encodedcontroller = _lev_ctrl_CC77_EXT;
2662                            break;
2663                        case 78:
2664                            encodedcontroller = _lev_ctrl_CC78_EXT;
2665                            break;
2666                        case 79:
2667                            encodedcontroller = _lev_ctrl_CC79_EXT;
2668                            break;
2669                        case 84:
2670                            encodedcontroller = _lev_ctrl_CC84_EXT;
2671                            break;
2672                        case 85:
2673                            encodedcontroller = _lev_ctrl_CC85_EXT;
2674                            break;
2675                        case 86:
2676                            encodedcontroller = _lev_ctrl_CC86_EXT;
2677                            break;
2678                        case 87:
2679                            encodedcontroller = _lev_ctrl_CC87_EXT;
2680                            break;
2681                        case 89:
2682                            encodedcontroller = _lev_ctrl_CC89_EXT;
2683                            break;
2684                        case 90:
2685                            encodedcontroller = _lev_ctrl_CC90_EXT;
2686                            break;
2687                        case 96:
2688                            encodedcontroller = _lev_ctrl_CC96_EXT;
2689                            break;
2690                        case 97:
2691                            encodedcontroller = _lev_ctrl_CC97_EXT;
2692                            break;
2693                        case 102:
2694                            encodedcontroller = _lev_ctrl_CC102_EXT;
2695                            break;
2696                        case 103:
2697                            encodedcontroller = _lev_ctrl_CC103_EXT;
2698                            break;
2699                        case 104:
2700                            encodedcontroller = _lev_ctrl_CC104_EXT;
2701                            break;
2702                        case 105:
2703                            encodedcontroller = _lev_ctrl_CC105_EXT;
2704                            break;
2705                        case 106:
2706                            encodedcontroller = _lev_ctrl_CC106_EXT;
2707                            break;
2708                        case 107:
2709                            encodedcontroller = _lev_ctrl_CC107_EXT;
2710                            break;
2711                        case 108:
2712                            encodedcontroller = _lev_ctrl_CC108_EXT;
2713                            break;
2714                        case 109:
2715                            encodedcontroller = _lev_ctrl_CC109_EXT;
2716                            break;
2717                        case 110:
2718                            encodedcontroller = _lev_ctrl_CC110_EXT;
2719                            break;
2720                        case 111:
2721                            encodedcontroller = _lev_ctrl_CC111_EXT;
2722                            break;
2723                        case 112:
2724                            encodedcontroller = _lev_ctrl_CC112_EXT;
2725                            break;
2726                        case 113:
2727                            encodedcontroller = _lev_ctrl_CC113_EXT;
2728                            break;
2729                        case 114:
2730                            encodedcontroller = _lev_ctrl_CC114_EXT;
2731                            break;
2732                        case 115:
2733                            encodedcontroller = _lev_ctrl_CC115_EXT;
2734                            break;
2735                        case 116:
2736                            encodedcontroller = _lev_ctrl_CC116_EXT;
2737                            break;
2738                        case 117:
2739                            encodedcontroller = _lev_ctrl_CC117_EXT;
2740                            break;
2741                        case 118:
2742                            encodedcontroller = _lev_ctrl_CC118_EXT;
2743                            break;
2744                        case 119:
2745                            encodedcontroller = _lev_ctrl_CC119_EXT;
2746                            break;
2747    
2748                        default:
2749                            throw gig::Exception("leverage controller number is not supported by the gig format");
2750                    }
2751                    break;
2752                default:
2753                    throw gig::Exception("Unknown leverage controller type.");
2754            }
2755            return encodedcontroller;
2756        }
2757    
2758      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
2759          Instances--;          Instances--;
# Line 1318  namespace { Line 2768  namespace {
2768              delete pVelocityTables;              delete pVelocityTables;
2769              pVelocityTables = NULL;              pVelocityTables = NULL;
2770          }          }
2771            if (VelocityTable) delete[] VelocityTable;
2772      }      }
2773    
2774      /**      /**
# Line 1339  namespace { Line 2790  namespace {
2790          return pVelocityReleaseTable[MIDIKeyVelocity];          return pVelocityReleaseTable[MIDIKeyVelocity];
2791      }      }
2792    
2793        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2794            return pVelocityCutoffTable[MIDIKeyVelocity];
2795        }
2796    
2797        /**
2798         * Updates the respective member variable and the lookup table / cache
2799         * that depends on this value.
2800         */
2801        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2802            pVelocityAttenuationTable =
2803                GetVelocityTable(
2804                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2805                );
2806            VelocityResponseCurve = curve;
2807        }
2808    
2809        /**
2810         * Updates the respective member variable and the lookup table / cache
2811         * that depends on this value.
2812         */
2813        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2814            pVelocityAttenuationTable =
2815                GetVelocityTable(
2816                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2817                );
2818            VelocityResponseDepth = depth;
2819        }
2820    
2821        /**
2822         * Updates the respective member variable and the lookup table / cache
2823         * that depends on this value.
2824         */
2825        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2826            pVelocityAttenuationTable =
2827                GetVelocityTable(
2828                    VelocityResponseCurve, VelocityResponseDepth, scaling
2829                );
2830            VelocityResponseCurveScaling = scaling;
2831        }
2832    
2833        /**
2834         * Updates the respective member variable and the lookup table / cache
2835         * that depends on this value.
2836         */
2837        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2838            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2839            ReleaseVelocityResponseCurve = curve;
2840        }
2841    
2842        /**
2843         * Updates the respective member variable and the lookup table / cache
2844         * that depends on this value.
2845         */
2846        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2847            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2848            ReleaseVelocityResponseDepth = depth;
2849        }
2850    
2851        /**
2852         * Updates the respective member variable and the lookup table / cache
2853         * that depends on this value.
2854         */
2855        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2856            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2857            VCFCutoffController = controller;
2858        }
2859    
2860        /**
2861         * Updates the respective member variable and the lookup table / cache
2862         * that depends on this value.
2863         */
2864        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2865            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2866            VCFVelocityCurve = curve;
2867        }
2868    
2869        /**
2870         * Updates the respective member variable and the lookup table / cache
2871         * that depends on this value.
2872         */
2873        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2874            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2875            VCFVelocityDynamicRange = range;
2876        }
2877    
2878        /**
2879         * Updates the respective member variable and the lookup table / cache
2880         * that depends on this value.
2881         */
2882        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2883            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2884            VCFVelocityScale = scaling;
2885        }
2886    
2887      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2888    
2889          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1372  namespace { Line 2917  namespace {
2917          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2918                               127, 127 };                               127, 127 };
2919    
2920            // this is only used by the VCF velocity curve
2921            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2922                                 91, 127, 127, 127 };
2923    
2924          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2925                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2926                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2927    
2928          double* const table = new double[128];          double* const table = new double[128];
2929    
# Line 1418  namespace { Line 2967  namespace {
2967    
2968          // Actual Loading          // Actual Loading
2969    
2970            if (!file->GetAutoLoad()) return;
2971    
2972          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2973    
2974          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 1426  namespace { Line 2977  namespace {
2977              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2978                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2979                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2980                    _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2981                    _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2982                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2983                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2984                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2985                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2986                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2987                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2988                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2989                  }                  }
2990                  else { // active dimension                  else { // active dimension
2991                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2992                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2993                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2994                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2995                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2996                      Dimensions++;                      Dimensions++;
2997    
2998                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2999                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
3000                  }                  }
3001                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
3002              }              }
3003                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
3004    
3005              // check velocity dimension (if there is one) for custom defined zone ranges              // if there's a velocity dimension and custom velocity zone splits are used,
3006              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
3007                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
                 if (pDimDef->dimension == dimension_velocity) {  
                     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {  
                         // no custom defined ranges  
                         pDimDef->split_type = split_type_normal;  
                         pDimDef->ranges     = NULL;  
                     }  
                     else { // custom defined ranges  
                         pDimDef->split_type = split_type_customvelocity;  
                         pDimDef->ranges     = new range_t[pDimDef->zones];  
                         uint8_t bits[8] = { 0 };  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);  
   
                             pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;  
                             pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;  
                             previousUpperLimit = pDimDef->ranges[velocityZone].high;  
                             // fill velocity table  
                             for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {  
                                 VelocityTable[i] = velocityZone;  
                             }  
                         }  
                     }  
                 }  
             }  
3008    
3009              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
             File* file = (File*) GetParent()->GetParent();  
3010              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
3011                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
3012              else              else
3013                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3014    
3015              // load sample references              // load sample references (if auto loading is enabled)
3016              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3017                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3018                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3019                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3020                    }
3021                    GetSample(); // load global region sample reference
3022                }
3023            } else {
3024                DimensionRegions = 0;
3025                for (int i = 0 ; i < 8 ; i++) {
3026                    pDimensionDefinitions[i].dimension  = dimension_none;
3027                    pDimensionDefinitions[i].bits       = 0;
3028                    pDimensionDefinitions[i].zones      = 0;
3029                }
3030            }
3031    
3032            // make sure there is at least one dimension region
3033            if (!DimensionRegions) {
3034                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3035                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3036                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3037                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3038                DimensionRegions = 1;
3039            }
3040        }
3041    
3042        /**
3043         * Apply Region settings and all its DimensionRegions to the respective
3044         * RIFF chunks. You have to call File::Save() to make changes persistent.
3045         *
3046         * Usually there is absolutely no need to call this method explicitly.
3047         * It will be called automatically when File::Save() was called.
3048         *
3049         * @param pProgress - callback function for progress notification
3050         * @throws gig::Exception if samples cannot be dereferenced
3051         */
3052        void Region::UpdateChunks(progress_t* pProgress) {
3053            // in the gig format we don't care about the Region's sample reference
3054            // but we still have to provide some existing one to not corrupt the
3055            // file, so to avoid the latter we simply always assign the sample of
3056            // the first dimension region of this region
3057            pSample = pDimensionRegions[0]->pSample;
3058    
3059            // first update base class's chunks
3060            DLS::Region::UpdateChunks(pProgress);
3061    
3062            // update dimension region's chunks
3063            for (int i = 0; i < DimensionRegions; i++) {
3064                pDimensionRegions[i]->UpdateChunks(pProgress);
3065            }
3066    
3067            File* pFile = (File*) GetParent()->GetParent();
3068            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3069            const int iMaxDimensions =  version3 ? 8 : 5;
3070            const int iMaxDimensionRegions = version3 ? 256 : 32;
3071    
3072            // make sure '3lnk' chunk exists
3073            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3074            if (!_3lnk) {
3075                const int _3lnkChunkSize = version3 ? 1092 : 172;
3076                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3077                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3078    
3079                // move 3prg to last position
3080                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3081            }
3082    
3083            // update dimension definitions in '3lnk' chunk
3084            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3085            store32(&pData[0], DimensionRegions);
3086            int shift = 0;
3087            for (int i = 0; i < iMaxDimensions; i++) {
3088                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3089                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3090                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3091                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3092                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3093                // next 3 bytes unknown, always zero?
3094    
3095                shift += pDimensionDefinitions[i].bits;
3096            }
3097    
3098            // update wave pool table in '3lnk' chunk
3099            const int iWavePoolOffset = version3 ? 68 : 44;
3100            for (uint i = 0; i < iMaxDimensionRegions; i++) {
3101                int iWaveIndex = -1;
3102                if (i < DimensionRegions) {
3103                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3104                    File::SampleList::iterator iter = pFile->pSamples->begin();
3105                    File::SampleList::iterator end  = pFile->pSamples->end();
3106                    for (int index = 0; iter != end; ++iter, ++index) {
3107                        if (*iter == pDimensionRegions[i]->pSample) {
3108                            iWaveIndex = index;
3109                            break;
3110                        }
3111                    }
3112              }              }
3113                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3114          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
3115      }      }
3116    
3117      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1509  namespace { Line 3121  namespace {
3121              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3122              while (_3ewl) {              while (_3ewl) {
3123                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3124                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3125                      dimensionRegionNr++;                      dimensionRegionNr++;
3126                  }                  }
3127                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 1518  namespace { Line 3130  namespace {
3130          }          }
3131      }      }
3132    
3133      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3134          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
3135              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
3136            // update Region key table for fast lookup
3137            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3138        }
3139    
3140        void Region::UpdateVelocityTable() {
3141            // get velocity dimension's index
3142            int veldim = -1;
3143            for (int i = 0 ; i < Dimensions ; i++) {
3144                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3145                    veldim = i;
3146                    break;
3147                }
3148            }
3149            if (veldim == -1) return;
3150    
3151            int step = 1;
3152            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3153            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3154    
3155            // loop through all dimension regions for all dimensions except the velocity dimension
3156            int dim[8] = { 0 };
3157            for (int i = 0 ; i < DimensionRegions ; i++) {
3158                const int end = i + step * pDimensionDefinitions[veldim].zones;
3159    
3160                // create a velocity table for all cases where the velocity zone is zero
3161                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3162                    pDimensionRegions[i]->VelocityUpperLimit) {
3163                    // create the velocity table
3164                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
3165                    if (!table) {
3166                        table = new uint8_t[128];
3167                        pDimensionRegions[i]->VelocityTable = table;
3168                    }
3169                    int tableidx = 0;
3170                    int velocityZone = 0;
3171                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3172                        for (int k = i ; k < end ; k += step) {
3173                            DimensionRegion *d = pDimensionRegions[k];
3174                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3175                            velocityZone++;
3176                        }
3177                    } else { // gig2
3178                        for (int k = i ; k < end ; k += step) {
3179                            DimensionRegion *d = pDimensionRegions[k];
3180                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3181                            velocityZone++;
3182                        }
3183                    }
3184                } else {
3185                    if (pDimensionRegions[i]->VelocityTable) {
3186                        delete[] pDimensionRegions[i]->VelocityTable;
3187                        pDimensionRegions[i]->VelocityTable = 0;
3188                    }
3189                }
3190    
3191                // jump to the next case where the velocity zone is zero
3192                int j;
3193                int shift = 0;
3194                for (j = 0 ; j < Dimensions ; j++) {
3195                    if (j == veldim) i += skipveldim; // skip velocity dimension
3196                    else {
3197                        dim[j]++;
3198                        if (dim[j] < pDimensionDefinitions[j].zones) break;
3199                        else {
3200                            // skip unused dimension regions
3201                            dim[j] = 0;
3202                            i += ((1 << pDimensionDefinitions[j].bits) -
3203                                  pDimensionDefinitions[j].zones) << shift;
3204                        }
3205                    }
3206                    shift += pDimensionDefinitions[j].bits;
3207                }
3208                if (j == Dimensions) break;
3209            }
3210        }
3211    
3212        /** @brief Einstein would have dreamed of it - create a new dimension.
3213         *
3214         * Creates a new dimension with the dimension definition given by
3215         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
3216         * There is a hard limit of dimensions and total amount of "bits" all
3217         * dimensions can have. This limit is dependant to what gig file format
3218         * version this file refers to. The gig v2 (and lower) format has a
3219         * dimension limit and total amount of bits limit of 5, whereas the gig v3
3220         * format has a limit of 8.
3221         *
3222         * @param pDimDef - defintion of the new dimension
3223         * @throws gig::Exception if dimension of the same type exists already
3224         * @throws gig::Exception if amount of dimensions or total amount of
3225         *                        dimension bits limit is violated
3226         */
3227        void Region::AddDimension(dimension_def_t* pDimDef) {
3228            // some initial sanity checks of the given dimension definition
3229            if (pDimDef->zones < 2)
3230                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3231            if (pDimDef->bits < 1)
3232                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3233            if (pDimDef->dimension == dimension_samplechannel) {
3234                if (pDimDef->zones != 2)
3235                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3236                if (pDimDef->bits != 1)
3237                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3238            }
3239    
3240            // check if max. amount of dimensions reached
3241            File* file = (File*) GetParent()->GetParent();
3242            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3243            if (Dimensions >= iMaxDimensions)
3244                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3245            // check if max. amount of dimension bits reached
3246            int iCurrentBits = 0;
3247            for (int i = 0; i < Dimensions; i++)
3248                iCurrentBits += pDimensionDefinitions[i].bits;
3249            if (iCurrentBits >= iMaxDimensions)
3250                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3251            const int iNewBits = iCurrentBits + pDimDef->bits;
3252            if (iNewBits > iMaxDimensions)
3253                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3254            // check if there's already a dimensions of the same type
3255            for (int i = 0; i < Dimensions; i++)
3256                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3257                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3258    
3259            // pos is where the new dimension should be placed, normally
3260            // last in list, except for the samplechannel dimension which
3261            // has to be first in list
3262            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3263            int bitpos = 0;
3264            for (int i = 0 ; i < pos ; i++)
3265                bitpos += pDimensionDefinitions[i].bits;
3266    
3267            // make room for the new dimension
3268            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3269            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3270                for (int j = Dimensions ; j > pos ; j--) {
3271                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3272                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3273                }
3274            }
3275    
3276            // assign definition of new dimension
3277            pDimensionDefinitions[pos] = *pDimDef;
3278    
3279            // auto correct certain dimension definition fields (where possible)
3280            pDimensionDefinitions[pos].split_type  =
3281                __resolveSplitType(pDimensionDefinitions[pos].dimension);
3282            pDimensionDefinitions[pos].zone_size =
3283                __resolveZoneSize(pDimensionDefinitions[pos]);
3284    
3285            // create new dimension region(s) for this new dimension, and make
3286            // sure that the dimension regions are placed correctly in both the
3287            // RIFF list and the pDimensionRegions array
3288            RIFF::Chunk* moveTo = NULL;
3289            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3290            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3291                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3292                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3293                }
3294                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3295                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3296                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3297                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3298                        // create a new dimension region and copy all parameter values from
3299                        // an existing dimension region
3300                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3301                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3302    
3303                        DimensionRegions++;
3304                    }
3305                }
3306                moveTo = pDimensionRegions[i]->pParentList;
3307            }
3308    
3309            // initialize the upper limits for this dimension
3310            int mask = (1 << bitpos) - 1;
3311            for (int z = 0 ; z < pDimDef->zones ; z++) {
3312                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3313                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3314                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3315                                      (z << bitpos) |
3316                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3317                }
3318            }
3319    
3320            Dimensions++;
3321    
3322            // if this is a layer dimension, update 'Layers' attribute
3323            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3324    
3325            UpdateVelocityTable();
3326        }
3327    
3328        /** @brief Delete an existing dimension.
3329         *
3330         * Deletes the dimension given by \a pDimDef and deletes all respective
3331         * dimension regions, that is all dimension regions where the dimension's
3332         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
3333         * for example this would delete all dimension regions for the case(s)
3334         * where the sustain pedal is pressed down.
3335         *
3336         * @param pDimDef - dimension to delete
3337         * @throws gig::Exception if given dimension cannot be found
3338         */
3339        void Region::DeleteDimension(dimension_def_t* pDimDef) {
3340            // get dimension's index
3341            int iDimensionNr = -1;
3342            for (int i = 0; i < Dimensions; i++) {
3343                if (&pDimensionDefinitions[i] == pDimDef) {
3344                    iDimensionNr = i;
3345                    break;
3346                }
3347          }          }
3348            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3349    
3350            // get amount of bits below the dimension to delete
3351            int iLowerBits = 0;
3352            for (int i = 0; i < iDimensionNr; i++)
3353                iLowerBits += pDimensionDefinitions[i].bits;
3354    
3355            // get amount ot bits above the dimension to delete
3356            int iUpperBits = 0;
3357            for (int i = iDimensionNr + 1; i < Dimensions; i++)
3358                iUpperBits += pDimensionDefinitions[i].bits;
3359    
3360            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3361    
3362            // delete dimension regions which belong to the given dimension
3363            // (that is where the dimension's bit > 0)
3364            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3365                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3366                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3367                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3368                                        iObsoleteBit << iLowerBits |
3369                                        iLowerBit;
3370    
3371                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3372                        delete pDimensionRegions[iToDelete];
3373                        pDimensionRegions[iToDelete] = NULL;
3374                        DimensionRegions--;
3375                    }
3376                }
3377            }
3378    
3379            // defrag pDimensionRegions array
3380            // (that is remove the NULL spaces within the pDimensionRegions array)
3381            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3382                if (!pDimensionRegions[iTo]) {
3383                    if (iFrom <= iTo) iFrom = iTo + 1;
3384                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3385                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
3386                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
3387                        pDimensionRegions[iFrom] = NULL;
3388                    }
3389                }
3390            }
3391    
3392            // remove the this dimension from the upper limits arrays
3393            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3394                DimensionRegion* d = pDimensionRegions[j];
3395                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3396                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3397                }
3398                d->DimensionUpperLimits[Dimensions - 1] = 127;
3399            }
3400    
3401            // 'remove' dimension definition
3402            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3403                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
3404            }
3405            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3406            pDimensionDefinitions[Dimensions - 1].bits      = 0;
3407            pDimensionDefinitions[Dimensions - 1].zones     = 0;
3408    
3409            Dimensions--;
3410    
3411            // if this was a layer dimension, update 'Layers' attribute
3412            if (pDimDef->dimension == dimension_layer) Layers = 1;
3413        }
3414    
3415        /** @brief Delete one split zone of a dimension (decrement zone amount).
3416         *
3417         * Instead of deleting an entire dimensions, this method will only delete
3418         * one particular split zone given by @a zone of the Region's dimension
3419         * given by @a type. So this method will simply decrement the amount of
3420         * zones by one of the dimension in question. To be able to do that, the
3421         * respective dimension must exist on this Region and it must have at least
3422         * 3 zones. All DimensionRegion objects associated with the zone will be
3423         * deleted.
3424         *
3425         * @param type - identifies the dimension where a zone shall be deleted
3426         * @param zone - index of the dimension split zone that shall be deleted
3427         * @throws gig::Exception if requested zone could not be deleted
3428         */
3429        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3430            dimension_def_t* oldDef = GetDimensionDefinition(type);
3431            if (!oldDef)
3432                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3433            if (oldDef->zones <= 2)
3434                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3435            if (zone < 0 || zone >= oldDef->zones)
3436                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3437    
3438            const int newZoneSize = oldDef->zones - 1;
3439    
3440            // create a temporary Region which just acts as a temporary copy
3441            // container and will be deleted at the end of this function and will
3442            // also not be visible through the API during this process
3443            gig::Region* tempRgn = NULL;
3444            {
3445                // adding these temporary chunks is probably not even necessary
3446                Instrument* instr = static_cast<Instrument*>(GetParent());
3447                RIFF::List* pCkInstrument = instr->pCkInstrument;
3448                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3449                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3450                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3451                tempRgn = new Region(instr, rgn);
3452            }
3453    
3454            // copy this region's dimensions (with already the dimension split size
3455            // requested by the arguments of this method call) to the temporary
3456            // region, and don't use Region::CopyAssign() here for this task, since
3457            // it would also alter fast lookup helper variables here and there
3458            dimension_def_t newDef;
3459            for (int i = 0; i < Dimensions; ++i) {
3460                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3461                // is this the dimension requested by the method arguments? ...
3462                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3463                    def.zones = newZoneSize;
3464                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3465                    newDef = def;
3466                }
3467                tempRgn->AddDimension(&def);
3468            }
3469    
3470            // find the dimension index in the tempRegion which is the dimension
3471            // type passed to this method (paranoidly expecting different order)
3472            int tempReducedDimensionIndex = -1;
3473            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3474                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3475                    tempReducedDimensionIndex = d;
3476                    break;
3477                }
3478            }
3479    
3480            // copy dimension regions from this region to the temporary region
3481            for (int iDst = 0; iDst < 256; ++iDst) {
3482                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3483                if (!dstDimRgn) continue;
3484                std::map<dimension_t,int> dimCase;
3485                bool isValidZone = true;
3486                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3487                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3488                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3489                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3490                    baseBits += dstBits;
3491                    // there are also DimensionRegion objects of unused zones, skip them
3492                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3493                        isValidZone = false;
3494                        break;
3495                    }
3496                }
3497                if (!isValidZone) continue;
3498                // a bit paranoid: cope with the chance that the dimensions would
3499                // have different order in source and destination regions
3500                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3501                if (dimCase[type] >= zone) dimCase[type]++;
3502                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3503                dstDimRgn->CopyAssign(srcDimRgn);
3504                // if this is the upper most zone of the dimension passed to this
3505                // method, then correct (raise) its upper limit to 127
3506                if (newDef.split_type == split_type_normal && isLastZone)
3507                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3508            }
3509    
3510            // now tempRegion's dimensions and DimensionRegions basically reflect
3511            // what we wanted to get for this actual Region here, so we now just
3512            // delete and recreate the dimension in question with the new amount
3513            // zones and then copy back from tempRegion      
3514            DeleteDimension(oldDef);
3515            AddDimension(&newDef);
3516            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3517                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3518                if (!srcDimRgn) continue;
3519                std::map<dimension_t,int> dimCase;
3520                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3521                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3522                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3523                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3524                    baseBits += srcBits;
3525                }
3526                // a bit paranoid: cope with the chance that the dimensions would
3527                // have different order in source and destination regions
3528                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3529                if (!dstDimRgn) continue;
3530                dstDimRgn->CopyAssign(srcDimRgn);
3531            }
3532    
3533            // delete temporary region
3534            delete tempRgn;
3535    
3536            UpdateVelocityTable();
3537        }
3538    
3539        /** @brief Divide split zone of a dimension in two (increment zone amount).
3540         *
3541         * This will increment the amount of zones for the dimension (given by
3542         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3543         * in the middle of its zone range in two. So the two zones resulting from
3544         * the zone being splitted, will be an equivalent copy regarding all their
3545         * articulation informations and sample reference. The two zones will only
3546         * differ in their zone's upper limit
3547         * (DimensionRegion::DimensionUpperLimits).
3548         *
3549         * @param type - identifies the dimension where a zone shall be splitted
3550         * @param zone - index of the dimension split zone that shall be splitted
3551         * @throws gig::Exception if requested zone could not be splitted
3552         */
3553        void Region::SplitDimensionZone(dimension_t type, int zone) {
3554            dimension_def_t* oldDef = GetDimensionDefinition(type);
3555            if (!oldDef)
3556                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3557            if (zone < 0 || zone >= oldDef->zones)
3558                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3559    
3560            const int newZoneSize = oldDef->zones + 1;
3561    
3562            // create a temporary Region which just acts as a temporary copy
3563            // container and will be deleted at the end of this function and will
3564            // also not be visible through the API during this process
3565            gig::Region* tempRgn = NULL;
3566            {
3567                // adding these temporary chunks is probably not even necessary
3568                Instrument* instr = static_cast<Instrument*>(GetParent());
3569                RIFF::List* pCkInstrument = instr->pCkInstrument;
3570                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3571                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3572                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3573                tempRgn = new Region(instr, rgn);
3574            }
3575    
3576            // copy this region's dimensions (with already the dimension split size
3577            // requested by the arguments of this method call) to the temporary
3578            // region, and don't use Region::CopyAssign() here for this task, since
3579            // it would also alter fast lookup helper variables here and there
3580            dimension_def_t newDef;
3581            for (int i = 0; i < Dimensions; ++i) {
3582                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3583                // is this the dimension requested by the method arguments? ...
3584                if (def.dimension == type) { // ... if yes, increment zone amount by one
3585                    def.zones = newZoneSize;
3586                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3587                    newDef = def;
3588                }
3589                tempRgn->AddDimension(&def);
3590            }
3591    
3592            // find the dimension index in the tempRegion which is the dimension
3593            // type passed to this method (paranoidly expecting different order)
3594            int tempIncreasedDimensionIndex = -1;
3595            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3596                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3597                    tempIncreasedDimensionIndex = d;
3598                    break;
3599                }
3600            }
3601    
3602            // copy dimension regions from this region to the temporary region
3603            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3604                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3605                if (!srcDimRgn) continue;
3606                std::map<dimension_t,int> dimCase;
3607                bool isValidZone = true;
3608                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3609                    const int srcBits = pDimensionDefinitions[d].bits;
3610                    dimCase[pDimensionDefinitions[d].dimension] =
3611                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3612                    // there are also DimensionRegion objects for unused zones, skip them
3613                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3614                        isValidZone = false;
3615                        break;
3616                    }
3617                    baseBits += srcBits;
3618                }
3619                if (!isValidZone) continue;
3620                // a bit paranoid: cope with the chance that the dimensions would
3621                // have different order in source and destination regions            
3622                if (dimCase[type] > zone) dimCase[type]++;
3623                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3624                dstDimRgn->CopyAssign(srcDimRgn);
3625                // if this is the requested zone to be splitted, then also copy
3626                // the source DimensionRegion to the newly created target zone
3627                // and set the old zones upper limit lower
3628                if (dimCase[type] == zone) {
3629                    // lower old zones upper limit
3630                    if (newDef.split_type == split_type_normal) {
3631                        const int high =
3632                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3633                        int low = 0;
3634                        if (zone > 0) {
3635                            std::map<dimension_t,int> lowerCase = dimCase;
3636                            lowerCase[type]--;
3637                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3638                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3639                        }
3640                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3641                    }
3642                    // fill the newly created zone of the divided zone as well
3643                    dimCase[type]++;
3644                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3645                    dstDimRgn->CopyAssign(srcDimRgn);
3646                }
3647            }
3648    
3649            // now tempRegion's dimensions and DimensionRegions basically reflect
3650            // what we wanted to get for this actual Region here, so we now just
3651            // delete and recreate the dimension in question with the new amount
3652            // zones and then copy back from tempRegion      
3653            DeleteDimension(oldDef);
3654            AddDimension(&newDef);
3655            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3656                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3657                if (!srcDimRgn) continue;
3658                std::map<dimension_t,int> dimCase;
3659                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3660                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3661                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3662                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3663                    baseBits += srcBits;
3664                }
3665                // a bit paranoid: cope with the chance that the dimensions would
3666                // have different order in source and destination regions
3667                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3668                if (!dstDimRgn) continue;
3669                dstDimRgn->CopyAssign(srcDimRgn);
3670            }
3671    
3672            // delete temporary region
3673            delete tempRgn;
3674    
3675            UpdateVelocityTable();
3676        }
3677    
3678        /** @brief Change type of an existing dimension.
3679         *
3680         * Alters the dimension type of a dimension already existing on this
3681         * region. If there is currently no dimension on this Region with type
3682         * @a oldType, then this call with throw an Exception. Likewise there are
3683         * cases where the requested dimension type cannot be performed. For example
3684         * if the new dimension type shall be gig::dimension_samplechannel, and the
3685         * current dimension has more than 2 zones. In such cases an Exception is
3686         * thrown as well.
3687         *
3688         * @param oldType - identifies the existing dimension to be changed
3689         * @param newType - to which dimension type it should be changed to
3690         * @throws gig::Exception if requested change cannot be performed
3691         */
3692        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3693            if (oldType == newType) return;
3694            dimension_def_t* def = GetDimensionDefinition(oldType);
3695            if (!def)
3696                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3697            if (newType == dimension_samplechannel && def->zones != 2)
3698                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3699            if (GetDimensionDefinition(newType))
3700                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3701            def->dimension  = newType;
3702            def->split_type = __resolveSplitType(newType);
3703        }
3704    
3705        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3706            uint8_t bits[8] = {};
3707            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3708                 it != DimCase.end(); ++it)
3709            {
3710                for (int d = 0; d < Dimensions; ++d) {
3711                    if (pDimensionDefinitions[d].dimension == it->first) {
3712                        bits[d] = it->second;
3713                        goto nextDimCaseSlice;
3714                    }
3715                }
3716                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3717                nextDimCaseSlice:
3718                ; // noop
3719            }
3720            return GetDimensionRegionByBit(bits);
3721        }
3722    
3723        /**
3724         * Searches in the current Region for a dimension of the given dimension
3725         * type and returns the precise configuration of that dimension in this
3726         * Region.
3727         *
3728         * @param type - dimension type of the sought dimension
3729         * @returns dimension definition or NULL if there is no dimension with
3730         *          sought type in this Region.
3731         */
3732        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3733            for (int i = 0; i < Dimensions; ++i)
3734                if (pDimensionDefinitions[i].dimension == type)
3735                    return &pDimensionDefinitions[i];
3736            return NULL;
3737        }
3738    
3739        Region::~Region() {
3740          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3741              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
3742          }          }
# Line 1546  namespace { Line 3761  namespace {
3761       * @see             Dimensions       * @see             Dimensions
3762       */       */
3763      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3764          uint8_t bits[8] = { 0 };          uint8_t bits;
3765            int veldim = -1;
3766            int velbitpos;
3767            int bitpos = 0;
3768            int dimregidx = 0;
3769          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
3770              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3771              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
3772                  case split_type_normal:                  veldim = i;
3773                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
3774                      break;              } else {
3775                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
3776                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
3777                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3778                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3779                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3780                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3781                      break;                              }
3782                            } else {
3783                                // gig2: evenly sized zones
3784                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3785                            }
3786                            break;
3787                        case split_type_bit: // the value is already the sought dimension bit number
3788                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3789                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3790                            break;
3791                    }
3792                    dimregidx |= bits << bitpos;
3793              }              }
3794                bitpos += pDimensionDefinitions[i].bits;
3795          }          }
3796          return GetDimensionRegionByBit(bits);          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3797            if (!dimreg) return NULL;
3798            if (veldim != -1) {
3799                // (dimreg is now the dimension region for the lowest velocity)
3800                if (dimreg->VelocityTable) // custom defined zone ranges
3801                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3802                else // normal split type
3803                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3804    
3805                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3806                dimregidx |= (bits & limiter_mask) << velbitpos;
3807                dimreg = pDimensionRegions[dimregidx & 255];
3808            }
3809            return dimreg;
3810        }
3811    
3812        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3813            uint8_t bits;
3814            int veldim = -1;
3815            int velbitpos;
3816            int bitpos = 0;
3817            int dimregidx = 0;
3818            for (uint i = 0; i < Dimensions; i++) {
3819                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3820                    // the velocity dimension must be handled after the other dimensions
3821                    veldim = i;
3822                    velbitpos = bitpos;
3823                } else {
3824                    switch (pDimensionDefinitions[i].split_type) {
3825                        case split_type_normal:
3826                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3827                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3828                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3829                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3830                                }
3831                            } else {
3832                                // gig2: evenly sized zones
3833                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3834                            }
3835                            break;
3836                        case split_type_bit: // the value is already the sought dimension bit number
3837                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3838                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3839                            break;
3840                    }
3841                    dimregidx |= bits << bitpos;
3842                }
3843                bitpos += pDimensionDefinitions[i].bits;
3844            }
3845            dimregidx &= 255;
3846            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3847            if (!dimreg) return -1;
3848            if (veldim != -1) {
3849                // (dimreg is now the dimension region for the lowest velocity)
3850                if (dimreg->VelocityTable) // custom defined zone ranges
3851                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3852                else // normal split type
3853                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3854    
3855                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3856                dimregidx |= (bits & limiter_mask) << velbitpos;
3857                dimregidx &= 255;
3858            }
3859            return dimregidx;
3860      }      }
3861    
3862      /**      /**
# Line 1602  namespace { Line 3896  namespace {
3896      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3897          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3898          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3899          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          if (!file->pWavePoolTable) return NULL;
3900          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3901          Sample* sample = file->GetFirstSample(pProgress);          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3902          while (sample) {              // use 64 bit wave pool offsets (treating this as large file)
3903              if (sample->ulWavePoolOffset == soughtoffset &&              uint64_t soughtoffset =
3904                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3905              sample = file->GetNextSample();                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3906                Sample* sample = file->GetFirstSample(pProgress);
3907                while (sample) {
3908                    if (sample->ullWavePoolOffset == soughtoffset)
3909                        return static_cast<gig::Sample*>(sample);
3910                    sample = file->GetNextSample();
3911                }
3912            } else {
3913                // use extension files and 32 bit wave pool offsets
3914                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3915                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3916                Sample* sample = file->GetFirstSample(pProgress);
3917                while (sample) {
3918                    if (sample->ullWavePoolOffset == soughtoffset &&
3919                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3920                    sample = file->GetNextSample();
3921                }
3922          }          }
3923          return NULL;          return NULL;
3924      }      }
3925        
3926        /**
3927         * Make a (semi) deep copy of the Region object given by @a orig
3928         * and assign it to this object.
3929         *
3930         * Note that all sample pointers referenced by @a orig are simply copied as
3931         * memory address. Thus the respective samples are shared, not duplicated!
3932         *
3933         * @param orig - original Region object to be copied from
3934         */
3935        void Region::CopyAssign(const Region* orig) {
3936            CopyAssign(orig, NULL);
3937        }
3938        
3939        /**
3940         * Make a (semi) deep copy of the Region object given by @a orig and
3941         * assign it to this object
3942         *
3943         * @param mSamples - crosslink map between the foreign file's samples and
3944         *                   this file's samples
3945         */
3946        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3947            // handle base classes
3948            DLS::Region::CopyAssign(orig);
3949            
3950            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3951                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3952            }
3953            
3954            // handle own member variables
3955            for (int i = Dimensions - 1; i >= 0; --i) {
3956                DeleteDimension(&pDimensionDefinitions[i]);
3957            }
3958            Layers = 0; // just to be sure
3959            for (int i = 0; i < orig->Dimensions; i++) {
3960                // we need to copy the dim definition here, to avoid the compiler
3961                // complaining about const-ness issue
3962                dimension_def_t def = orig->pDimensionDefinitions[i];
3963                AddDimension(&def);
3964            }
3965            for (int i = 0; i < 256; i++) {
3966                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3967                    pDimensionRegions[i]->CopyAssign(
3968                        orig->pDimensionRegions[i],
3969                        mSamples
3970                    );
3971                }
3972            }
3973            Layers = orig->Layers;
3974        }
3975    
3976    
3977    // *************** MidiRule ***************
3978    // *
3979    
3980        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3981            _3ewg->SetPos(36);
3982            Triggers = _3ewg->ReadUint8();
3983            _3ewg->SetPos(40);
3984            ControllerNumber = _3ewg->ReadUint8();
3985            _3ewg->SetPos(46);
3986            for (int i = 0 ; i < Triggers ; i++) {
3987                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3988                pTriggers[i].Descending = _3ewg->ReadUint8();
3989                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3990                pTriggers[i].Key = _3ewg->ReadUint8();
3991                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3992                pTriggers[i].Velocity = _3ewg->ReadUint8();
3993                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3994                _3ewg->ReadUint8();
3995            }
3996        }
3997    
3998        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3999            ControllerNumber(0),
4000            Triggers(0) {
4001        }
4002    
4003        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4004            pData[32] = 4;
4005            pData[33] = 16;
4006            pData[36] = Triggers;
4007            pData[40] = ControllerNumber;
4008            for (int i = 0 ; i < Triggers ; i++) {
4009                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4010                pData[47 + i * 8] = pTriggers[i].Descending;
4011                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4012                pData[49 + i * 8] = pTriggers[i].Key;
4013                pData[50 + i * 8] = pTriggers[i].NoteOff;
4014                pData[51 + i * 8] = pTriggers[i].Velocity;
4015                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4016            }
4017        }
4018    
4019        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4020            _3ewg->SetPos(36);
4021            LegatoSamples = _3ewg->ReadUint8(); // always 12
4022            _3ewg->SetPos(40);
4023            BypassUseController = _3ewg->ReadUint8();
4024            BypassKey = _3ewg->ReadUint8();
4025            BypassController = _3ewg->ReadUint8();
4026            ThresholdTime = _3ewg->ReadUint16();
4027            _3ewg->ReadInt16();
4028            ReleaseTime = _3ewg->ReadUint16();
4029            _3ewg->ReadInt16();
4030            KeyRange.low = _3ewg->ReadUint8();
4031            KeyRange.high = _3ewg->ReadUint8();
4032            _3ewg->SetPos(64);
4033            ReleaseTriggerKey = _3ewg->ReadUint8();
4034            AltSustain1Key = _3ewg->ReadUint8();
4035            AltSustain2Key = _3ewg->ReadUint8();
4036        }
4037    
4038        MidiRuleLegato::MidiRuleLegato() :
4039            LegatoSamples(12),
4040            BypassUseController(false),
4041            BypassKey(0),
4042            BypassController(1),
4043            ThresholdTime(20),
4044            ReleaseTime(20),
4045            ReleaseTriggerKey(0),
4046            AltSustain1Key(0),
4047            AltSustain2Key(0)
4048        {
4049            KeyRange.low = KeyRange.high = 0;
4050        }
4051    
4052        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4053            pData[32] = 0;
4054            pData[33] = 16;
4055            pData[36] = LegatoSamples;
4056            pData[40] = BypassUseController;
4057            pData[41] = BypassKey;
4058            pData[42] = BypassController;
4059            store16(&pData[43], ThresholdTime);
4060            store16(&pData[47], ReleaseTime);
4061            pData[51] = KeyRange.low;
4062            pData[52] = KeyRange.high;
4063            pData[64] = ReleaseTriggerKey;
4064            pData[65] = AltSustain1Key;
4065            pData[66] = AltSustain2Key;
4066        }
4067    
4068        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4069            _3ewg->SetPos(36);
4070            Articulations = _3ewg->ReadUint8();
4071            int flags = _3ewg->ReadUint8();
4072            Polyphonic = flags & 8;
4073            Chained = flags & 4;
4074            Selector = (flags & 2) ? selector_controller :
4075                (flags & 1) ? selector_key_switch : selector_none;
4076            Patterns = _3ewg->ReadUint8();
4077            _3ewg->ReadUint8(); // chosen row
4078            _3ewg->ReadUint8(); // unknown
4079            _3ewg->ReadUint8(); // unknown
4080            _3ewg->ReadUint8(); // unknown
4081            KeySwitchRange.low = _3ewg->ReadUint8();
4082            KeySwitchRange.high = _3ewg->ReadUint8();
4083            Controller = _3ewg->ReadUint8();
4084            PlayRange.low = _3ewg->ReadUint8();
4085            PlayRange.high = _3ewg->ReadUint8();
4086    
4087            int n = std::min(int(Articulations), 32);
4088            for (int i = 0 ; i < n ; i++) {
4089                _3ewg->ReadString(pArticulations[i], 32);
4090            }
4091            _3ewg->SetPos(1072);
4092            n = std::min(int(Patterns), 32);
4093            for (int i = 0 ; i < n ; i++) {
4094                _3ewg->ReadString(pPatterns[i].Name, 16);
4095                pPatterns[i].Size = _3ewg->ReadUint8();
4096                _3ewg->Read(&pPatterns[i][0], 1, 32);
4097            }
4098        }
4099    
4100        MidiRuleAlternator::MidiRuleAlternator() :
4101            Articulations(0),
4102            Patterns(0),
4103            Selector(selector_none),
4104            Controller(0),
4105            Polyphonic(false),
4106            Chained(false)
4107        {
4108            PlayRange.low = PlayRange.high = 0;
4109            KeySwitchRange.low = KeySwitchRange.high = 0;
4110        }
4111    
4112        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4113            pData[32] = 3;
4114            pData[33] = 16;
4115            pData[36] = Articulations;
4116            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4117                (Selector == selector_controller ? 2 :
4118                 (Selector == selector_key_switch ? 1 : 0));
4119            pData[38] = Patterns;
4120    
4121            pData[43] = KeySwitchRange.low;
4122            pData[44] = KeySwitchRange.high;
4123            pData[45] = Controller;
4124            pData[46] = PlayRange.low;
4125            pData[47] = PlayRange.high;
4126    
4127            char* str = reinterpret_cast<char*>(pData);
4128            int pos = 48;
4129            int n = std::min(int(Articulations), 32);
4130            for (int i = 0 ; i < n ; i++, pos += 32) {
4131                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4132            }
4133    
4134            pos = 1072;
4135            n = std::min(int(Patterns), 32);
4136            for (int i = 0 ; i < n ; i++, pos += 49) {
4137                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4138                pData[pos + 16] = pPatterns[i].Size;
4139                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4140            }
4141        }
4142    
4143    // *************** Script ***************
4144    // *
4145    
4146        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4147            pGroup = group;
4148            pChunk = ckScri;
4149            if (ckScri) { // object is loaded from file ...
4150                // read header
4151                uint32_t headerSize = ckScri->ReadUint32();
4152                Compression = (Compression_t) ckScri->ReadUint32();
4153                Encoding    = (Encoding_t) ckScri->ReadUint32();
4154                Language    = (Language_t) ckScri->ReadUint32();
4155                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4156                crc         = ckScri->ReadUint32();
4157                uint32_t nameSize = ckScri->ReadUint32();
4158                Name.resize(nameSize, ' ');
4159                for (int i = 0; i < nameSize; ++i)
4160                    Name[i] = ckScri->ReadUint8();
4161                // to handle potential future extensions of the header
4162                ckScri->SetPos(sizeof(int32_t) + headerSize);
4163                // read actual script data
4164                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4165                data.resize(scriptSize);
4166                for (int i = 0; i < scriptSize; ++i)
4167                    data[i] = ckScri->ReadUint8();
4168            } else { // this is a new script object, so just initialize it as such ...
4169                Compression = COMPRESSION_NONE;
4170                Encoding = ENCODING_ASCII;
4171                Language = LANGUAGE_NKSP;
4172                Bypass   = false;
4173                crc      = 0;
4174                Name     = "Unnamed Script";
4175            }
4176        }
4177    
4178        Script::~Script() {
4179        }
4180    
4181        /**
4182         * Returns the current script (i.e. as source code) in text format.
4183         */
4184        String Script::GetScriptAsText() {
4185            String s;
4186            s.resize(data.size(), ' ');
4187            memcpy(&s[0], &data[0], data.size());
4188            return s;
4189        }
4190    
4191        /**
4192         * Replaces the current script with the new script source code text given
4193         * by @a text.
4194         *
4195         * @param text - new script source code
4196         */
4197        void Script::SetScriptAsText(const String& text) {
4198            data.resize(text.size());
4199            memcpy(&data[0], &text[0], text.size());
4200        }
4201    
4202        /**
4203         * Apply this script to the respective RIFF chunks. You have to call
4204         * File::Save() to make changes persistent.
4205         *
4206         * Usually there is absolutely no need to call this method explicitly.
4207         * It will be called automatically when File::Save() was called.
4208         *
4209         * @param pProgress - callback function for progress notification
4210         */
4211        void Script::UpdateChunks(progress_t* pProgress) {
4212            // recalculate CRC32 check sum
4213            __resetCRC(crc);
4214            __calculateCRC(&data[0], data.size(), crc);
4215            __encodeCRC(crc);
4216            // make sure chunk exists and has the required size
4217            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4218            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4219            else pChunk->Resize(chunkSize);
4220            // fill the chunk data to be written to disk
4221            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4222            int pos = 0;
4223            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4224            pos += sizeof(int32_t);
4225            store32(&pData[pos], Compression);
4226            pos += sizeof(int32_t);
4227            store32(&pData[pos], Encoding);
4228            pos += sizeof(int32_t);
4229            store32(&pData[pos], Language);
4230            pos += sizeof(int32_t);
4231            store32(&pData[pos], Bypass ? 1 : 0);
4232            pos += sizeof(int32_t);
4233            store32(&pData[pos], crc);
4234            pos += sizeof(int32_t);
4235            store32(&pData[pos], Name.size());
4236            pos += sizeof(int32_t);
4237            for (int i = 0; i < Name.size(); ++i, ++pos)
4238                pData[pos] = Name[i];
4239            for (int i = 0; i < data.size(); ++i, ++pos)
4240                pData[pos] = data[i];
4241        }
4242    
4243        /**
4244         * Move this script from its current ScriptGroup to another ScriptGroup
4245         * given by @a pGroup.
4246         *
4247         * @param pGroup - script's new group
4248         */
4249        void Script::SetGroup(ScriptGroup* pGroup) {
4250            if (this->pGroup == pGroup) return;
4251            if (pChunk)
4252                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4253            this->pGroup = pGroup;
4254        }
4255    
4256        /**
4257         * Returns the script group this script currently belongs to. Each script
4258         * is a member of exactly one ScriptGroup.
4259         *
4260         * @returns current script group
4261         */
4262        ScriptGroup* Script::GetGroup() const {
4263            return pGroup;
4264        }
4265    
4266        void Script::RemoveAllScriptReferences() {
4267            File* pFile = pGroup->pFile;
4268            for (int i = 0; pFile->GetInstrument(i); ++i) {
4269                Instrument* instr = pFile->GetInstrument(i);
4270                instr->RemoveScript(this);
4271            }
4272        }
4273    
4274    // *************** ScriptGroup ***************
4275    // *
4276    
4277        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4278            pFile = file;
4279            pList = lstRTIS;
4280            pScripts = NULL;
4281            if (lstRTIS) {
4282                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4283                ::LoadString(ckName, Name);
4284            } else {
4285                Name = "Default Group";
4286            }
4287        }
4288    
4289        ScriptGroup::~ScriptGroup() {
4290            if (pScripts) {
4291                std::list<Script*>::iterator iter = pScripts->begin();
4292                std::list<Script*>::iterator end  = pScripts->end();
4293                while (iter != end) {
4294                    delete *iter;
4295                    ++iter;
4296                }
4297                delete pScripts;
4298            }
4299        }
4300    
4301        /**
4302         * Apply this script group to the respective RIFF chunks. You have to call
4303         * File::Save() to make changes persistent.
4304         *
4305         * Usually there is absolutely no need to call this method explicitly.
4306         * It will be called automatically when File::Save() was called.
4307         *
4308         * @param pProgress - callback function for progress notification
4309         */
4310        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4311            if (pScripts) {
4312                if (!pList)
4313                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4314    
4315                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4316                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4317    
4318                for (std::list<Script*>::iterator it = pScripts->begin();
4319                     it != pScripts->end(); ++it)
4320                {
4321                    (*it)->UpdateChunks(pProgress);
4322                }
4323            }
4324        }
4325    
4326        /** @brief Get instrument script.
4327         *
4328         * Returns the real-time instrument script with the given index.
4329         *
4330         * @param index - number of the sought script (0..n)
4331         * @returns sought script or NULL if there's no such script
4332         */
4333        Script* ScriptGroup::GetScript(uint index) {
4334            if (!pScripts) LoadScripts();
4335            std::list<Script*>::iterator it = pScripts->begin();
4336            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4337                if (i == index) return *it;
4338            return NULL;
4339        }
4340    
4341        /** @brief Add new instrument script.
4342         *
4343         * Adds a new real-time instrument script to the file. The script is not
4344         * actually used / executed unless it is referenced by an instrument to be
4345         * used. This is similar to samples, which you can add to a file, without
4346         * an instrument necessarily actually using it.
4347         *
4348         * You have to call Save() to make this persistent to the file.
4349         *
4350         * @return new empty script object
4351         */
4352        Script* ScriptGroup::AddScript() {
4353            if (!pScripts) LoadScripts();
4354            Script* pScript = new Script(this, NULL);
4355            pScripts->push_back(pScript);
4356            return pScript;
4357        }
4358    
4359        /** @brief Delete an instrument script.
4360         *
4361         * This will delete the given real-time instrument script. References of
4362         * instruments that are using that script will be removed accordingly.
4363         *
4364         * You have to call Save() to make this persistent to the file.
4365         *
4366         * @param pScript - script to delete
4367         * @throws gig::Exception if given script could not be found
4368         */
4369        void ScriptGroup::DeleteScript(Script* pScript) {
4370            if (!pScripts) LoadScripts();
4371            std::list<Script*>::iterator iter =
4372                find(pScripts->begin(), pScripts->end(), pScript);
4373            if (iter == pScripts->end())
4374                throw gig::Exception("Could not delete script, could not find given script");
4375            pScripts->erase(iter);
4376            pScript->RemoveAllScriptReferences();
4377            if (pScript->pChunk)
4378                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4379            delete pScript;
4380        }
4381    
4382        void ScriptGroup::LoadScripts() {
4383            if (pScripts) return;
4384            pScripts = new std::list<Script*>;
4385            if (!pList) return;
4386    
4387            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4388                 ck = pList->GetNextSubChunk())
4389            {
4390                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4391                    pScripts->push_back(new Script(this, ck));
4392                }
4393            }
4394        }
4395    
4396  // *************** Instrument ***************  // *************** Instrument ***************
4397  // *  // *
4398    
4399      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4400            static const DLS::Info::string_length_t fixedStringLengths[] = {
4401                { CHUNK_ID_INAM, 64 },
4402                { CHUNK_ID_ISFT, 12 },
4403                { 0, 0 }
4404            };
4405            pInfo->SetFixedStringLengths(fixedStringLengths);
4406    
4407          // Initialization          // Initialization
4408          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4409          RegionIndex = -1;          EffectSend = 0;
4410            Attenuation = 0;
4411            FineTune = 0;
4412            PitchbendRange = 0;
4413            PianoReleaseMode = false;
4414            DimensionKeyRange.low = 0;
4415            DimensionKeyRange.high = 0;
4416            pMidiRules = new MidiRule*[3];
4417            pMidiRules[0] = NULL;
4418            pScriptRefs = NULL;
4419    
4420          // Loading          // Loading
4421          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1636  namespace { Line 4430  namespace {
4430                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4431                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4432                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4433    
4434                    if (_3ewg->GetSize() > 32) {
4435                        // read MIDI rules
4436                        int i = 0;
4437                        _3ewg->SetPos(32);
4438                        uint8_t id1 = _3ewg->ReadUint8();
4439                        uint8_t id2 = _3ewg->ReadUint8();
4440    
4441                        if (id2 == 16) {
4442                            if (id1 == 4) {
4443                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4444                            } else if (id1 == 0) {
4445                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4446                            } else if (id1 == 3) {
4447                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4448                            } else {
4449                                pMidiRules[i++] = new MidiRuleUnknown;
4450                            }
4451                        }
4452                        else if (id1 != 0 || id2 != 0) {
4453                            pMidiRules[i++] = new MidiRuleUnknown;
4454                        }
4455                        //TODO: all the other types of rules
4456    
4457                        pMidiRules[i] = NULL;
4458                    }
4459                }
4460            }
4461    
4462            if (pFile->GetAutoLoad()) {
4463                if (!pRegions) pRegions = new RegionList;
4464                RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4465                if (lrgn) {
4466                    RIFF::List* rgn = lrgn->GetFirstSubList();
4467                    while (rgn) {
4468                        if (rgn->GetListType() == LIST_TYPE_RGN) {
4469                            __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4470                            pRegions->push_back(new Region(this, rgn));
4471                        }
4472                        rgn = lrgn->GetNextSubList();
4473                    }
4474                    // Creating Region Key Table for fast lookup
4475                    UpdateRegionKeyTable();
4476              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
4477          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
4478    
4479          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          // own gig format extensions
4480          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4481          pRegions = new Region*[Regions];          if (lst3LS) {
4482          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4483          RIFF::List* rgn = lrgn->GetFirstSubList();              if (ckSCSL) {
4484          unsigned int iRegion = 0;                  int headerSize = ckSCSL->ReadUint32();
4485          while (rgn) {                  int slotCount  = ckSCSL->ReadUint32();
4486              if (rgn->GetListType() == LIST_TYPE_RGN) {                  if (slotCount) {
4487                  __notify_progress(pProgress, (float) iRegion / (float) Regions);                      int slotSize  = ckSCSL->ReadUint32();
4488                  pRegions[iRegion] = new Region(this, rgn);                      ckSCSL->SetPos(headerSize); // in case of future header extensions
4489                  iRegion++;                      int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4490              }                      for (int i = 0; i < slotCount; ++i) {
4491              rgn = lrgn->GetNextSubList();                          _ScriptPooolEntry e;
4492          }                          e.fileOffset = ckSCSL->ReadUint32();
4493                            e.bypass     = ckSCSL->ReadUint32() & 1;
4494          // Creating Region Key Table for fast lookup                          if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4495          for (uint iReg = 0; iReg < Regions; iReg++) {                          scriptPoolFileOffsets.push_back(e);
4496              for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {                      }
4497                  RegionKeyTable[iKey] = pRegions[iReg];                  }
4498              }              }
4499          }          }
4500    
4501          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4502      }      }
4503    
4504        void Instrument::UpdateRegionKeyTable() {
4505            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4506            RegionList::iterator iter = pRegions->begin();
4507            RegionList::iterator end  = pRegions->end();
4508            for (; iter != end; ++iter) {
4509                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4510                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
4511                    RegionKeyTable[iKey] = pRegion;
4512                }
4513            }
4514        }
4515    
4516      Instrument::~Instrument() {      Instrument::~Instrument() {
4517          for (uint i = 0; i < Regions; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
4518              if (pRegions) {              delete pMidiRules[i];
4519                  if (pRegions[i]) delete (pRegions[i]);          }
4520            delete[] pMidiRules;
4521            if (pScriptRefs) delete pScriptRefs;
4522        }
4523    
4524        /**
4525         * Apply Instrument with all its Regions to the respective RIFF chunks.
4526         * You have to call File::Save() to make changes persistent.
4527         *
4528         * Usually there is absolutely no need to call this method explicitly.
4529         * It will be called automatically when File::Save() was called.
4530         *
4531         * @param pProgress - callback function for progress notification
4532         * @throws gig::Exception if samples cannot be dereferenced
4533         */
4534        void Instrument::UpdateChunks(progress_t* pProgress) {
4535            // first update base classes' chunks
4536            DLS::Instrument::UpdateChunks(pProgress);
4537    
4538            // update Regions' chunks
4539            {
4540                RegionList::iterator iter = pRegions->begin();
4541                RegionList::iterator end  = pRegions->end();
4542                for (; iter != end; ++iter)
4543                    (*iter)->UpdateChunks(pProgress);
4544            }
4545    
4546            // make sure 'lart' RIFF list chunk exists
4547            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
4548            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4549            // make sure '3ewg' RIFF chunk exists
4550            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4551            if (!_3ewg)  {
4552                File* pFile = (File*) GetParent();
4553    
4554                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4555                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4556                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4557                memset(_3ewg->LoadChunkData(), 0, size);
4558            }
4559            // update '3ewg' RIFF chunk
4560            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4561            store16(&pData[0], EffectSend);
4562            store32(&pData[2], Attenuation);
4563            store16(&pData[6], FineTune);
4564            store16(&pData[8], PitchbendRange);
4565            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4566                                        DimensionKeyRange.low << 1;
4567            pData[10] = dimkeystart;
4568            pData[11] = DimensionKeyRange.high;
4569    
4570            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4571                pData[32] = 0;
4572                pData[33] = 0;
4573            } else {
4574                for (int i = 0 ; pMidiRules[i] ; i++) {
4575                    pMidiRules[i]->UpdateChunks(pData);
4576              }              }
4577          }          }
4578          if (pRegions) delete[] pRegions;  
4579            // own gig format extensions
4580           if (ScriptSlotCount()) {
4581               // make sure we have converted the original loaded script file
4582               // offsets into valid Script object pointers
4583               LoadScripts();
4584    
4585               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4586               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4587               const int slotCount = pScriptRefs->size();
4588               const int headerSize = 3 * sizeof(uint32_t);
4589               const int slotSize  = 2 * sizeof(uint32_t);
4590               const int totalChunkSize = headerSize + slotCount * slotSize;
4591               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4592               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4593               else ckSCSL->Resize(totalChunkSize);
4594               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4595               int pos = 0;
4596               store32(&pData[pos], headerSize);
4597               pos += sizeof(uint32_t);
4598               store32(&pData[pos], slotCount);
4599               pos += sizeof(uint32_t);
4600               store32(&pData[pos], slotSize);
4601               pos += sizeof(uint32_t);
4602               for (int i = 0; i < slotCount; ++i) {
4603                   // arbitrary value, the actual file offset will be updated in
4604                   // UpdateScriptFileOffsets() after the file has been resized
4605                   int bogusFileOffset = 0;
4606                   store32(&pData[pos], bogusFileOffset);
4607                   pos += sizeof(uint32_t);
4608                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4609                   pos += sizeof(uint32_t);
4610               }
4611           } else {
4612               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4613               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4614               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4615           }
4616        }
4617    
4618        void Instrument::UpdateScriptFileOffsets() {
4619           // own gig format extensions
4620           if (pScriptRefs && pScriptRefs->size() > 0) {
4621               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4622               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4623               const int slotCount = pScriptRefs->size();
4624               const int headerSize = 3 * sizeof(uint32_t);
4625               ckSCSL->SetPos(headerSize);
4626               for (int i = 0; i < slotCount; ++i) {
4627                   uint32_t fileOffset =
4628                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4629                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4630                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4631                   ckSCSL->WriteUint32(&fileOffset);
4632                   // jump over flags entry (containing the bypass flag)
4633                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4634               }
4635           }        
4636      }      }
4637    
4638      /**      /**
# Line 1683  namespace { Line 4643  namespace {
4643       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4644       */       */
4645      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4646          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4647          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4648    
4649          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
4650              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
4651                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1700  namespace { Line 4661  namespace {
4661       * @see      GetNextRegion()       * @see      GetNextRegion()
4662       */       */
4663      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
4664          if (!Regions) return NULL;          if (!pRegions) return NULL;
4665          RegionIndex = 1;          RegionsIterator = pRegions->begin();
4666          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4667      }      }
4668    
4669      /**      /**
# Line 1714  namespace { Line 4675  namespace {
4675       * @see      GetFirstRegion()       * @see      GetFirstRegion()
4676       */       */
4677      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
4678          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
4679          return pRegions[RegionIndex++];          RegionsIterator++;
4680            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4681        }
4682    
4683        Region* Instrument::AddRegion() {
4684            // create new Region object (and its RIFF chunks)
4685            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
4686            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4687            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4688            Region* pNewRegion = new Region(this, rgn);
4689            pRegions->push_back(pNewRegion);
4690            Regions = pRegions->size();
4691            // update Region key table for fast lookup
4692            UpdateRegionKeyTable();
4693            // done
4694            return pNewRegion;
4695        }
4696    
4697        void Instrument::DeleteRegion(Region* pRegion) {
4698            if (!pRegions) return;
4699            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
4700            // update Region key table for fast lookup
4701            UpdateRegionKeyTable();
4702        }
4703    
4704        /**
4705         * Move this instrument at the position before @arg dst.
4706         *
4707         * This method can be used to reorder the sequence of instruments in a
4708         * .gig file. This might be helpful especially on large .gig files which
4709         * contain a large number of instruments within the same .gig file. So
4710         * grouping such instruments to similar ones, can help to keep track of them
4711         * when working with such complex .gig files.
4712         *
4713         * When calling this method, this instrument will be removed from in its
4714         * current position in the instruments list and moved to the requested
4715         * target position provided by @param dst. You may also pass NULL as
4716         * argument to this method, in that case this intrument will be moved to the
4717         * very end of the .gig file's instrument list.
4718         *
4719         * You have to call Save() to make the order change persistent to the .gig
4720         * file.
4721         *
4722         * Currently this method is limited to moving the instrument within the same
4723         * .gig file. Trying to move it to another .gig file by calling this method
4724         * will throw an exception.
4725         *
4726         * @param dst - destination instrument at which this instrument will be
4727         *              moved to, or pass NULL for moving to end of list
4728         * @throw gig::Exception if this instrument and target instrument are not
4729         *                       part of the same file
4730         */
4731        void Instrument::MoveTo(Instrument* dst) {
4732            if (dst && GetParent() != dst->GetParent())
4733                throw Exception(
4734                    "gig::Instrument::MoveTo() can only be used for moving within "
4735                    "the same gig file."
4736                );
4737    
4738            File* pFile = (File*) GetParent();
4739    
4740            // move this instrument within the instrument list
4741            {
4742                File::InstrumentList& list = *pFile->pInstruments;
4743    
4744                File::InstrumentList::iterator itFrom =
4745                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4746    
4747                File::InstrumentList::iterator itTo =
4748                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4749    
4750                list.splice(itTo, list, itFrom);
4751            }
4752    
4753            // move the instrument's actual list RIFF chunk appropriately
4754            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4755            lstCkInstruments->MoveSubChunk(
4756                this->pCkInstrument,
4757                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4758            );
4759        }
4760    
4761        /**
4762         * Returns a MIDI rule of the instrument.
4763         *
4764         * The list of MIDI rules, at least in gig v3, always contains at
4765         * most two rules. The second rule can only be the DEF filter
4766         * (which currently isn't supported by libgig).
4767         *
4768         * @param i - MIDI rule number
4769         * @returns   pointer address to MIDI rule number i or NULL if there is none
4770         */
4771        MidiRule* Instrument::GetMidiRule(int i) {
4772            return pMidiRules[i];
4773        }
4774    
4775        /**
4776         * Adds the "controller trigger" MIDI rule to the instrument.
4777         *
4778         * @returns the new MIDI rule
4779         */
4780        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4781            delete pMidiRules[0];
4782            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4783            pMidiRules[0] = r;
4784            pMidiRules[1] = 0;
4785            return r;
4786        }
4787    
4788        /**
4789         * Adds the legato MIDI rule to the instrument.
4790         *
4791         * @returns the new MIDI rule
4792         */
4793        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4794            delete pMidiRules[0];
4795            MidiRuleLegato* r = new MidiRuleLegato;
4796            pMidiRules[0] = r;
4797            pMidiRules[1] = 0;
4798            return r;
4799        }
4800    
4801        /**
4802         * Adds the alternator MIDI rule to the instrument.
4803         *
4804         * @returns the new MIDI rule
4805         */
4806        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4807            delete pMidiRules[0];
4808            MidiRuleAlternator* r = new MidiRuleAlternator;
4809            pMidiRules[0] = r;
4810            pMidiRules[1] = 0;
4811            return r;
4812        }
4813    
4814        /**
4815         * Deletes a MIDI rule from the instrument.
4816         *
4817         * @param i - MIDI rule number
4818         */
4819        void Instrument::DeleteMidiRule(int i) {
4820            delete pMidiRules[i];
4821            pMidiRules[i] = 0;
4822        }
4823    
4824        void Instrument::LoadScripts() {
4825            if (pScriptRefs) return;
4826            pScriptRefs = new std::vector<_ScriptPooolRef>;
4827            if (scriptPoolFileOffsets.empty()) return;
4828            File* pFile = (File*) GetParent();
4829            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4830                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4831                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4832                    ScriptGroup* group = pFile->GetScriptGroup(i);
4833                    for (uint s = 0; group->GetScript(s); ++s) {
4834                        Script* script = group->GetScript(s);
4835                        if (script->pChunk) {
4836                            uint32_t offset = script->pChunk->GetFilePos() -
4837                                              script->pChunk->GetPos() -
4838                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4839                            if (offset == soughtOffset)
4840                            {
4841                                _ScriptPooolRef ref;
4842                                ref.script = script;
4843                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4844                                pScriptRefs->push_back(ref);
4845                                break;
4846                            }
4847                        }
4848                    }
4849                }
4850            }
4851            // we don't need that anymore
4852            scriptPoolFileOffsets.clear();
4853        }
4854    
4855        /** @brief Get instrument script (gig format extension).
4856         *
4857         * Returns the real-time instrument script of instrument script slot
4858         * @a index.
4859         *
4860         * @note This is an own format extension which did not exist i.e. in the
4861         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4862         * gigedit.
4863         *
4864         * @param index - instrument script slot index
4865         * @returns script or NULL if index is out of bounds
4866         */
4867        Script* Instrument::GetScriptOfSlot(uint index) {
4868            LoadScripts();
4869            if (index >= pScriptRefs->size()) return NULL;
4870            return pScriptRefs->at(index).script;
4871        }
4872    
4873        /** @brief Add new instrument script slot (gig format extension).
4874         *
4875         * Add the given real-time instrument script reference to this instrument,
4876         * which shall be executed by the sampler for for this instrument. The
4877         * script will be added to the end of the script list of this instrument.
4878         * The positions of the scripts in the Instrument's Script list are
4879         * relevant, because they define in which order they shall be executed by
4880         * the sampler. For this reason it is also legal to add the same script
4881         * twice to an instrument, for example you might have a script called
4882         * "MyFilter" which performs an event filter task, and you might have
4883         * another script called "MyNoteTrigger" which triggers new notes, then you
4884         * might for example have the following list of scripts on the instrument:
4885         *
4886         * 1. Script "MyFilter"
4887         * 2. Script "MyNoteTrigger"
4888         * 3. Script "MyFilter"
4889         *
4890         * Which would make sense, because the 2nd script launched new events, which
4891         * you might need to filter as well.
4892         *
4893         * There are two ways to disable / "bypass" scripts. You can either disable
4894         * a script locally for the respective script slot on an instrument (i.e. by
4895         * passing @c false to the 2nd argument of this method, or by calling
4896         * SetScriptBypassed()). Or you can disable a script globally for all slots
4897         * and all instruments by setting Script::Bypass.
4898         *
4899         * @note This is an own format extension which did not exist i.e. in the
4900         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4901         * gigedit.
4902         *
4903         * @param pScript - script that shall be executed for this instrument
4904         * @param bypass  - if enabled, the sampler shall skip executing this
4905         *                  script (in the respective list position)
4906         * @see SetScriptBypassed()
4907         */
4908        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4909            LoadScripts();
4910            _ScriptPooolRef ref = { pScript, bypass };
4911            pScriptRefs->push_back(ref);
4912        }
4913    
4914        /** @brief Flip two script slots with each other (gig format extension).
4915         *
4916         * Swaps the position of the two given scripts in the Instrument's Script
4917         * list. The positions of the scripts in the Instrument's Script list are
4918         * relevant, because they define in which order they shall be executed by
4919         * the sampler.
4920         *
4921         * @note This is an own format extension which did not exist i.e. in the
4922         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4923         * gigedit.
4924         *
4925         * @param index1 - index of the first script slot to swap
4926         * @param index2 - index of the second script slot to swap
4927         */
4928        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4929            LoadScripts();
4930            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4931                return;
4932            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4933            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4934            (*pScriptRefs)[index2] = tmp;
4935        }
4936    
4937        /** @brief Remove script slot.
4938         *
4939         * Removes the script slot with the given slot index.
4940         *
4941         * @param index - index of script slot to remove
4942         */
4943        void Instrument::RemoveScriptSlot(uint index) {
4944            LoadScripts();
4945            if (index >= pScriptRefs->size()) return;
4946            pScriptRefs->erase( pScriptRefs->begin() + index );
4947        }
4948    
4949        /** @brief Remove reference to given Script (gig format extension).
4950         *
4951         * This will remove all script slots on the instrument which are referencing
4952         * the given script.
4953         *
4954         * @note This is an own format extension which did not exist i.e. in the
4955         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4956         * gigedit.
4957         *
4958         * @param pScript - script reference to remove from this instrument
4959         * @see RemoveScriptSlot()
4960         */
4961        void Instrument::RemoveScript(Script* pScript) {
4962            LoadScripts();
4963            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4964                if ((*pScriptRefs)[i].script == pScript) {
4965                    pScriptRefs->erase( pScriptRefs->begin() + i );
4966                }
4967            }
4968        }
4969    
4970        /** @brief Instrument's amount of script slots.
4971         *
4972         * This method returns the amount of script slots this instrument currently
4973         * uses.
4974         *
4975         * A script slot is a reference of a real-time instrument script to be
4976         * executed by the sampler. The scripts will be executed by the sampler in
4977         * sequence of the slots. One (same) script may be referenced multiple
4978         * times in different slots.
4979         *
4980         * @note This is an own format extension which did not exist i.e. in the
4981         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4982         * gigedit.
4983         */
4984        uint Instrument::ScriptSlotCount() const {
4985            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4986        }
4987    
4988        /** @brief Whether script execution shall be skipped.
4989         *
4990         * Defines locally for the Script reference slot in the Instrument's Script
4991         * list, whether the script shall be skipped by the sampler regarding
4992         * execution.
4993         *
4994         * It is also possible to ignore exeuction of the script globally, for all
4995         * slots and for all instruments by setting Script::Bypass.
4996         *
4997         * @note This is an own format extension which did not exist i.e. in the
4998         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4999         * gigedit.
5000         *
5001         * @param index - index of the script slot on this instrument
5002         * @see Script::Bypass
5003         */
5004        bool Instrument::IsScriptSlotBypassed(uint index) {
5005            if (index >= ScriptSlotCount()) return false;
5006            return pScriptRefs ? pScriptRefs->at(index).bypass
5007                               : scriptPoolFileOffsets.at(index).bypass;
5008            
5009        }
5010    
5011        /** @brief Defines whether execution shall be skipped.
5012         *
5013         * You can call this method to define locally whether or whether not the
5014         * given script slot shall be executed by the sampler.
5015         *
5016         * @note This is an own format extension which did not exist i.e. in the
5017         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5018         * gigedit.
5019         *
5020         * @param index - script slot index on this instrument
5021         * @param bBypass - if true, the script slot will be skipped by the sampler
5022         * @see Script::Bypass
5023         */
5024        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5025            if (index >= ScriptSlotCount()) return;
5026            if (pScriptRefs)
5027                pScriptRefs->at(index).bypass = bBypass;
5028            else
5029                scriptPoolFileOffsets.at(index).bypass = bBypass;
5030        }
5031    
5032        /**
5033         * Make a (semi) deep copy of the Instrument object given by @a orig
5034         * and assign it to this object.
5035         *
5036         * Note that all sample pointers referenced by @a orig are simply copied as
5037         * memory address. Thus the respective samples are shared, not duplicated!
5038         *
5039         * @param orig - original Instrument object to be copied from
5040         */
5041        void Instrument::CopyAssign(const Instrument* orig) {
5042            CopyAssign(orig, NULL);
5043        }
5044            
5045        /**
5046         * Make a (semi) deep copy of the Instrument object given by @a orig
5047         * and assign it to this object.
5048         *
5049         * @param orig - original Instrument object to be copied from
5050         * @param mSamples - crosslink map between the foreign file's samples and
5051         *                   this file's samples
5052         */
5053        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5054            // handle base class
5055            // (without copying DLS region stuff)
5056            DLS::Instrument::CopyAssignCore(orig);
5057            
5058            // handle own member variables
5059            Attenuation = orig->Attenuation;
5060            EffectSend = orig->EffectSend;
5061            FineTune = orig->FineTune;
5062            PitchbendRange = orig->PitchbendRange;
5063            PianoReleaseMode = orig->PianoReleaseMode;
5064            DimensionKeyRange = orig->DimensionKeyRange;
5065            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5066            pScriptRefs = orig->pScriptRefs;
5067            
5068            // free old midi rules
5069            for (int i = 0 ; pMidiRules[i] ; i++) {
5070                delete pMidiRules[i];
5071            }
5072            //TODO: MIDI rule copying
5073            pMidiRules[0] = NULL;
5074            
5075            // delete all old regions
5076            while (Regions) DeleteRegion(GetFirstRegion());
5077            // create new regions and copy them from original
5078            {
5079                RegionList::const_iterator it = orig->pRegions->begin();
5080                for (int i = 0; i < orig->Regions; ++i, ++it) {
5081                    Region* dstRgn = AddRegion();
5082                    //NOTE: Region does semi-deep copy !
5083                    dstRgn->CopyAssign(
5084                        static_cast<gig::Region*>(*it),
5085                        mSamples
5086                    );
5087                }
5088            }
5089    
5090            UpdateRegionKeyTable();
5091        }
5092    
5093    
5094    // *************** Group ***************
5095    // *
5096    
5097        /** @brief Constructor.
5098         *
5099         * @param file   - pointer to the gig::File object
5100         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
5101         *                 NULL if this is a new Group
5102         */
5103        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5104            pFile      = file;
5105            pNameChunk = ck3gnm;
5106            ::LoadString(pNameChunk, Name);
5107        }
5108    
5109        Group::~Group() {
5110            // remove the chunk associated with this group (if any)
5111            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5112        }
5113    
5114        /** @brief Update chunks with current group settings.
5115         *
5116         * Apply current Group field values to the respective chunks. You have
5117         * to call File::Save() to make changes persistent.
5118         *
5119         * Usually there is absolutely no need to call this method explicitly.
5120         * It will be called automatically when File::Save() was called.
5121         *
5122         * @param pProgress - callback function for progress notification
5123         */
5124        void Group::UpdateChunks(progress_t* pProgress) {
5125            // make sure <3gri> and <3gnl> list chunks exist
5126            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5127            if (!_3gri) {
5128                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5129                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5130            }
5131            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5132            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5133    
5134            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5135                // v3 has a fixed list of 128 strings, find a free one
5136                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5137                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5138                        pNameChunk = ck;
5139                        break;
5140                    }
5141                }
5142            }
5143    
5144            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5145            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5146        }
5147    
5148        /**
5149         * Returns the first Sample of this Group. You have to call this method
5150         * once before you use GetNextSample().
5151         *
5152         * <b>Notice:</b> this method might block for a long time, in case the
5153         * samples of this .gig file were not scanned yet
5154         *
5155         * @returns  pointer address to first Sample or NULL if there is none
5156         *           applied to this Group
5157         * @see      GetNextSample()
5158         */
5159        Sample* Group::GetFirstSample() {
5160            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5161            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5162                if (pSample->GetGroup() == this) return pSample;
5163            }
5164            return NULL;
5165        }
5166    
5167        /**
5168         * Returns the next Sample of the Group. You have to call
5169         * GetFirstSample() once before you can use this method. By calling this
5170         * method multiple times it iterates through the Samples assigned to
5171         * this Group.
5172         *
5173         * @returns  pointer address to the next Sample of this Group or NULL if
5174         *           end reached
5175         * @see      GetFirstSample()
5176         */
5177        Sample* Group::GetNextSample() {
5178            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5179            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5180                if (pSample->GetGroup() == this) return pSample;
5181            }
5182            return NULL;
5183        }
5184    
5185        /**
5186         * Move Sample given by \a pSample from another Group to this Group.
5187         */
5188        void Group::AddSample(Sample* pSample) {
5189            pSample->pGroup = this;
5190        }
5191    
5192        /**
5193         * Move all members of this group to another group (preferably the 1st
5194         * one except this). This method is called explicitly by
5195         * File::DeleteGroup() thus when a Group was deleted. This code was
5196         * intentionally not placed in the destructor!
5197         */
5198        void Group::MoveAll() {
5199            // get "that" other group first
5200            Group* pOtherGroup = NULL;
5201            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5202                if (pOtherGroup != this) break;
5203            }
5204            if (!pOtherGroup) throw Exception(
5205                "Could not move samples to another group, since there is no "
5206                "other Group. This is a bug, report it!"
5207            );
5208            // now move all samples of this group to the other group
5209            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5210                pOtherGroup->AddSample(pSample);
5211            }
5212      }      }
5213    
5214    
# Line 1723  namespace { Line 5216  namespace {
5216  // *************** File ***************  // *************** File ***************
5217  // *  // *
5218    
5219        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5220        const DLS::version_t File::VERSION_2 = {
5221            0, 2, 19980628 & 0xffff, 19980628 >> 16
5222        };
5223    
5224        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5225        const DLS::version_t File::VERSION_3 = {
5226            0, 3, 20030331 & 0xffff, 20030331 >> 16
5227        };
5228    
5229        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5230            { CHUNK_ID_IARL, 256 },
5231            { CHUNK_ID_IART, 128 },
5232            { CHUNK_ID_ICMS, 128 },
5233            { CHUNK_ID_ICMT, 1024 },
5234            { CHUNK_ID_ICOP, 128 },
5235            { CHUNK_ID_ICRD, 128 },
5236            { CHUNK_ID_IENG, 128 },
5237            { CHUNK_ID_IGNR, 128 },
5238            { CHUNK_ID_IKEY, 128 },
5239            { CHUNK_ID_IMED, 128 },
5240            { CHUNK_ID_INAM, 128 },
5241            { CHUNK_ID_IPRD, 128 },
5242            { CHUNK_ID_ISBJ, 128 },
5243            { CHUNK_ID_ISFT, 128 },
5244            { CHUNK_ID_ISRC, 128 },
5245            { CHUNK_ID_ISRF, 128 },
5246            { CHUNK_ID_ITCH, 128 },
5247            { 0, 0 }
5248        };
5249    
5250        File::File() : DLS::File() {
5251            bAutoLoad = true;
5252            *pVersion = VERSION_3;
5253            pGroups = NULL;
5254            pScriptGroups = NULL;
5255            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5256            pInfo->ArchivalLocation = String(256, ' ');
5257    
5258            // add some mandatory chunks to get the file chunks in right
5259            // order (INFO chunk will be moved to first position later)
5260            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5261            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5262            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5263    
5264            GenerateDLSID();
5265        }
5266    
5267      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5268          pSamples     = NULL;          bAutoLoad = true;
5269          pInstruments = NULL;          pGroups = NULL;
5270            pScriptGroups = NULL;
5271            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5272      }      }
5273    
5274      File::~File() {      File::~File() {
5275          // free samples          if (pGroups) {
5276          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
5277              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
5278              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
5279                  delete (*SamplesIterator);                  delete *iter;
5280                  SamplesIterator++;                  ++iter;
5281              }              }
5282              pSamples->clear();              delete pGroups;
5283              delete pSamples;          }
5284            if (pScriptGroups) {
5285          }              std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5286          // free instruments              std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5287          if (pInstruments) {              while (iter != end) {
5288              InstrumentsIterator = pInstruments->begin();                  delete *iter;
5289              while (InstrumentsIterator != pInstruments->end() ) {                  ++iter;
5290                  delete (*InstrumentsIterator);              }
5291                  InstrumentsIterator++;              delete pScriptGroups;
5292              }          }
             pInstruments->clear();  
             delete pInstruments;  
         }  
         // free extension files  
         for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)  
             delete *i;  
5293      }      }
5294    
5295      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 1767  namespace { Line 5304  namespace {
5304          SamplesIterator++;          SamplesIterator++;
5305          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5306      }      }
5307        
5308        /**
5309         * Returns Sample object of @a index.
5310         *
5311         * @returns sample object or NULL if index is out of bounds
5312         */
5313        Sample* File::GetSample(uint index) {
5314            if (!pSamples) LoadSamples();
5315            if (!pSamples) return NULL;
5316            DLS::File::SampleList::iterator it = pSamples->begin();
5317            for (int i = 0; i < index; ++i) {
5318                ++it;
5319                if (it == pSamples->end()) return NULL;
5320            }
5321            if (it == pSamples->end()) return NULL;
5322            return static_cast<gig::Sample*>( *it );
5323        }
5324    
5325        /** @brief Add a new sample.
5326         *
5327         * This will create a new Sample object for the gig file. You have to
5328         * call Save() to make this persistent to the file.
5329         *
5330         * @returns pointer to new Sample object
5331         */
5332        Sample* File::AddSample() {
5333           if (!pSamples) LoadSamples();
5334           __ensureMandatoryChunksExist();
5335           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
5336           // create new Sample object and its respective 'wave' list chunk
5337           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5338           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5339    
5340           // add mandatory chunks to get the chunks in right order
5341           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5342           wave->AddSubList(LIST_TYPE_INFO);
5343    
5344           pSamples->push_back(pSample);
5345           return pSample;
5346        }
5347    
5348        /** @brief Delete a sample.
5349         *
5350         * This will delete the given Sample object from the gig file. Any
5351         * references to this sample from Regions and DimensionRegions will be
5352         * removed. You have to call Save() to make this persistent to the file.
5353         *
5354         * @param pSample - sample to delete
5355         * @throws gig::Exception if given sample could not be found
5356         */
5357        void File::DeleteSample(Sample* pSample) {
5358            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5359            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5360            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5361            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5362            pSamples->erase(iter);
5363            delete pSample;
5364    
5365            SampleList::iterator tmp = SamplesIterator;
5366            // remove all references to the sample
5367            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5368                 instrument = GetNextInstrument()) {
5369                for (Region* region = instrument->GetFirstRegion() ; region ;
5370                     region = instrument->GetNextRegion()) {
5371    
5372                    if (region->GetSample() == pSample) region->SetSample(NULL);
5373    
5374                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5375                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5376                        if (d->pSample == pSample) d->pSample = NULL;
5377                    }
5378                }
5379            }
5380            SamplesIterator = tmp; // restore iterator
5381        }
5382    
5383        void File::LoadSamples() {
5384            LoadSamples(NULL);
5385        }
5386    
5387      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
5388            // Groups must be loaded before samples, because samples will try
5389            // to resolve the group they belong to
5390            if (!pGroups) LoadGroups();
5391    
5392            if (!pSamples) pSamples = new SampleList;
5393    
5394          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
5395    
5396          // just for progress calculation          // just for progress calculation
# Line 1776  namespace { Line 5398  namespace {
5398          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5399    
5400          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5401            // (only for old gig files < 2 GB)
5402          int lastFileNo = 0;          int lastFileNo = 0;
5403          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5404              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5405                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5406                }
5407          }          }
5408          String name(pRIFF->Filename);          String name(pRIFF->GetFileName());
5409          int nameLen = pRIFF->Filename.length();          int nameLen = name.length();
5410          char suffix[6];          char suffix[6];
5411          if (nameLen > 4 && pRIFF->Filename.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5412    
5413          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5414              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5415              if (wvpl) {              if (wvpl) {
5416                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5417                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5418                  while (wave) {                  while (wave) {
5419                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 1796  namespace { Line 5421  namespace {
5421                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5422                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5423    
5424                          if (!pSamples) pSamples = new SampleList;                          file_offset_t waveFileOffset = wave->GetFilePos();
                         unsigned long waveFileOffset = wave->GetFilePos();  
5425                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5426    
5427                          iSampleIndex++;                          iSampleIndex++;
# Line 1813  namespace { Line 5437  namespace {
5437                  name.replace(nameLen, 5, suffix);                  name.replace(nameLen, 5, suffix);
5438                  file = new RIFF::File(name);                  file = new RIFF::File(name);
5439                  ExtensionFiles.push_back(file);                  ExtensionFiles.push_back(file);
5440              }              } else break;
             else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
5441          }          }
5442    
5443          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
# Line 1824  namespace { Line 5447  namespace {
5447          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
5448          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5449          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
5450          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5451      }      }
5452    
5453      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
5454          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5455          InstrumentsIterator++;          InstrumentsIterator++;
5456          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5457      }      }
5458    
5459      /**      /**
# Line 1848  namespace { Line 5471  namespace {
5471              progress_t subprogress;              progress_t subprogress;
5472              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5473              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5474              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5475                    GetFirstSample(&subprogress); // now force all samples to be loaded
5476              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5477    
5478              // instrument loading subtask              // instrument loading subtask
# Line 1863  namespace { Line 5487  namespace {
5487          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5488          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
5489          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5490              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5491              InstrumentsIterator++;              InstrumentsIterator++;
5492          }          }
5493          return NULL;          return NULL;
5494      }      }
5495    
5496        /** @brief Add a new instrument definition.
5497         *
5498         * This will create a new Instrument object for the gig file. You have
5499         * to call Save() to make this persistent to the file.
5500         *
5501         * @returns pointer to new Instrument object
5502         */
5503        Instrument* File::AddInstrument() {
5504           if (!pInstruments) LoadInstruments();
5505           __ensureMandatoryChunksExist();
5506           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5507           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5508    
5509           // add mandatory chunks to get the chunks in right order
5510           lstInstr->AddSubList(LIST_TYPE_INFO);
5511           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5512    
5513           Instrument* pInstrument = new Instrument(this, lstInstr);
5514           pInstrument->GenerateDLSID();
5515    
5516           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5517    
5518           // this string is needed for the gig to be loadable in GSt:
5519           pInstrument->pInfo->Software = "Endless Wave";
5520    
5521           pInstruments->push_back(pInstrument);
5522           return pInstrument;
5523        }
5524        
5525        /** @brief Add a duplicate of an existing instrument.
5526         *
5527         * Duplicates the instrument definition given by @a orig and adds it
5528         * to this file. This allows in an instrument editor application to
5529         * easily create variations of an instrument, which will be stored in
5530         * the same .gig file, sharing i.e. the same samples.
5531         *
5532         * Note that all sample pointers referenced by @a orig are simply copied as
5533         * memory address. Thus the respective samples are shared, not duplicated!
5534         *
5535         * You have to call Save() to make this persistent to the file.
5536         *
5537         * @param orig - original instrument to be copied
5538         * @returns duplicated copy of the given instrument
5539         */
5540        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5541            Instrument* instr = AddInstrument();
5542            instr->CopyAssign(orig);
5543            return instr;
5544        }
5545        
5546        /** @brief Add content of another existing file.
5547         *
5548         * Duplicates the samples, groups and instruments of the original file
5549         * given by @a pFile and adds them to @c this File. In case @c this File is
5550         * a new one that you haven't saved before, then you have to call
5551         * SetFileName() before calling AddContentOf(), because this method will
5552         * automatically save this file during operation, which is required for
5553         * writing the sample waveform data by disk streaming.
5554         *
5555         * @param pFile - original file whose's content shall be copied from
5556         */
5557        void File::AddContentOf(File* pFile) {
5558            static int iCallCount = -1;
5559            iCallCount++;
5560            std::map<Group*,Group*> mGroups;
5561            std::map<Sample*,Sample*> mSamples;
5562            
5563            // clone sample groups
5564            for (int i = 0; pFile->GetGroup(i); ++i) {
5565                Group* g = AddGroup();
5566                g->Name =
5567                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5568                mGroups[pFile->GetGroup(i)] = g;
5569            }
5570            
5571            // clone samples (not waveform data here yet)
5572            for (int i = 0; pFile->GetSample(i); ++i) {
5573                Sample* s = AddSample();
5574                s->CopyAssignMeta(pFile->GetSample(i));
5575                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5576                mSamples[pFile->GetSample(i)] = s;
5577            }
5578            
5579            //BUG: For some reason this method only works with this additional
5580            //     Save() call in between here.
5581            //
5582            // Important: The correct one of the 2 Save() methods has to be called
5583            // here, depending on whether the file is completely new or has been
5584            // saved to disk already, otherwise it will result in data corruption.
5585            if (pRIFF->IsNew())
5586                Save(GetFileName());
5587            else
5588                Save();
5589            
5590            // clone instruments
5591            // (passing the crosslink table here for the cloned samples)
5592            for (int i = 0; pFile->GetInstrument(i); ++i) {
5593                Instrument* instr = AddInstrument();
5594                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5595            }
5596            
5597            // Mandatory: file needs to be saved to disk at this point, so this
5598            // file has the correct size and data layout for writing the samples'
5599            // waveform data to disk.
5600            Save();
5601            
5602            // clone samples' waveform data
5603            // (using direct read & write disk streaming)
5604            for (int i = 0; pFile->GetSample(i); ++i) {
5605                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5606            }
5607        }
5608    
5609        /** @brief Delete an instrument.
5610         *
5611         * This will delete the given Instrument object from the gig file. You
5612         * have to call Save() to make this persistent to the file.
5613         *
5614         * @param pInstrument - instrument to delete
5615         * @throws gig::Exception if given instrument could not be found
5616         */
5617        void File::DeleteInstrument(Instrument* pInstrument) {
5618            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5619            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5620            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5621            pInstruments->erase(iter);
5622            delete pInstrument;
5623        }
5624    
5625        void File::LoadInstruments() {
5626            LoadInstruments(NULL);
5627        }
5628    
5629      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
5630            if (!pInstruments) pInstruments = new InstrumentList;
5631          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5632          if (lstInstruments) {          if (lstInstruments) {
5633              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1884  namespace { Line 5642  namespace {
5642                      progress_t subprogress;                      progress_t subprogress;
5643                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5644    
                     if (!pInstruments) pInstruments = new InstrumentList;  
5645                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5646    
5647                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1893  namespace { Line 5650  namespace {
5650              }              }
5651              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
5652          }          }
5653          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
5654    
5655        /// Updates the 3crc chunk with the checksum of a sample. The
5656        /// update is done directly to disk, as this method is called
5657        /// after File::Save()
5658        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5659            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5660            if (!_3crc) return;
5661    
5662            // get the index of the sample
5663            int iWaveIndex = GetWaveTableIndexOf(pSample);
5664            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5665    
5666            // write the CRC-32 checksum to disk
5667            _3crc->SetPos(iWaveIndex * 8);
5668            uint32_t one = 1;
5669            _3crc->WriteUint32(&one); // always 1
5670            _3crc->WriteUint32(&crc);
5671    
5672            // reload CRC table to RAM to keep it persistent over several subsequent save operations
5673            _3crc->ReleaseChunkData();
5674            _3crc->LoadChunkData();
5675        }
5676    
5677        uint32_t File::GetSampleChecksum(Sample* pSample) {
5678            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5679            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5680            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5681            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5682    
5683            // get the index of the sample
5684            int iWaveIndex = GetWaveTableIndexOf(pSample);
5685            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5686    
5687            // read the CRC-32 checksum directly from disk
5688            size_t pos = iWaveIndex * 8;
5689            if (pos + 8 > _3crc->GetNewSize())
5690                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5691    
5692            uint32_t one = load32(&pData[pos]); // always 1
5693            if (one != 1)
5694                throw gig::Exception("Could not verify sample, because reference checksum table is damaged");
5695    
5696            return load32(&pData[pos+4]);
5697        }
5698        
5699        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5700            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5701            File::SampleList::iterator iter = pSamples->begin();
5702            File::SampleList::iterator end  = pSamples->end();
5703            for (int index = 0; iter != end; ++iter, ++index)
5704                if (*iter == pSample)
5705                    return index;
5706            return -1;
5707        }
5708    
5709        /**
5710         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5711         * the CRC32 check sums of all samples' raw wave data.
5712         *
5713         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5714         */
5715        bool File::VerifySampleChecksumTable() {
5716            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5717            if (!_3crc) return false;
5718            if (_3crc->GetNewSize() <= 0) return false;
5719            if (_3crc->GetNewSize() % 8) return false;
5720            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5721            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5722    
5723            const int n = _3crc->GetNewSize() / 8;
5724    
5725            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5726            if (!pData) return false;
5727    
5728            for (int i = 0; i < n; ++i) {
5729                uint32_t one = pData[i*2];
5730                if (one != 1) return false;
5731            }
5732    
5733            return true;
5734        }
5735    
5736        /**
5737         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5738         * file's checksum table with those new checksums. This might usually
5739         * just be necessary if the checksum table was damaged.
5740         *
5741         * @e IMPORTANT: The current implementation of this method only works
5742         * with files that have not been modified since it was loaded, because
5743         * it expects that no externally caused file structure changes are
5744         * required!
5745         *
5746         * Due to the expectation above, this method is currently protected
5747         * and actually only used by the command line tool "gigdump" yet.
5748         *
5749         * @returns true if Save() is required to be called after this call,
5750         *          false if no further action is required
5751         */
5752        bool File::RebuildSampleChecksumTable() {
5753            // make sure sample chunks were scanned
5754            if (!pSamples) GetFirstSample();
5755    
5756            bool bRequiresSave = false;
5757    
5758            // make sure "3CRC" chunk exists with required size
5759            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5760            if (!_3crc) {
5761                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5762                bRequiresSave = true;
5763            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5764                _3crc->Resize(pSamples->size() * 8);
5765                bRequiresSave = true;
5766            }
5767    
5768            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5769                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5770                {
5771                    File::SampleList::iterator iter = pSamples->begin();
5772                    File::SampleList::iterator end  = pSamples->end();
5773                    for (; iter != end; ++iter) {
5774                        gig::Sample* pSample = (gig::Sample*) *iter;
5775                        int index = GetWaveTableIndexOf(pSample);
5776                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5777                        pData[index*2]   = 1; // always 1
5778                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5779                    }
5780                }
5781            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5782                // make sure file is in write mode
5783                pRIFF->SetMode(RIFF::stream_mode_read_write);
5784                {
5785                    File::SampleList::iterator iter = pSamples->begin();
5786                    File::SampleList::iterator end  = pSamples->end();
5787                    for (; iter != end; ++iter) {
5788                        gig::Sample* pSample = (gig::Sample*) *iter;
5789                        int index = GetWaveTableIndexOf(pSample);
5790                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5791                        uint32_t crc = pSample->CalculateWaveDataChecksum();
5792                        SetSampleChecksum(pSample, crc);
5793                    }
5794                }
5795            }
5796    
5797            return bRequiresSave;
5798        }
5799    
5800        Group* File::GetFirstGroup() {
5801            if (!pGroups) LoadGroups();
5802            // there must always be at least one group
5803            GroupsIterator = pGroups->begin();
5804            return *GroupsIterator;
5805        }
5806    
5807        Group* File::GetNextGroup() {
5808            if (!pGroups) return NULL;
5809            ++GroupsIterator;
5810            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5811        }
5812    
5813        /**
5814         * Returns the group with the given index.
5815         *
5816         * @param index - number of the sought group (0..n)
5817         * @returns sought group or NULL if there's no such group
5818         */
5819        Group* File::GetGroup(uint index) {
5820            if (!pGroups) LoadGroups();
5821            GroupsIterator = pGroups->begin();
5822            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5823                if (i == index) return *GroupsIterator;
5824                ++GroupsIterator;
5825            }
5826            return NULL;
5827        }
5828    
5829        /**
5830         * Returns the group with the given group name.
5831         *
5832         * Note: group names don't have to be unique in the gig format! So there
5833         * can be multiple groups with the same name. This method will simply
5834         * return the first group found with the given name.
5835         *
5836         * @param name - name of the sought group
5837         * @returns sought group or NULL if there's no group with that name
5838         */
5839        Group* File::GetGroup(String name) {
5840            if (!pGroups) LoadGroups();
5841            GroupsIterator = pGroups->begin();
5842            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5843                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5844            return NULL;
5845        }
5846    
5847        Group* File::AddGroup() {
5848            if (!pGroups) LoadGroups();
5849            // there must always be at least one group
5850            __ensureMandatoryChunksExist();
5851            Group* pGroup = new Group(this, NULL);
5852            pGroups->push_back(pGroup);
5853            return pGroup;
5854        }
5855    
5856        /** @brief Delete a group and its samples.
5857         *
5858         * This will delete the given Group object and all the samples that
5859         * belong to this group from the gig file. You have to call Save() to
5860         * make this persistent to the file.
5861         *
5862         * @param pGroup - group to delete
5863         * @throws gig::Exception if given group could not be found
5864         */
5865        void File::DeleteGroup(Group* pGroup) {
5866            if (!pGroups) LoadGroups();
5867            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5868            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5869            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5870            // delete all members of this group
5871            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5872                DeleteSample(pSample);
5873            }
5874            // now delete this group object
5875            pGroups->erase(iter);
5876            delete pGroup;
5877        }
5878    
5879        /** @brief Delete a group.
5880         *
5881         * This will delete the given Group object from the gig file. All the
5882         * samples that belong to this group will not be deleted, but instead
5883         * be moved to another group. You have to call Save() to make this
5884         * persistent to the file.
5885         *
5886         * @param pGroup - group to delete
5887         * @throws gig::Exception if given group could not be found
5888         */
5889        void File::DeleteGroupOnly(Group* pGroup) {
5890            if (!pGroups) LoadGroups();
5891            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5892            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5893            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5894            // move all members of this group to another group
5895            pGroup->MoveAll();
5896            pGroups->erase(iter);
5897            delete pGroup;
5898        }
5899    
5900        void File::LoadGroups() {
5901            if (!pGroups) pGroups = new std::list<Group*>;
5902            // try to read defined groups from file
5903            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5904            if (lst3gri) {
5905                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5906                if (lst3gnl) {
5907                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5908                    while (ck) {
5909                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5910                            if (pVersion && pVersion->major == 3 &&
5911                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5912    
5913                            pGroups->push_back(new Group(this, ck));
5914                        }
5915                        ck = lst3gnl->GetNextSubChunk();
5916                    }
5917                }
5918            }
5919            // if there were no group(s), create at least the mandatory default group
5920            if (!pGroups->size()) {
5921                Group* pGroup = new Group(this, NULL);
5922                pGroup->Name = "Default Group";
5923                pGroups->push_back(pGroup);
5924            }
5925        }
5926    
5927        /** @brief Get instrument script group (by index).
5928         *
5929         * Returns the real-time instrument script group with the given index.
5930         *
5931         * @param index - number of the sought group (0..n)
5932         * @returns sought script group or NULL if there's no such group
5933         */
5934        ScriptGroup* File::GetScriptGroup(uint index) {
5935            if (!pScriptGroups) LoadScriptGroups();
5936            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5937            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5938                if (i == index) return *it;
5939            return NULL;
5940        }
5941    
5942        /** @brief Get instrument script group (by name).
5943         *
5944         * Returns the first real-time instrument script group found with the given
5945         * group name. Note that group names may not necessarily be unique.
5946         *
5947         * @param name - name of the sought script group
5948         * @returns sought script group or NULL if there's no such group
5949         */
5950        ScriptGroup* File::GetScriptGroup(const String& name) {
5951            if (!pScriptGroups) LoadScriptGroups();
5952            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5953            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5954                if ((*it)->Name == name) return *it;
5955            return NULL;
5956        }
5957    
5958        /** @brief Add new instrument script group.
5959         *
5960         * Adds a new, empty real-time instrument script group to the file.
5961         *
5962         * You have to call Save() to make this persistent to the file.
5963         *
5964         * @return new empty script group
5965         */
5966        ScriptGroup* File::AddScriptGroup() {
5967            if (!pScriptGroups) LoadScriptGroups();
5968            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5969            pScriptGroups->push_back(pScriptGroup);
5970            return pScriptGroup;
5971        }
5972    
5973        /** @brief Delete an instrument script group.
5974         *
5975         * This will delete the given real-time instrument script group and all its
5976         * instrument scripts it contains. References inside instruments that are
5977         * using the deleted scripts will be removed from the respective instruments
5978         * accordingly.
5979         *
5980         * You have to call Save() to make this persistent to the file.
5981         *
5982         * @param pScriptGroup - script group to delete
5983         * @throws gig::Exception if given script group could not be found
5984         */
5985        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5986            if (!pScriptGroups) LoadScriptGroups();
5987            std::list<ScriptGroup*>::iterator iter =
5988                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5989            if (iter == pScriptGroups->end())
5990                throw gig::Exception("Could not delete script group, could not find given script group");
5991            pScriptGroups->erase(iter);
5992            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5993                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5994            if (pScriptGroup->pList)
5995                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5996            delete pScriptGroup;
5997        }
5998    
5999        void File::LoadScriptGroups() {
6000            if (pScriptGroups) return;
6001            pScriptGroups = new std::list<ScriptGroup*>;
6002            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6003            if (lstLS) {
6004                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6005                     lst = lstLS->GetNextSubList())
6006                {
6007                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6008                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6009                    }
6010                }
6011            }
6012        }
6013    
6014        /**
6015         * Apply all the gig file's current instruments, samples, groups and settings
6016         * to the respective RIFF chunks. You have to call Save() to make changes
6017         * persistent.
6018         *
6019         * Usually there is absolutely no need to call this method explicitly.
6020         * It will be called automatically when File::Save() was called.
6021         *
6022         * @param pProgress - callback function for progress notification
6023         * @throws Exception - on errors
6024         */
6025        void File::UpdateChunks(progress_t* pProgress) {
6026            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6027    
6028            // update own gig format extension chunks
6029            // (not part of the GigaStudio 4 format)
6030            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6031            if (!lst3LS) {
6032                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6033            }
6034            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6035            // location of <3LS > is irrelevant, however it should be located
6036            // before  the actual wave data
6037            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6038            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6039    
6040            // This must be performed before writing the chunks for instruments,
6041            // because the instruments' script slots will write the file offsets
6042            // of the respective instrument script chunk as reference.
6043            if (pScriptGroups) {
6044                // Update instrument script (group) chunks.
6045                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6046                     it != pScriptGroups->end(); ++it)
6047                {
6048                    (*it)->UpdateChunks(pProgress);
6049                }
6050            }
6051    
6052            // in case no libgig custom format data was added, then remove the
6053            // custom "3LS " chunk again
6054            if (!lst3LS->CountSubChunks()) {
6055                pRIFF->DeleteSubChunk(lst3LS);
6056                lst3LS = NULL;
6057            }
6058    
6059            // if there is a 3CRC chunk, make sure it is loaded into RAM, otherwise
6060            // its data might get lost or damaged on file structure changes
6061            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6062            if (_3crc) _3crc->LoadChunkData();
6063    
6064            // first update base class's chunks
6065            DLS::File::UpdateChunks(pProgress);
6066    
6067            if (newFile) {
6068                // INFO was added by Resource::UpdateChunks - make sure it
6069                // is placed first in file
6070                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
6071                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
6072                if (first != info) {
6073                    pRIFF->MoveSubChunk(info, first);
6074                }
6075            }
6076    
6077            // update group's chunks
6078            if (pGroups) {
6079                // make sure '3gri' and '3gnl' list chunks exist
6080                // (before updating the Group chunks)
6081                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6082                if (!_3gri) {
6083                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6084                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6085                }
6086                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6087                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6088    
6089                // v3: make sure the file has 128 3gnm chunks
6090                // (before updating the Group chunks)
6091                if (pVersion && pVersion->major == 3) {
6092                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6093                    for (int i = 0 ; i < 128 ; i++) {
6094                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6095                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6096                    }
6097                }
6098    
6099                std::list<Group*>::iterator iter = pGroups->begin();
6100                std::list<Group*>::iterator end  = pGroups->end();
6101                for (; iter != end; ++iter) {
6102                    (*iter)->UpdateChunks(pProgress);
6103                }
6104            }
6105    
6106            // update einf chunk
6107    
6108            // The einf chunk contains statistics about the gig file, such
6109            // as the number of regions and samples used by each
6110            // instrument. It is divided in equally sized parts, where the
6111            // first part contains information about the whole gig file,
6112            // and the rest of the parts map to each instrument in the
6113            // file.
6114            //
6115            // At the end of each part there is a bit map of each sample
6116            // in the file, where a set bit means that the sample is used
6117            // by the file/instrument.
6118            //
6119            // Note that there are several fields with unknown use. These
6120            // are set to zero.
6121    
6122            int sublen = pSamples->size() / 8 + 49;
6123            int einfSize = (Instruments + 1) * sublen;
6124    
6125            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6126            if (einf) {
6127                if (einf->GetSize() != einfSize) {
6128                    einf->Resize(einfSize);
6129                    memset(einf->LoadChunkData(), 0, einfSize);
6130                }
6131            } else if (newFile) {
6132                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
6133            }
6134            if (einf) {
6135                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
6136    
6137                std::map<gig::Sample*,int> sampleMap;
6138                int sampleIdx = 0;
6139                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
6140                    sampleMap[pSample] = sampleIdx++;
6141                }
6142    
6143                int totnbusedsamples = 0;
6144                int totnbusedchannels = 0;
6145                int totnbregions = 0;
6146                int totnbdimregions = 0;
6147                int totnbloops = 0;
6148                int instrumentIdx = 0;
6149    
6150                memset(&pData[48], 0, sublen - 48);
6151    
6152                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
6153                     instrument = GetNextInstrument()) {
6154                    int nbusedsamples = 0;
6155                    int nbusedchannels = 0;
6156                    int nbdimregions = 0;
6157                    int nbloops = 0;
6158    
6159                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
6160    
6161                    for (Region* region = instrument->GetFirstRegion() ; region ;
6162                         region = instrument->GetNextRegion()) {
6163                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
6164                            gig::DimensionRegion *d = region->pDimensionRegions[i];
6165                            if (d->pSample) {
6166                                int sampleIdx = sampleMap[d->pSample];
6167                                int byte = 48 + sampleIdx / 8;
6168                                int bit = 1 << (sampleIdx & 7);
6169                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6170                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6171                                    nbusedsamples++;
6172                                    nbusedchannels += d->pSample->Channels;
6173    
6174                                    if ((pData[byte] & bit) == 0) {
6175                                        pData[byte] |= bit;
6176                                        totnbusedsamples++;
6177                                        totnbusedchannels += d->pSample->Channels;
6178                                    }
6179                                }
6180                            }
6181                            if (d->SampleLoops) nbloops++;
6182                        }
6183                        nbdimregions += region->DimensionRegions;
6184                    }
6185                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6186                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6187                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6188                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6189                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6190                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6191                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6192                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6193                    // next 8 bytes unknown
6194                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6195                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
6196                    // next 4 bytes unknown
6197    
6198                    totnbregions += instrument->Regions;
6199                    totnbdimregions += nbdimregions;
6200                    totnbloops += nbloops;
6201                    instrumentIdx++;
6202                }
6203                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6204                // store32(&pData[0], sublen);
6205                store32(&pData[4], totnbusedchannels);
6206                store32(&pData[8], totnbusedsamples);
6207                store32(&pData[12], Instruments);
6208                store32(&pData[16], totnbregions);
6209                store32(&pData[20], totnbdimregions);
6210                store32(&pData[24], totnbloops);
6211                // next 8 bytes unknown
6212                // next 4 bytes unknown, not always 0
6213                store32(&pData[40], pSamples->size());
6214                // next 4 bytes unknown
6215            }
6216    
6217            // update 3crc chunk
6218    
6219            // The 3crc chunk contains CRC-32 checksums for the
6220            // samples. The actual checksum values will be filled in
6221            // later, by Sample::Write.
6222    
6223            if (_3crc) {
6224                _3crc->Resize(pSamples->size() * 8);
6225            } else if (newFile) {
6226                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6227                _3crc->LoadChunkData();
6228    
6229                // the order of einf and 3crc is not the same in v2 and v3
6230                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6231            }
6232        }
6233        
6234        void File::UpdateFileOffsets() {
6235            DLS::File::UpdateFileOffsets();
6236    
6237            for (Instrument* instrument = GetFirstInstrument(); instrument;
6238                 instrument = GetNextInstrument())
6239            {
6240                instrument->UpdateScriptFileOffsets();
6241            }
6242        }
6243    
6244        /**
6245         * Enable / disable automatic loading. By default this properyt is
6246         * enabled and all informations are loaded automatically. However
6247         * loading all Regions, DimensionRegions and especially samples might
6248         * take a long time for large .gig files, and sometimes one might only
6249         * be interested in retrieving very superficial informations like the
6250         * amount of instruments and their names. In this case one might disable
6251         * automatic loading to avoid very slow response times.
6252         *
6253         * @e CAUTION: by disabling this property many pointers (i.e. sample
6254         * references) and informations will have invalid or even undefined
6255         * data! This feature is currently only intended for retrieving very
6256         * superficial informations in a very fast way. Don't use it to retrieve
6257         * details like synthesis informations or even to modify .gig files!
6258         */
6259        void File::SetAutoLoad(bool b) {
6260            bAutoLoad = b;
6261        }
6262    
6263        /**
6264         * Returns whether automatic loading is enabled.
6265         * @see SetAutoLoad()
6266         */
6267        bool File::GetAutoLoad() {
6268            return bAutoLoad;
6269      }      }
6270    
6271    

Legend:
Removed from v.695  
changed lines
  Added in v.2985

  ViewVC Help
Powered by ViewVC