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

Legend:
Removed from v.666  
changed lines
  Added in v.3203

  ViewVC Help
Powered by ViewVC