/[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 823 by schoenebeck, Fri Dec 23 01:38:50 2005 UTC revision 3140 by schoenebeck, Wed May 3 16:19:53 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 24  Line 24 
24  #include "gig.h"  #include "gig.h"
25    
26  #include "helper.h"  #include "helper.h"
27    #include "Serialization.h"
28    
29    #include <algorithm>
30  #include <math.h>  #include <math.h>
31  #include <iostream>  #include <iostream>
32    #include <assert.h>
33    
34    /// libgig's current file format version (for extending the original Giga file
35    /// format with libgig's own custom data / custom features).
36    #define GIG_FILE_EXT_VERSION    2
37    
38  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
39  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 49  Line 56 
56  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
57  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
58    
59  namespace gig {  #define SRLZ(member) \
60        archive->serializeMember(*this, member, #member);
 // *************** dimension_def_t ***************  
 // *  
   
     dimension_def_t& dimension_def_t::operator=(const dimension_def_t& arg) {  
         dimension  = arg.dimension;  
         bits       = arg.bits;  
         zones      = arg.zones;  
         split_type = arg.split_type;  
         ranges     = arg.ranges;  
         zone_size  = arg.zone_size;  
         if (ranges) {  
             ranges = new range_t[zones];  
             for (int i = 0; i < zones; i++)  
                 ranges[i] = arg.ranges[i];  
         }  
         return *this;  
     }  
   
   
   
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         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 decompression ***************  // *************** Internal functions for sample decompression ***************
65  // *  // *
# Line 131  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 170  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      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
142          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
143    
144  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
145          y    = get24(params);                   \          y    = get24(params);                   \
# Line 193  namespace { Line 155  namespace {
155    
156  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
157          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
158          *pDst = y >> shift;                     \          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 270  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      /** @brief Constructor.      /** @brief Constructor.
# Line 293  namespace { Line 364  namespace {
364       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
365       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
366       *                         is located, 0 otherwise       *                         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, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      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            __resetCRC(crc);
381            // if this is not a new sample, try to get the sample's already existing
382            // 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            // user for the last time (by calling Sample::Write() that is).
385            if (index >= 0) { // not a new file ...
386                try {
387                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
388                    this->crc = crc;
389                } catch (...) {}
390            }
391    
392          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
393          if (pCk3gix) {          if (pCk3gix) {
394              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
395                pGroup = pFile->GetGroup(iSampleGroup);
396          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
397              // use default value(s)              // by default assigned to that mandatory "Default Group"
398              SampleGroup = 0;              pGroup = pFile->GetGroup(0);
399          }          }
400    
401          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 327  namespace { Line 419  namespace {
419              // use default values              // use default values
420              Manufacturer  = 0;              Manufacturer  = 0;
421              Product       = 0;              Product       = 0;
422              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
423              MIDIUnityNote = 64;              MIDIUnityNote = 60;
424              FineTune      = 0;              FineTune      = 0;
425                SMPTEFormat   = smpte_format_no_offset;
426              SMPTEOffset   = 0;              SMPTEOffset   = 0;
427              Loops         = 0;              Loops         = 0;
428              LoopID        = 0;              LoopID        = 0;
429                LoopType      = loop_type_normal;
430              LoopStart     = 0;              LoopStart     = 0;
431              LoopEnd       = 0;              LoopEnd       = 0;
432              LoopFraction  = 0;              LoopFraction  = 0;
# Line 368  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      /**      /**
# Line 378  namespace { Line 539  namespace {
539       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
540       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
541       *       *
542       * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @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       *                        was provided yet
545       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
546       */       */
547      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
548          // first update base class's chunks          // first update base class's chunks
549          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
550    
551          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
552          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
553          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
554                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
555                memset(pCkSmpl->LoadChunkData(), 0, 60);
556            }
557          // update 'smpl' chunk          // update 'smpl' chunk
558          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
559          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
560          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
561          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
562          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
563          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
564          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
565          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
566          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
567          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
568    
569          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
570    
571          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
572          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
573          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
574          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
575          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
576          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
577    
578          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
579          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
580          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          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          // update '3gix' chunk
595          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
596          memcpy(&pData[0], &SampleGroup, 2);          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 438  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 457  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 473  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 516  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 575  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 616  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.      /** @brief Resize sample.
# Line 636  namespace { Line 824  namespace {
824       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
825       * current sample's boundary!       * current sample's boundary!
826       *       *
827       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
828       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
829       * other formats will fail!       * other formats will fail!
830       *       *
831       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
832       *                   greater than zero)       *                  greater than zero)
833       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
834       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
835       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
836       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
837       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
838       */       */
839      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
840          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
841          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
842      }      }
843    
844      /**      /**
# Line 674  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 692  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 708  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 742  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 904  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 945  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 964  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 1045  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 1108  namespace { Line 1289  namespace {
1289       *       *
1290       * Note: there is currently no support for writing compressed samples.       * 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       * @param pBuffer     - source buffer
1297       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1298       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
1299       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1300       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1301       */       */
1302      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      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)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1304          return DLS::Sample::Write(pBuffer, SampleCount);  
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      /**      /**
# Line 1135  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 1161  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 1177  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          pSample = NULL;          pSample = NULL;
1473            pRegion = pParent;
1474    
1475            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1476            else memset(&Crossfade, 0, 4);
1477    
         memcpy(&Crossfade, &SamplerOptions, 4);  
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          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1482              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1483              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1484              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1485              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1299  namespace { Line 1588  namespace {
1588                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1589              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1590              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1591                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1592              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1593              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1594              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1335  namespace { Line 1624  namespace {
1624                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1625                      VCFType = vcf_type_lowpassturbo;                      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          } else { // '3ewa' chunk does not exist yet
1633              // use default values              // use default values
1634              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1344  namespace { Line 1638  namespace {
1638              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1639              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1640              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1641              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1642              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1643              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1644              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1645              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1646              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1361  namespace { Line 1655  namespace {
1655              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1656              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1657              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1658              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1659              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1660              EG2Release                      = 0.0;              EG2Release                      = 60;
1661              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1662              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1663              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1664              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1665              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1666              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1667              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1668              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1669              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1670              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1671              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1672              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1415  namespace { Line 1709  namespace {
1709              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1710              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1711              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1712                memset(DimensionUpperLimits, 127, 8);
1713          }          }
1714    
1715          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1716                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1717                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1718    
1719          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1720          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1721                                        ReleaseVelocityResponseDepth
1722          // this models a strange behaviour or bug in GSt: two of the                                  );
1723          // velocity response curves for release time are not used even  
1724          // if specified, instead another curve is chosen.          pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1725          if ((curveType == curve_type_nonlinear && depth == 0) ||                                                        VCFVelocityDynamicRange,
1726              (curveType == curve_type_special   && depth == 4)) {                                                        VCFVelocityScale,
1727              curveType = curve_type_nonlinear;                                                        VCFCutoffController);
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1728    
1729          curveType = VCFVelocityCurve;          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1730          depth = VCFVelocityDynamicRange;          VelocityTable = 0;
1731        }
1732    
1733          // even stranger GSt: two of the velocity response curves for      /*
1734          // filter cutoff are not used, instead another special curve       * Constructs a DimensionRegion by copying all parameters from
1735          // is chosen. This curve is not used anywhere else.       * another DimensionRegion
1736          if ((curveType == curve_type_nonlinear && depth == 0) ||       */
1737              (curveType == curve_type_special   && depth == 4)) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1738              curveType = curve_type_special;          Instances++;
1739              depth = 5;          //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          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
1755                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);      
1756        /**
1757         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1758         * and assign it to this object.
1759         *
1760         * Note that all sample pointers referenced by @a orig are simply copied as
1761         * memory address. Thus the respective samples are shared, not duplicated!
1762         *
1763         * @param orig - original DimensionRegion object to be copied from
1764         */
1765        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            SRLZ(VelocityUpperLimit);
1821            SRLZ(EG1PreAttack);
1822            SRLZ(EG1Attack);
1823            SRLZ(EG1Decay1);
1824            SRLZ(EG1Decay2);
1825            SRLZ(EG1InfiniteSustain);
1826            SRLZ(EG1Sustain);
1827            SRLZ(EG1Release);
1828            SRLZ(EG1Hold);
1829            SRLZ(EG1Controller);
1830            SRLZ(EG1ControllerInvert);
1831            SRLZ(EG1ControllerAttackInfluence);
1832            SRLZ(EG1ControllerDecayInfluence);
1833            SRLZ(EG1ControllerReleaseInfluence);
1834            SRLZ(LFO1Frequency);
1835            SRLZ(LFO1InternalDepth);
1836            SRLZ(LFO1ControlDepth);
1837            SRLZ(LFO1Controller);
1838            SRLZ(LFO1FlipPhase);
1839            SRLZ(LFO1Sync);
1840            SRLZ(EG2PreAttack);
1841            SRLZ(EG2Attack);
1842            SRLZ(EG2Decay1);
1843            SRLZ(EG2Decay2);
1844            SRLZ(EG2InfiniteSustain);
1845            SRLZ(EG2Sustain);
1846            SRLZ(EG2Release);
1847            SRLZ(EG2Controller);
1848            SRLZ(EG2ControllerInvert);
1849            SRLZ(EG2ControllerAttackInfluence);
1850            SRLZ(EG2ControllerDecayInfluence);
1851            SRLZ(EG2ControllerReleaseInfluence);
1852            SRLZ(LFO2Frequency);
1853            SRLZ(LFO2InternalDepth);
1854            SRLZ(LFO2ControlDepth);
1855            SRLZ(LFO2Controller);
1856            SRLZ(LFO2FlipPhase);
1857            SRLZ(LFO2Sync);
1858            SRLZ(EG3Attack);
1859            SRLZ(EG3Depth);
1860            SRLZ(LFO3Frequency);
1861            SRLZ(LFO3InternalDepth);
1862            SRLZ(LFO3ControlDepth);
1863            SRLZ(LFO3Controller);
1864            SRLZ(LFO3Sync);
1865            SRLZ(VCFEnabled);
1866            SRLZ(VCFType);
1867            SRLZ(VCFCutoffController);
1868            SRLZ(VCFCutoffControllerInvert);
1869            SRLZ(VCFCutoff);
1870            SRLZ(VCFVelocityCurve);
1871            SRLZ(VCFVelocityScale);
1872            SRLZ(VCFVelocityDynamicRange);
1873            SRLZ(VCFResonance);
1874            SRLZ(VCFResonanceDynamic);
1875            SRLZ(VCFResonanceController);
1876            SRLZ(VCFKeyboardTracking);
1877            SRLZ(VCFKeyboardTrackingBreakpoint);
1878            SRLZ(VelocityResponseCurve);
1879            SRLZ(VelocityResponseDepth);
1880            SRLZ(VelocityResponseCurveScaling);
1881            SRLZ(ReleaseVelocityResponseCurve);
1882            SRLZ(ReleaseVelocityResponseDepth);
1883            SRLZ(ReleaseTriggerDecay);
1884            SRLZ(Crossfade);
1885            SRLZ(PitchTrack);
1886            SRLZ(DimensionBypass);
1887            SRLZ(Pan);
1888            SRLZ(SelfMask);
1889            SRLZ(AttenuationController);
1890            SRLZ(InvertAttenuationController);
1891            SRLZ(AttenuationControllerThreshold);
1892            SRLZ(ChannelOffset);
1893            SRLZ(SustainDefeat);
1894            SRLZ(MSDecode);
1895            //SRLZ(SampleStartOffset);
1896            SRLZ(SampleAttenuation);
1897    
1898            // derived attributes from DLS::Sampler
1899            SRLZ(FineTune);
1900            SRLZ(Gain);
1901        }
1902    
1903        /**
1904         * Updates the respective member variable and updates @c SampleAttenuation
1905         * which depends on this value.
1906         */
1907        void DimensionRegion::SetGain(int32_t gain) {
1908            DLS::Sampler::SetGain(gain);
1909          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1910      }      }
1911    
# Line 1457  namespace { Line 1915  namespace {
1915       *       *
1916       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1917       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1918         *
1919         * @param pProgress - callback function for progress notification
1920       */       */
1921      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1922          // first update base class's chunk          // first update base class's chunk
1923          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1924    
1925            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1926            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1927            pData[12] = Crossfade.in_start;
1928            pData[13] = Crossfade.in_end;
1929            pData[14] = Crossfade.out_start;
1930            pData[15] = Crossfade.out_end;
1931    
1932          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1933          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1934          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1935          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1936                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1937                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1938            }
1939            pData = (uint8_t*) _3ewa->LoadChunkData();
1940    
1941          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1942    
1943          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1944          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1945    
1946          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1947          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1948    
1949          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1950          memcpy(&pData[4], &eg3attack, 4);          store32(&pData[8], eg3attack);
1951    
1952          // next 2 bytes unknown          // next 2 bytes unknown
1953    
1954          memcpy(&pData[10], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1955    
1956          // next 2 bytes unknown          // next 2 bytes unknown
1957    
1958          memcpy(&pData[14], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1959    
1960          // next 2 bytes unknown          // next 2 bytes unknown
1961    
1962          memcpy(&pData[18], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1963    
1964          // next 2 bytes unknown          // next 2 bytes unknown
1965    
1966          memcpy(&pData[22], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1967    
1968          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1969          memcpy(&pData[24], &eg1attack, 4);          store32(&pData[28], eg1attack);
1970    
1971          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1972          memcpy(&pData[28], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1973    
1974          // next 2 bytes unknown          // next 2 bytes unknown
1975    
1976          memcpy(&pData[34], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1977    
1978          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1979          memcpy(&pData[36], &eg1release, 4);          store32(&pData[40], eg1release);
1980    
1981          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1982          memcpy(&pData[40], &eg1ctl, 1);          pData[44] = eg1ctl;
1983    
1984          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1985              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1986              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1987              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1988              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1989          memcpy(&pData[41], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1990    
1991          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1992          memcpy(&pData[42], &eg2ctl, 1);          pData[46] = eg2ctl;
1993    
1994          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1995              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1996              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1997              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1998              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1999          memcpy(&pData[43], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
2000    
2001          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
2002          memcpy(&pData[44], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
2003    
2004          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
2005          memcpy(&pData[48], &eg2attack, 4);          store32(&pData[52], eg2attack);
2006    
2007          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
2008          memcpy(&pData[52], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
2009    
2010          // next 2 bytes unknown          // next 2 bytes unknown
2011    
2012          memcpy(&pData[58], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
2013    
2014          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
2015          memcpy(&pData[60], &eg2release, 4);          store32(&pData[64], eg2release);
2016    
2017          // next 2 bytes unknown          // next 2 bytes unknown
2018    
2019          memcpy(&pData[66], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
2020    
2021          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
2022          memcpy(&pData[68], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
2023    
2024          // next 2 bytes unknown          // next 2 bytes unknown
2025    
2026          memcpy(&pData[72], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
2027    
2028          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
2029          memcpy(&pData[74], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
2030    
2031          // next 2 bytes unknown          // next 2 bytes unknown
2032    
2033          memcpy(&pData[80], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
2034    
2035          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
2036          memcpy(&pData[82], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
2037    
2038          // next 2 bytes unknown          // next 2 bytes unknown
2039    
2040          memcpy(&pData[88], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
2041    
2042          {          {
2043              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1584  namespace { Line 2055  namespace {
2055                  default:                  default:
2056                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
2057              }              }
2058              memcpy(&pData[90], &velocityresponse, 1);              pData[96] = velocityresponse;
2059          }          }
2060    
2061          {          {
# Line 1603  namespace { Line 2074  namespace {
2074                  default:                  default:
2075                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
2076              }              }
2077              memcpy(&pData[91], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
2078          }          }
2079    
2080          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
2081    
2082          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
2083    
2084          // next 4 bytes unknown          // next 4 bytes unknown
2085    
2086          memcpy(&pData[98], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
2087    
2088          // next 2 bytes unknown          // next 2 bytes unknown
2089    
# Line 1631  namespace { Line 2102  namespace {
2102                  default:                  default:
2103                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
2104              }              }
2105              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
2106          }          }
2107    
2108          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
2109          memcpy(&pData[103], &pan, 1);          pData[109] = pan;
2110    
2111          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
2112          memcpy(&pData[104], &selfmask, 1);          pData[110] = selfmask;
2113    
2114          // next byte unknown          // next byte unknown
2115    
# Line 1647  namespace { Line 2118  namespace {
2118              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
2119              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
2120              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
2121              memcpy(&pData[106], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
2122          }          }
2123    
2124          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
2125          memcpy(&pData[107], &attenctl, 1);          pData[113] = attenctl;
2126    
2127          {          {
2128              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
2129              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
2130              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
2131              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
2132              memcpy(&pData[108], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
2133          }          }
2134    
2135          {          {
# Line 1667  namespace { Line 2138  namespace {
2138              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
2139              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
2140                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
2141              memcpy(&pData[109], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
2142          }          }
2143    
2144          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2145                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2146          memcpy(&pData[110], &eg3depth, 1);          store16(&pData[116], eg3depth);
2147    
2148          // next 2 bytes unknown          // next 2 bytes unknown
2149    
2150          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
2151          memcpy(&pData[113], &channeloffset, 1);          pData[120] = channeloffset;
2152    
2153          {          {
2154              uint8_t regoptions = 0;              uint8_t regoptions = 0;
2155              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
2156              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
2157              memcpy(&pData[114], &regoptions, 1);              pData[121] = regoptions;
2158          }          }
2159    
2160          // next 2 bytes unknown          // next 2 bytes unknown
2161    
2162          memcpy(&pData[117], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
2163    
2164          // next 3 bytes unknown          // next 3 bytes unknown
2165    
2166          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
2167    
2168          // next 2 bytes unknown          // next 2 bytes unknown
2169    
2170          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2171          memcpy(&pData[124], &eg1hold, 1);          pData[131] = eg1hold;
2172    
2173          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2174                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2175          memcpy(&pData[125], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2176    
2177          memcpy(&pData[126], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2178    
2179          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2180                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2181          memcpy(&pData[127], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2182    
2183          // next byte unknown          // next byte unknown
2184    
2185          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2186                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2187          memcpy(&pData[129], &vcfresonance, 1);          pData[136] = vcfresonance;
2188    
2189          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2190                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2191          memcpy(&pData[130], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2192    
2193          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2194                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2195          memcpy(&pData[131], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2196    
2197          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2198          memcpy(&pData[132], &vcftype, 1);          pData[139] = vcftype;
2199    
2200            if (chunksize >= 148) {
2201                memcpy(&pData[140], DimensionUpperLimits, 8);
2202            }
2203        }
2204    
2205        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2206            curve_type_t curveType = releaseVelocityResponseCurve;
2207            uint8_t depth = releaseVelocityResponseDepth;
2208            // this models a strange behaviour or bug in GSt: two of the
2209            // velocity response curves for release time are not used even
2210            // if specified, instead another curve is chosen.
2211            if ((curveType == curve_type_nonlinear && depth == 0) ||
2212                (curveType == curve_type_special   && depth == 4)) {
2213                curveType = curve_type_nonlinear;
2214                depth = 3;
2215            }
2216            return GetVelocityTable(curveType, depth, 0);
2217        }
2218    
2219        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2220                                                        uint8_t vcfVelocityDynamicRange,
2221                                                        uint8_t vcfVelocityScale,
2222                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2223        {
2224            curve_type_t curveType = vcfVelocityCurve;
2225            uint8_t depth = vcfVelocityDynamicRange;
2226            // even stranger GSt: two of the velocity response curves for
2227            // filter cutoff are not used, instead another special curve
2228            // is chosen. This curve is not used anywhere else.
2229            if ((curveType == curve_type_nonlinear && depth == 0) ||
2230                (curveType == curve_type_special   && depth == 4)) {
2231                curveType = curve_type_special;
2232                depth = 5;
2233            }
2234            return GetVelocityTable(curveType, depth,
2235                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2236                                        ? vcfVelocityScale : 0);
2237      }      }
2238    
2239      // 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 1742  namespace { Line 2251  namespace {
2251          return table;          return table;
2252      }      }
2253    
2254        Region* DimensionRegion::GetParent() const {
2255            return pRegion;
2256        }
2257    
2258    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2259    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2260    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2261    //#pragma GCC diagnostic push
2262    //#pragma GCC diagnostic error "-Wswitch"
2263    
2264      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2265          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2266          switch (EncodedController) {          switch (EncodedController) {
# Line 1853  namespace { Line 2372  namespace {
2372                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2373                  break;                  break;
2374    
2375                // format extension (these controllers are so far only supported by
2376                // LinuxSampler & gigedit) they will *NOT* work with
2377                // Gigasampler/GigaStudio !
2378                case _lev_ctrl_CC3_EXT:
2379                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2380                    decodedcontroller.controller_number = 3;
2381                    break;
2382                case _lev_ctrl_CC6_EXT:
2383                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2384                    decodedcontroller.controller_number = 6;
2385                    break;
2386                case _lev_ctrl_CC7_EXT:
2387                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2388                    decodedcontroller.controller_number = 7;
2389                    break;
2390                case _lev_ctrl_CC8_EXT:
2391                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2392                    decodedcontroller.controller_number = 8;
2393                    break;
2394                case _lev_ctrl_CC9_EXT:
2395                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2396                    decodedcontroller.controller_number = 9;
2397                    break;
2398                case _lev_ctrl_CC10_EXT:
2399                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2400                    decodedcontroller.controller_number = 10;
2401                    break;
2402                case _lev_ctrl_CC11_EXT:
2403                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2404                    decodedcontroller.controller_number = 11;
2405                    break;
2406                case _lev_ctrl_CC14_EXT:
2407                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2408                    decodedcontroller.controller_number = 14;
2409                    break;
2410                case _lev_ctrl_CC15_EXT:
2411                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2412                    decodedcontroller.controller_number = 15;
2413                    break;
2414                case _lev_ctrl_CC20_EXT:
2415                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2416                    decodedcontroller.controller_number = 20;
2417                    break;
2418                case _lev_ctrl_CC21_EXT:
2419                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2420                    decodedcontroller.controller_number = 21;
2421                    break;
2422                case _lev_ctrl_CC22_EXT:
2423                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2424                    decodedcontroller.controller_number = 22;
2425                    break;
2426                case _lev_ctrl_CC23_EXT:
2427                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2428                    decodedcontroller.controller_number = 23;
2429                    break;
2430                case _lev_ctrl_CC24_EXT:
2431                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2432                    decodedcontroller.controller_number = 24;
2433                    break;
2434                case _lev_ctrl_CC25_EXT:
2435                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2436                    decodedcontroller.controller_number = 25;
2437                    break;
2438                case _lev_ctrl_CC26_EXT:
2439                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2440                    decodedcontroller.controller_number = 26;
2441                    break;
2442                case _lev_ctrl_CC27_EXT:
2443                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2444                    decodedcontroller.controller_number = 27;
2445                    break;
2446                case _lev_ctrl_CC28_EXT:
2447                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2448                    decodedcontroller.controller_number = 28;
2449                    break;
2450                case _lev_ctrl_CC29_EXT:
2451                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2452                    decodedcontroller.controller_number = 29;
2453                    break;
2454                case _lev_ctrl_CC30_EXT:
2455                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2456                    decodedcontroller.controller_number = 30;
2457                    break;
2458                case _lev_ctrl_CC31_EXT:
2459                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2460                    decodedcontroller.controller_number = 31;
2461                    break;
2462                case _lev_ctrl_CC68_EXT:
2463                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2464                    decodedcontroller.controller_number = 68;
2465                    break;
2466                case _lev_ctrl_CC69_EXT:
2467                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2468                    decodedcontroller.controller_number = 69;
2469                    break;
2470                case _lev_ctrl_CC70_EXT:
2471                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2472                    decodedcontroller.controller_number = 70;
2473                    break;
2474                case _lev_ctrl_CC71_EXT:
2475                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2476                    decodedcontroller.controller_number = 71;
2477                    break;
2478                case _lev_ctrl_CC72_EXT:
2479                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2480                    decodedcontroller.controller_number = 72;
2481                    break;
2482                case _lev_ctrl_CC73_EXT:
2483                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2484                    decodedcontroller.controller_number = 73;
2485                    break;
2486                case _lev_ctrl_CC74_EXT:
2487                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2488                    decodedcontroller.controller_number = 74;
2489                    break;
2490                case _lev_ctrl_CC75_EXT:
2491                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2492                    decodedcontroller.controller_number = 75;
2493                    break;
2494                case _lev_ctrl_CC76_EXT:
2495                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2496                    decodedcontroller.controller_number = 76;
2497                    break;
2498                case _lev_ctrl_CC77_EXT:
2499                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2500                    decodedcontroller.controller_number = 77;
2501                    break;
2502                case _lev_ctrl_CC78_EXT:
2503                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2504                    decodedcontroller.controller_number = 78;
2505                    break;
2506                case _lev_ctrl_CC79_EXT:
2507                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2508                    decodedcontroller.controller_number = 79;
2509                    break;
2510                case _lev_ctrl_CC84_EXT:
2511                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2512                    decodedcontroller.controller_number = 84;
2513                    break;
2514                case _lev_ctrl_CC85_EXT:
2515                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2516                    decodedcontroller.controller_number = 85;
2517                    break;
2518                case _lev_ctrl_CC86_EXT:
2519                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2520                    decodedcontroller.controller_number = 86;
2521                    break;
2522                case _lev_ctrl_CC87_EXT:
2523                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2524                    decodedcontroller.controller_number = 87;
2525                    break;
2526                case _lev_ctrl_CC89_EXT:
2527                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2528                    decodedcontroller.controller_number = 89;
2529                    break;
2530                case _lev_ctrl_CC90_EXT:
2531                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2532                    decodedcontroller.controller_number = 90;
2533                    break;
2534                case _lev_ctrl_CC96_EXT:
2535                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2536                    decodedcontroller.controller_number = 96;
2537                    break;
2538                case _lev_ctrl_CC97_EXT:
2539                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2540                    decodedcontroller.controller_number = 97;
2541                    break;
2542                case _lev_ctrl_CC102_EXT:
2543                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2544                    decodedcontroller.controller_number = 102;
2545                    break;
2546                case _lev_ctrl_CC103_EXT:
2547                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2548                    decodedcontroller.controller_number = 103;
2549                    break;
2550                case _lev_ctrl_CC104_EXT:
2551                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2552                    decodedcontroller.controller_number = 104;
2553                    break;
2554                case _lev_ctrl_CC105_EXT:
2555                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2556                    decodedcontroller.controller_number = 105;
2557                    break;
2558                case _lev_ctrl_CC106_EXT:
2559                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2560                    decodedcontroller.controller_number = 106;
2561                    break;
2562                case _lev_ctrl_CC107_EXT:
2563                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2564                    decodedcontroller.controller_number = 107;
2565                    break;
2566                case _lev_ctrl_CC108_EXT:
2567                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2568                    decodedcontroller.controller_number = 108;
2569                    break;
2570                case _lev_ctrl_CC109_EXT:
2571                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2572                    decodedcontroller.controller_number = 109;
2573                    break;
2574                case _lev_ctrl_CC110_EXT:
2575                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2576                    decodedcontroller.controller_number = 110;
2577                    break;
2578                case _lev_ctrl_CC111_EXT:
2579                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2580                    decodedcontroller.controller_number = 111;
2581                    break;
2582                case _lev_ctrl_CC112_EXT:
2583                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2584                    decodedcontroller.controller_number = 112;
2585                    break;
2586                case _lev_ctrl_CC113_EXT:
2587                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2588                    decodedcontroller.controller_number = 113;
2589                    break;
2590                case _lev_ctrl_CC114_EXT:
2591                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2592                    decodedcontroller.controller_number = 114;
2593                    break;
2594                case _lev_ctrl_CC115_EXT:
2595                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2596                    decodedcontroller.controller_number = 115;
2597                    break;
2598                case _lev_ctrl_CC116_EXT:
2599                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2600                    decodedcontroller.controller_number = 116;
2601                    break;
2602                case _lev_ctrl_CC117_EXT:
2603                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2604                    decodedcontroller.controller_number = 117;
2605                    break;
2606                case _lev_ctrl_CC118_EXT:
2607                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2608                    decodedcontroller.controller_number = 118;
2609                    break;
2610                case _lev_ctrl_CC119_EXT:
2611                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2612                    decodedcontroller.controller_number = 119;
2613                    break;
2614    
2615              // unknown controller type              // unknown controller type
2616              default:              default:
2617                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2618          }          }
2619          return decodedcontroller;          return decodedcontroller;
2620      }      }
2621        
2622    // see above (diagnostic push not supported prior GCC 4.6)
2623    //#pragma GCC diagnostic pop
2624    
2625      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2626          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1946  namespace { Line 2708  namespace {
2708                      case 95:                      case 95:
2709                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2710                          break;                          break;
2711    
2712                        // format extension (these controllers are so far only
2713                        // supported by LinuxSampler & gigedit) they will *NOT*
2714                        // work with Gigasampler/GigaStudio !
2715                        case 3:
2716                            encodedcontroller = _lev_ctrl_CC3_EXT;
2717                            break;
2718                        case 6:
2719                            encodedcontroller = _lev_ctrl_CC6_EXT;
2720                            break;
2721                        case 7:
2722                            encodedcontroller = _lev_ctrl_CC7_EXT;
2723                            break;
2724                        case 8:
2725                            encodedcontroller = _lev_ctrl_CC8_EXT;
2726                            break;
2727                        case 9:
2728                            encodedcontroller = _lev_ctrl_CC9_EXT;
2729                            break;
2730                        case 10:
2731                            encodedcontroller = _lev_ctrl_CC10_EXT;
2732                            break;
2733                        case 11:
2734                            encodedcontroller = _lev_ctrl_CC11_EXT;
2735                            break;
2736                        case 14:
2737                            encodedcontroller = _lev_ctrl_CC14_EXT;
2738                            break;
2739                        case 15:
2740                            encodedcontroller = _lev_ctrl_CC15_EXT;
2741                            break;
2742                        case 20:
2743                            encodedcontroller = _lev_ctrl_CC20_EXT;
2744                            break;
2745                        case 21:
2746                            encodedcontroller = _lev_ctrl_CC21_EXT;
2747                            break;
2748                        case 22:
2749                            encodedcontroller = _lev_ctrl_CC22_EXT;
2750                            break;
2751                        case 23:
2752                            encodedcontroller = _lev_ctrl_CC23_EXT;
2753                            break;
2754                        case 24:
2755                            encodedcontroller = _lev_ctrl_CC24_EXT;
2756                            break;
2757                        case 25:
2758                            encodedcontroller = _lev_ctrl_CC25_EXT;
2759                            break;
2760                        case 26:
2761                            encodedcontroller = _lev_ctrl_CC26_EXT;
2762                            break;
2763                        case 27:
2764                            encodedcontroller = _lev_ctrl_CC27_EXT;
2765                            break;
2766                        case 28:
2767                            encodedcontroller = _lev_ctrl_CC28_EXT;
2768                            break;
2769                        case 29:
2770                            encodedcontroller = _lev_ctrl_CC29_EXT;
2771                            break;
2772                        case 30:
2773                            encodedcontroller = _lev_ctrl_CC30_EXT;
2774                            break;
2775                        case 31:
2776                            encodedcontroller = _lev_ctrl_CC31_EXT;
2777                            break;
2778                        case 68:
2779                            encodedcontroller = _lev_ctrl_CC68_EXT;
2780                            break;
2781                        case 69:
2782                            encodedcontroller = _lev_ctrl_CC69_EXT;
2783                            break;
2784                        case 70:
2785                            encodedcontroller = _lev_ctrl_CC70_EXT;
2786                            break;
2787                        case 71:
2788                            encodedcontroller = _lev_ctrl_CC71_EXT;
2789                            break;
2790                        case 72:
2791                            encodedcontroller = _lev_ctrl_CC72_EXT;
2792                            break;
2793                        case 73:
2794                            encodedcontroller = _lev_ctrl_CC73_EXT;
2795                            break;
2796                        case 74:
2797                            encodedcontroller = _lev_ctrl_CC74_EXT;
2798                            break;
2799                        case 75:
2800                            encodedcontroller = _lev_ctrl_CC75_EXT;
2801                            break;
2802                        case 76:
2803                            encodedcontroller = _lev_ctrl_CC76_EXT;
2804                            break;
2805                        case 77:
2806                            encodedcontroller = _lev_ctrl_CC77_EXT;
2807                            break;
2808                        case 78:
2809                            encodedcontroller = _lev_ctrl_CC78_EXT;
2810                            break;
2811                        case 79:
2812                            encodedcontroller = _lev_ctrl_CC79_EXT;
2813                            break;
2814                        case 84:
2815                            encodedcontroller = _lev_ctrl_CC84_EXT;
2816                            break;
2817                        case 85:
2818                            encodedcontroller = _lev_ctrl_CC85_EXT;
2819                            break;
2820                        case 86:
2821                            encodedcontroller = _lev_ctrl_CC86_EXT;
2822                            break;
2823                        case 87:
2824                            encodedcontroller = _lev_ctrl_CC87_EXT;
2825                            break;
2826                        case 89:
2827                            encodedcontroller = _lev_ctrl_CC89_EXT;
2828                            break;
2829                        case 90:
2830                            encodedcontroller = _lev_ctrl_CC90_EXT;
2831                            break;
2832                        case 96:
2833                            encodedcontroller = _lev_ctrl_CC96_EXT;
2834                            break;
2835                        case 97:
2836                            encodedcontroller = _lev_ctrl_CC97_EXT;
2837                            break;
2838                        case 102:
2839                            encodedcontroller = _lev_ctrl_CC102_EXT;
2840                            break;
2841                        case 103:
2842                            encodedcontroller = _lev_ctrl_CC103_EXT;
2843                            break;
2844                        case 104:
2845                            encodedcontroller = _lev_ctrl_CC104_EXT;
2846                            break;
2847                        case 105:
2848                            encodedcontroller = _lev_ctrl_CC105_EXT;
2849                            break;
2850                        case 106:
2851                            encodedcontroller = _lev_ctrl_CC106_EXT;
2852                            break;
2853                        case 107:
2854                            encodedcontroller = _lev_ctrl_CC107_EXT;
2855                            break;
2856                        case 108:
2857                            encodedcontroller = _lev_ctrl_CC108_EXT;
2858                            break;
2859                        case 109:
2860                            encodedcontroller = _lev_ctrl_CC109_EXT;
2861                            break;
2862                        case 110:
2863                            encodedcontroller = _lev_ctrl_CC110_EXT;
2864                            break;
2865                        case 111:
2866                            encodedcontroller = _lev_ctrl_CC111_EXT;
2867                            break;
2868                        case 112:
2869                            encodedcontroller = _lev_ctrl_CC112_EXT;
2870                            break;
2871                        case 113:
2872                            encodedcontroller = _lev_ctrl_CC113_EXT;
2873                            break;
2874                        case 114:
2875                            encodedcontroller = _lev_ctrl_CC114_EXT;
2876                            break;
2877                        case 115:
2878                            encodedcontroller = _lev_ctrl_CC115_EXT;
2879                            break;
2880                        case 116:
2881                            encodedcontroller = _lev_ctrl_CC116_EXT;
2882                            break;
2883                        case 117:
2884                            encodedcontroller = _lev_ctrl_CC117_EXT;
2885                            break;
2886                        case 118:
2887                            encodedcontroller = _lev_ctrl_CC118_EXT;
2888                            break;
2889                        case 119:
2890                            encodedcontroller = _lev_ctrl_CC119_EXT;
2891                            break;
2892    
2893                      default:                      default:
2894                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2895                  }                  }
2896                    break;
2897              default:              default:
2898                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2899          }          }
# Line 1968  namespace { Line 2913  namespace {
2913              delete pVelocityTables;              delete pVelocityTables;
2914              pVelocityTables = NULL;              pVelocityTables = NULL;
2915          }          }
2916            if (VelocityTable) delete[] VelocityTable;
2917      }      }
2918    
2919      /**      /**
# Line 1993  namespace { Line 2939  namespace {
2939          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2940      }      }
2941    
2942        /**
2943         * Updates the respective member variable and the lookup table / cache
2944         * that depends on this value.
2945         */
2946        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2947            pVelocityAttenuationTable =
2948                GetVelocityTable(
2949                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2950                );
2951            VelocityResponseCurve = curve;
2952        }
2953    
2954        /**
2955         * Updates the respective member variable and the lookup table / cache
2956         * that depends on this value.
2957         */
2958        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2959            pVelocityAttenuationTable =
2960                GetVelocityTable(
2961                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2962                );
2963            VelocityResponseDepth = depth;
2964        }
2965    
2966        /**
2967         * Updates the respective member variable and the lookup table / cache
2968         * that depends on this value.
2969         */
2970        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2971            pVelocityAttenuationTable =
2972                GetVelocityTable(
2973                    VelocityResponseCurve, VelocityResponseDepth, scaling
2974                );
2975            VelocityResponseCurveScaling = scaling;
2976        }
2977    
2978        /**
2979         * Updates the respective member variable and the lookup table / cache
2980         * that depends on this value.
2981         */
2982        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2983            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2984            ReleaseVelocityResponseCurve = curve;
2985        }
2986    
2987        /**
2988         * Updates the respective member variable and the lookup table / cache
2989         * that depends on this value.
2990         */
2991        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2992            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2993            ReleaseVelocityResponseDepth = depth;
2994        }
2995    
2996        /**
2997         * Updates the respective member variable and the lookup table / cache
2998         * that depends on this value.
2999         */
3000        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
3001            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
3002            VCFCutoffController = controller;
3003        }
3004    
3005        /**
3006         * Updates the respective member variable and the lookup table / cache
3007         * that depends on this value.
3008         */
3009        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
3010            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
3011            VCFVelocityCurve = curve;
3012        }
3013    
3014        /**
3015         * Updates the respective member variable and the lookup table / cache
3016         * that depends on this value.
3017         */
3018        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
3019            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
3020            VCFVelocityDynamicRange = range;
3021        }
3022    
3023        /**
3024         * Updates the respective member variable and the lookup table / cache
3025         * that depends on this value.
3026         */
3027        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
3028            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
3029            VCFVelocityScale = scaling;
3030        }
3031    
3032      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) {
3033    
3034          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2076  namespace { Line 3112  namespace {
3112    
3113          // Actual Loading          // Actual Loading
3114    
3115            if (!file->GetAutoLoad()) return;
3116    
3117          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
3118    
3119          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2084  namespace { Line 3122  namespace {
3122              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
3123                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
3124                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
3125                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
3126                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
3127                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
3128                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
3129                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
3130                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
3131                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
3132                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
3133                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
3134                  }                  }
3135                  else { // active dimension                  else { // active dimension
3136                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
3137                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
3138                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
3139                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
3140                                                             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.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
3141                      Dimensions++;                      Dimensions++;
3142    
3143                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2116  namespace { Line 3145  namespace {
3145                  }                  }
3146                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
3147              }              }
3148                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
3149    
3150              // 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,
3151              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
3152                  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];  
                         UpdateVelocityTable(pDimDef);  
                     }  
                 }  
             }  
3153    
3154              // 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();  
3155              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
3156                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
3157              else              else
3158                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3159    
3160              // load sample references              // load sample references (if auto loading is enabled)
3161              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3162                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3163                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3164                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3165                    }
3166                    GetSample(); // load global region sample reference
3167                }
3168            } else {
3169                DimensionRegions = 0;
3170                for (int i = 0 ; i < 8 ; i++) {
3171                    pDimensionDefinitions[i].dimension  = dimension_none;
3172                    pDimensionDefinitions[i].bits       = 0;
3173                    pDimensionDefinitions[i].zones      = 0;
3174              }              }
3175          }          }
3176    
# Line 2153  namespace { Line 3179  namespace {
3179              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3180              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3181              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3182              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3183              DimensionRegions = 1;              DimensionRegions = 1;
3184          }          }
3185      }      }
# Line 2165  namespace { Line 3191  namespace {
3191       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3192       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3193       *       *
3194         * @param pProgress - callback function for progress notification
3195       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3196       */       */
3197      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3198            // in the gig format we don't care about the Region's sample reference
3199            // but we still have to provide some existing one to not corrupt the
3200            // file, so to avoid the latter we simply always assign the sample of
3201            // the first dimension region of this region
3202            pSample = pDimensionRegions[0]->pSample;
3203    
3204          // first update base class's chunks          // first update base class's chunks
3205          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3206    
3207          // update dimension region's chunks          // update dimension region's chunks
3208          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3209              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3210          }          }
3211    
3212          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3213          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3214          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3215            const int iMaxDimensionRegions = version3 ? 256 : 32;
3216    
3217          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3218          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3219          if (!_3lnk) {          if (!_3lnk) {
3220              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3221              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3222                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3223    
3224                // move 3prg to last position
3225                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3226          }          }
3227    
3228          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3229          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3230            store32(&pData[0], DimensionRegions);
3231            int shift = 0;
3232          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3233              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3234              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3235              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3236              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3237              // next 3 bytes unknown              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3238                // next 3 bytes unknown, always zero?
3239    
3240                shift += pDimensionDefinitions[i].bits;
3241          }          }
3242    
3243          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3244          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3245          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3246              int iWaveIndex = -1;              int iWaveIndex = -1;
3247              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2211  namespace { Line 3254  namespace {
3254                          break;                          break;
3255                      }                      }
3256                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3257              }              }
3258              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3259          }          }
3260      }      }
3261    
# Line 2224  namespace { Line 3266  namespace {
3266              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3267              while (_3ewl) {              while (_3ewl) {
3268                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3269                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3270                      dimensionRegionNr++;                      dimensionRegionNr++;
3271                  }                  }
3272                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2233  namespace { Line 3275  namespace {
3275          }          }
3276      }      }
3277    
3278      void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3279          // get dimension's index          // update KeyRange struct and make sure regions are in correct order
3280          int iDimensionNr = -1;          DLS::Region::SetKeyRange(Low, High);
3281          for (int i = 0; i < Dimensions; i++) {          // update Region key table for fast lookup
3282              if (&pDimensionDefinitions[i] == pDimDef) {          ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3283                  iDimensionNr = i;      }
3284    
3285        void Region::UpdateVelocityTable() {
3286            // get velocity dimension's index
3287            int veldim = -1;
3288            for (int i = 0 ; i < Dimensions ; i++) {
3289                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3290                    veldim = i;
3291                  break;                  break;
3292              }              }
3293          }          }
3294          if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");          if (veldim == -1) return;
3295    
3296            int step = 1;
3297            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3298            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3299    
3300            // loop through all dimension regions for all dimensions except the velocity dimension
3301            int dim[8] = { 0 };
3302            for (int i = 0 ; i < DimensionRegions ; i++) {
3303                const int end = i + step * pDimensionDefinitions[veldim].zones;
3304    
3305                // create a velocity table for all cases where the velocity zone is zero
3306                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3307                    pDimensionRegions[i]->VelocityUpperLimit) {
3308                    // create the velocity table
3309                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
3310                    if (!table) {
3311                        table = new uint8_t[128];
3312                        pDimensionRegions[i]->VelocityTable = table;
3313                    }
3314                    int tableidx = 0;
3315                    int velocityZone = 0;
3316                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3317                        for (int k = i ; k < end ; k += step) {
3318                            DimensionRegion *d = pDimensionRegions[k];
3319                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3320                            velocityZone++;
3321                        }
3322                    } else { // gig2
3323                        for (int k = i ; k < end ; k += step) {
3324                            DimensionRegion *d = pDimensionRegions[k];
3325                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3326                            velocityZone++;
3327                        }
3328                    }
3329                } else {
3330                    if (pDimensionRegions[i]->VelocityTable) {
3331                        delete[] pDimensionRegions[i]->VelocityTable;
3332                        pDimensionRegions[i]->VelocityTable = 0;
3333                    }
3334                }
3335    
3336          uint8_t bits[8] = { 0 };              // jump to the next case where the velocity zone is zero
3337          int previousUpperLimit = -1;              int j;
3338          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {              int shift = 0;
3339              bits[iDimensionNr] = velocityZone;              for (j = 0 ; j < Dimensions ; j++) {
3340              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);                  if (j == veldim) i += skipveldim; // skip velocity dimension
3341                    else {
3342              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                      dim[j]++;
3343              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                      if (dim[j] < pDimensionDefinitions[j].zones) break;
3344              previousUpperLimit = pDimDef->ranges[velocityZone].high;                      else {
3345              // fill velocity table                          // skip unused dimension regions
3346              for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {                          dim[j] = 0;
3347                  VelocityTable[i] = velocityZone;                          i += ((1 << pDimensionDefinitions[j].bits) -
3348                                  pDimensionDefinitions[j].zones) << shift;
3349                        }
3350                    }
3351                    shift += pDimensionDefinitions[j].bits;
3352              }              }
3353                if (j == Dimensions) break;
3354          }          }
3355      }      }
3356    
# Line 2276  namespace { Line 3370  namespace {
3370       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3371       */       */
3372      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3373            // some initial sanity checks of the given dimension definition
3374            if (pDimDef->zones < 2)
3375                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3376            if (pDimDef->bits < 1)
3377                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3378            if (pDimDef->dimension == dimension_samplechannel) {
3379                if (pDimDef->zones != 2)
3380                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3381                if (pDimDef->bits != 1)
3382                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3383            }
3384    
3385          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3386          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3387          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2295  namespace { Line 3401  namespace {
3401              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3402                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3403    
3404            // pos is where the new dimension should be placed, normally
3405            // last in list, except for the samplechannel dimension which
3406            // has to be first in list
3407            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3408            int bitpos = 0;
3409            for (int i = 0 ; i < pos ; i++)
3410                bitpos += pDimensionDefinitions[i].bits;
3411    
3412            // make room for the new dimension
3413            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3414            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3415                for (int j = Dimensions ; j > pos ; j--) {
3416                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3417                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3418                }
3419            }
3420    
3421          // assign definition of new dimension          // assign definition of new dimension
3422          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3423    
3424            // auto correct certain dimension definition fields (where possible)
3425            pDimensionDefinitions[pos].split_type  =
3426                __resolveSplitType(pDimensionDefinitions[pos].dimension);
3427            pDimensionDefinitions[pos].zone_size =
3428                __resolveZoneSize(pDimensionDefinitions[pos]);
3429    
3430            // create new dimension region(s) for this new dimension, and make
3431            // sure that the dimension regions are placed correctly in both the
3432            // RIFF list and the pDimensionRegions array
3433            RIFF::Chunk* moveTo = NULL;
3434            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3435            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3436                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3437                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3438                }
3439                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3440                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3441                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3442                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3443                        // create a new dimension region and copy all parameter values from
3444                        // an existing dimension region
3445                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3446                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3447    
3448                        DimensionRegions++;
3449                    }
3450                }
3451                moveTo = pDimensionRegions[i]->pParentList;
3452            }
3453    
3454          // create new dimension region(s) for this new dimension          // initialize the upper limits for this dimension
3455          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          int mask = (1 << bitpos) - 1;
3456              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values          for (int z = 0 ; z < pDimDef->zones ; z++) {
3457              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);              uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3458              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3459              DimensionRegions++;                  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3460                                      (z << bitpos) |
3461                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3462                }
3463          }          }
3464    
3465          Dimensions++;          Dimensions++;
# Line 2311  namespace { Line 3467  namespace {
3467          // if this is a layer dimension, update 'Layers' attribute          // if this is a layer dimension, update 'Layers' attribute
3468          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3469    
3470          // if this is velocity dimension and got custom defined ranges, update velocity table          UpdateVelocityTable();
         if (pDimDef->dimension  == dimension_velocity &&  
             pDimDef->split_type == split_type_customvelocity) {  
             UpdateVelocityTable(pDimDef);  
         }  
3471      }      }
3472    
3473      /** @brief Delete an existing dimension.      /** @brief Delete an existing dimension.
# Line 2350  namespace { Line 3502  namespace {
3502          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3503              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3504    
3505            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3506    
3507          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3508          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3509          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2358  namespace { Line 3512  namespace {
3512                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3513                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3514                                      iLowerBit;                                      iLowerBit;
3515    
3516                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3517                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3518                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3519                      DimensionRegions--;                      DimensionRegions--;
# Line 2378  namespace { Line 3534  namespace {
3534              }              }
3535          }          }
3536    
3537            // remove the this dimension from the upper limits arrays
3538            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3539                DimensionRegion* d = pDimensionRegions[j];
3540                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3541                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3542                }
3543                d->DimensionUpperLimits[Dimensions - 1] = 127;
3544            }
3545    
3546          // 'remove' dimension definition          // 'remove' dimension definition
3547          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3548              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2385  namespace { Line 3550  namespace {
3550          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3551          pDimensionDefinitions[Dimensions - 1].bits      = 0;          pDimensionDefinitions[Dimensions - 1].bits      = 0;
3552          pDimensionDefinitions[Dimensions - 1].zones     = 0;          pDimensionDefinitions[Dimensions - 1].zones     = 0;
         if (pDimensionDefinitions[Dimensions - 1].ranges) {  
             delete[] pDimensionDefinitions[Dimensions - 1].ranges;  
             pDimensionDefinitions[Dimensions - 1].ranges = NULL;  
         }  
3553    
3554          Dimensions--;          Dimensions--;
3555    
# Line 2396  namespace { Line 3557  namespace {
3557          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3558      }      }
3559    
3560      Region::~Region() {      /** @brief Delete one split zone of a dimension (decrement zone amount).
3561          for (uint i = 0; i < Dimensions; i++) {       *
3562              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;       * Instead of deleting an entire dimensions, this method will only delete
3563         * one particular split zone given by @a zone of the Region's dimension
3564         * given by @a type. So this method will simply decrement the amount of
3565         * zones by one of the dimension in question. To be able to do that, the
3566         * respective dimension must exist on this Region and it must have at least
3567         * 3 zones. All DimensionRegion objects associated with the zone will be
3568         * deleted.
3569         *
3570         * @param type - identifies the dimension where a zone shall be deleted
3571         * @param zone - index of the dimension split zone that shall be deleted
3572         * @throws gig::Exception if requested zone could not be deleted
3573         */
3574        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3575            dimension_def_t* oldDef = GetDimensionDefinition(type);
3576            if (!oldDef)
3577                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3578            if (oldDef->zones <= 2)
3579                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3580            if (zone < 0 || zone >= oldDef->zones)
3581                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3582    
3583            const int newZoneSize = oldDef->zones - 1;
3584    
3585            // create a temporary Region which just acts as a temporary copy
3586            // container and will be deleted at the end of this function and will
3587            // also not be visible through the API during this process
3588            gig::Region* tempRgn = NULL;
3589            {
3590                // adding these temporary chunks is probably not even necessary
3591                Instrument* instr = static_cast<Instrument*>(GetParent());
3592                RIFF::List* pCkInstrument = instr->pCkInstrument;
3593                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3594                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3595                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3596                tempRgn = new Region(instr, rgn);
3597            }
3598    
3599            // copy this region's dimensions (with already the dimension split size
3600            // requested by the arguments of this method call) to the temporary
3601            // region, and don't use Region::CopyAssign() here for this task, since
3602            // it would also alter fast lookup helper variables here and there
3603            dimension_def_t newDef;
3604            for (int i = 0; i < Dimensions; ++i) {
3605                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3606                // is this the dimension requested by the method arguments? ...
3607                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3608                    def.zones = newZoneSize;
3609                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3610                    newDef = def;
3611                }
3612                tempRgn->AddDimension(&def);
3613            }
3614    
3615            // find the dimension index in the tempRegion which is the dimension
3616            // type passed to this method (paranoidly expecting different order)
3617            int tempReducedDimensionIndex = -1;
3618            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3619                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3620                    tempReducedDimensionIndex = d;
3621                    break;
3622                }
3623            }
3624    
3625            // copy dimension regions from this region to the temporary region
3626            for (int iDst = 0; iDst < 256; ++iDst) {
3627                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3628                if (!dstDimRgn) continue;
3629                std::map<dimension_t,int> dimCase;
3630                bool isValidZone = true;
3631                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3632                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3633                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3634                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3635                    baseBits += dstBits;
3636                    // there are also DimensionRegion objects of unused zones, skip them
3637                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3638                        isValidZone = false;
3639                        break;
3640                    }
3641                }
3642                if (!isValidZone) continue;
3643                // a bit paranoid: cope with the chance that the dimensions would
3644                // have different order in source and destination regions
3645                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3646                if (dimCase[type] >= zone) dimCase[type]++;
3647                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3648                dstDimRgn->CopyAssign(srcDimRgn);
3649                // if this is the upper most zone of the dimension passed to this
3650                // method, then correct (raise) its upper limit to 127
3651                if (newDef.split_type == split_type_normal && isLastZone)
3652                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3653            }
3654    
3655            // now tempRegion's dimensions and DimensionRegions basically reflect
3656            // what we wanted to get for this actual Region here, so we now just
3657            // delete and recreate the dimension in question with the new amount
3658            // zones and then copy back from tempRegion      
3659            DeleteDimension(oldDef);
3660            AddDimension(&newDef);
3661            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3662                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3663                if (!srcDimRgn) continue;
3664                std::map<dimension_t,int> dimCase;
3665                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3666                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3667                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3668                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3669                    baseBits += srcBits;
3670                }
3671                // a bit paranoid: cope with the chance that the dimensions would
3672                // have different order in source and destination regions
3673                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3674                if (!dstDimRgn) continue;
3675                dstDimRgn->CopyAssign(srcDimRgn);
3676            }
3677    
3678            // delete temporary region
3679            delete tempRgn;
3680    
3681            UpdateVelocityTable();
3682        }
3683    
3684        /** @brief Divide split zone of a dimension in two (increment zone amount).
3685         *
3686         * This will increment the amount of zones for the dimension (given by
3687         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3688         * in the middle of its zone range in two. So the two zones resulting from
3689         * the zone being splitted, will be an equivalent copy regarding all their
3690         * articulation informations and sample reference. The two zones will only
3691         * differ in their zone's upper limit
3692         * (DimensionRegion::DimensionUpperLimits).
3693         *
3694         * @param type - identifies the dimension where a zone shall be splitted
3695         * @param zone - index of the dimension split zone that shall be splitted
3696         * @throws gig::Exception if requested zone could not be splitted
3697         */
3698        void Region::SplitDimensionZone(dimension_t type, int zone) {
3699            dimension_def_t* oldDef = GetDimensionDefinition(type);
3700            if (!oldDef)
3701                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3702            if (zone < 0 || zone >= oldDef->zones)
3703                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3704    
3705            const int newZoneSize = oldDef->zones + 1;
3706    
3707            // create a temporary Region which just acts as a temporary copy
3708            // container and will be deleted at the end of this function and will
3709            // also not be visible through the API during this process
3710            gig::Region* tempRgn = NULL;
3711            {
3712                // adding these temporary chunks is probably not even necessary
3713                Instrument* instr = static_cast<Instrument*>(GetParent());
3714                RIFF::List* pCkInstrument = instr->pCkInstrument;
3715                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3716                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3717                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3718                tempRgn = new Region(instr, rgn);
3719            }
3720    
3721            // copy this region's dimensions (with already the dimension split size
3722            // requested by the arguments of this method call) to the temporary
3723            // region, and don't use Region::CopyAssign() here for this task, since
3724            // it would also alter fast lookup helper variables here and there
3725            dimension_def_t newDef;
3726            for (int i = 0; i < Dimensions; ++i) {
3727                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3728                // is this the dimension requested by the method arguments? ...
3729                if (def.dimension == type) { // ... if yes, increment zone amount by one
3730                    def.zones = newZoneSize;
3731                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3732                    newDef = def;
3733                }
3734                tempRgn->AddDimension(&def);
3735            }
3736    
3737            // find the dimension index in the tempRegion which is the dimension
3738            // type passed to this method (paranoidly expecting different order)
3739            int tempIncreasedDimensionIndex = -1;
3740            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3741                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3742                    tempIncreasedDimensionIndex = d;
3743                    break;
3744                }
3745            }
3746    
3747            // copy dimension regions from this region to the temporary region
3748            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3749                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3750                if (!srcDimRgn) continue;
3751                std::map<dimension_t,int> dimCase;
3752                bool isValidZone = true;
3753                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3754                    const int srcBits = pDimensionDefinitions[d].bits;
3755                    dimCase[pDimensionDefinitions[d].dimension] =
3756                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3757                    // there are also DimensionRegion objects for unused zones, skip them
3758                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3759                        isValidZone = false;
3760                        break;
3761                    }
3762                    baseBits += srcBits;
3763                }
3764                if (!isValidZone) continue;
3765                // a bit paranoid: cope with the chance that the dimensions would
3766                // have different order in source and destination regions            
3767                if (dimCase[type] > zone) dimCase[type]++;
3768                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3769                dstDimRgn->CopyAssign(srcDimRgn);
3770                // if this is the requested zone to be splitted, then also copy
3771                // the source DimensionRegion to the newly created target zone
3772                // and set the old zones upper limit lower
3773                if (dimCase[type] == zone) {
3774                    // lower old zones upper limit
3775                    if (newDef.split_type == split_type_normal) {
3776                        const int high =
3777                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3778                        int low = 0;
3779                        if (zone > 0) {
3780                            std::map<dimension_t,int> lowerCase = dimCase;
3781                            lowerCase[type]--;
3782                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3783                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3784                        }
3785                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3786                    }
3787                    // fill the newly created zone of the divided zone as well
3788                    dimCase[type]++;
3789                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3790                    dstDimRgn->CopyAssign(srcDimRgn);
3791                }
3792            }
3793    
3794            // now tempRegion's dimensions and DimensionRegions basically reflect
3795            // what we wanted to get for this actual Region here, so we now just
3796            // delete and recreate the dimension in question with the new amount
3797            // zones and then copy back from tempRegion      
3798            DeleteDimension(oldDef);
3799            AddDimension(&newDef);
3800            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3801                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3802                if (!srcDimRgn) continue;
3803                std::map<dimension_t,int> dimCase;
3804                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3805                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3806                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3807                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3808                    baseBits += srcBits;
3809                }
3810                // a bit paranoid: cope with the chance that the dimensions would
3811                // have different order in source and destination regions
3812                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3813                if (!dstDimRgn) continue;
3814                dstDimRgn->CopyAssign(srcDimRgn);
3815            }
3816    
3817            // delete temporary region
3818            delete tempRgn;
3819    
3820            UpdateVelocityTable();
3821        }
3822    
3823        /** @brief Change type of an existing dimension.
3824         *
3825         * Alters the dimension type of a dimension already existing on this
3826         * region. If there is currently no dimension on this Region with type
3827         * @a oldType, then this call with throw an Exception. Likewise there are
3828         * cases where the requested dimension type cannot be performed. For example
3829         * if the new dimension type shall be gig::dimension_samplechannel, and the
3830         * current dimension has more than 2 zones. In such cases an Exception is
3831         * thrown as well.
3832         *
3833         * @param oldType - identifies the existing dimension to be changed
3834         * @param newType - to which dimension type it should be changed to
3835         * @throws gig::Exception if requested change cannot be performed
3836         */
3837        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3838            if (oldType == newType) return;
3839            dimension_def_t* def = GetDimensionDefinition(oldType);
3840            if (!def)
3841                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3842            if (newType == dimension_samplechannel && def->zones != 2)
3843                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3844            if (GetDimensionDefinition(newType))
3845                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3846            def->dimension  = newType;
3847            def->split_type = __resolveSplitType(newType);
3848        }
3849    
3850        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3851            uint8_t bits[8] = {};
3852            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3853                 it != DimCase.end(); ++it)
3854            {
3855                for (int d = 0; d < Dimensions; ++d) {
3856                    if (pDimensionDefinitions[d].dimension == it->first) {
3857                        bits[d] = it->second;
3858                        goto nextDimCaseSlice;
3859                    }
3860                }
3861                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3862                nextDimCaseSlice:
3863                ; // noop
3864          }          }
3865            return GetDimensionRegionByBit(bits);
3866        }
3867    
3868        /**
3869         * Searches in the current Region for a dimension of the given dimension
3870         * type and returns the precise configuration of that dimension in this
3871         * Region.
3872         *
3873         * @param type - dimension type of the sought dimension
3874         * @returns dimension definition or NULL if there is no dimension with
3875         *          sought type in this Region.
3876         */
3877        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3878            for (int i = 0; i < Dimensions; ++i)
3879                if (pDimensionDefinitions[i].dimension == type)
3880                    return &pDimensionDefinitions[i];
3881            return NULL;
3882        }
3883    
3884        Region::~Region() {
3885          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3886              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
3887          }          }
# Line 2424  namespace { Line 3906  namespace {
3906       * @see             Dimensions       * @see             Dimensions
3907       */       */
3908      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3909          uint8_t bits[8] = { 0 };          uint8_t bits;
3910            int veldim = -1;
3911            int velbitpos = 0;
3912            int bitpos = 0;
3913            int dimregidx = 0;
3914          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
3915              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3916              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
3917                  case split_type_normal:                  veldim = i;
3918                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);                  velbitpos = bitpos;
3919                      break;              } else {
3920                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
3921                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
3922                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3923                  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
3924                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3925                      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;
3926                      break;                              }
3927                            } else {
3928                                // gig2: evenly sized zones
3929                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3930                            }
3931                            break;
3932                        case split_type_bit: // the value is already the sought dimension bit number
3933                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3934                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3935                            break;
3936                    }
3937                    dimregidx |= bits << bitpos;
3938              }              }
3939                bitpos += pDimensionDefinitions[i].bits;
3940          }          }
3941          return GetDimensionRegionByBit(bits);          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3942            if (!dimreg) return NULL;
3943            if (veldim != -1) {
3944                // (dimreg is now the dimension region for the lowest velocity)
3945                if (dimreg->VelocityTable) // custom defined zone ranges
3946                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3947                else // normal split type
3948                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3949    
3950                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3951                dimregidx |= (bits & limiter_mask) << velbitpos;
3952                dimreg = pDimensionRegions[dimregidx & 255];
3953            }
3954            return dimreg;
3955        }
3956    
3957        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3958            uint8_t bits;
3959            int veldim = -1;
3960            int velbitpos = 0;
3961            int bitpos = 0;
3962            int dimregidx = 0;
3963            for (uint i = 0; i < Dimensions; i++) {
3964                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3965                    // the velocity dimension must be handled after the other dimensions
3966                    veldim = i;
3967                    velbitpos = bitpos;
3968                } else {
3969                    switch (pDimensionDefinitions[i].split_type) {
3970                        case split_type_normal:
3971                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3972                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3973                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3974                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3975                                }
3976                            } else {
3977                                // gig2: evenly sized zones
3978                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3979                            }
3980                            break;
3981                        case split_type_bit: // the value is already the sought dimension bit number
3982                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3983                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3984                            break;
3985                    }
3986                    dimregidx |= bits << bitpos;
3987                }
3988                bitpos += pDimensionDefinitions[i].bits;
3989            }
3990            dimregidx &= 255;
3991            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3992            if (!dimreg) return -1;
3993            if (veldim != -1) {
3994                // (dimreg is now the dimension region for the lowest velocity)
3995                if (dimreg->VelocityTable) // custom defined zone ranges
3996                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3997                else // normal split type
3998                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3999    
4000                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4001                dimregidx |= (bits & limiter_mask) << velbitpos;
4002                dimregidx &= 255;
4003            }
4004            return dimregidx;
4005      }      }
4006    
4007      /**      /**
# Line 2480  namespace { Line 4041  namespace {
4041      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
4042          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4043          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4044          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          if (!file->pWavePoolTable) return NULL;
4045          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4046          Sample* sample = file->GetFirstSample(pProgress);          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4047          while (sample) {              // use 64 bit wave pool offsets (treating this as large file)
4048              if (sample->ulWavePoolOffset == soughtoffset &&              uint64_t soughtoffset =
4049                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4050              sample = file->GetNextSample();                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4051                Sample* sample = file->GetFirstSample(pProgress);
4052                while (sample) {
4053                    if (sample->ullWavePoolOffset == soughtoffset)
4054                        return static_cast<gig::Sample*>(sample);
4055                    sample = file->GetNextSample();
4056                }
4057            } else {
4058                // use extension files and 32 bit wave pool offsets
4059                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4060                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4061                Sample* sample = file->GetFirstSample(pProgress);
4062                while (sample) {
4063                    if (sample->ullWavePoolOffset == soughtoffset &&
4064                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4065                    sample = file->GetNextSample();
4066                }
4067            }
4068            return NULL;
4069        }
4070        
4071        /**
4072         * Make a (semi) deep copy of the Region object given by @a orig
4073         * and assign it to this object.
4074         *
4075         * Note that all sample pointers referenced by @a orig are simply copied as
4076         * memory address. Thus the respective samples are shared, not duplicated!
4077         *
4078         * @param orig - original Region object to be copied from
4079         */
4080        void Region::CopyAssign(const Region* orig) {
4081            CopyAssign(orig, NULL);
4082        }
4083        
4084        /**
4085         * Make a (semi) deep copy of the Region object given by @a orig and
4086         * assign it to this object
4087         *
4088         * @param mSamples - crosslink map between the foreign file's samples and
4089         *                   this file's samples
4090         */
4091        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4092            // handle base classes
4093            DLS::Region::CopyAssign(orig);
4094            
4095            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4096                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4097            }
4098            
4099            // handle own member variables
4100            for (int i = Dimensions - 1; i >= 0; --i) {
4101                DeleteDimension(&pDimensionDefinitions[i]);
4102            }
4103            Layers = 0; // just to be sure
4104            for (int i = 0; i < orig->Dimensions; i++) {
4105                // we need to copy the dim definition here, to avoid the compiler
4106                // complaining about const-ness issue
4107                dimension_def_t def = orig->pDimensionDefinitions[i];
4108                AddDimension(&def);
4109            }
4110            for (int i = 0; i < 256; i++) {
4111                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4112                    pDimensionRegions[i]->CopyAssign(
4113                        orig->pDimensionRegions[i],
4114                        mSamples
4115                    );
4116                }
4117            }
4118            Layers = orig->Layers;
4119        }
4120    
4121    
4122    // *************** MidiRule ***************
4123    // *
4124    
4125        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4126            _3ewg->SetPos(36);
4127            Triggers = _3ewg->ReadUint8();
4128            _3ewg->SetPos(40);
4129            ControllerNumber = _3ewg->ReadUint8();
4130            _3ewg->SetPos(46);
4131            for (int i = 0 ; i < Triggers ; i++) {
4132                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4133                pTriggers[i].Descending = _3ewg->ReadUint8();
4134                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4135                pTriggers[i].Key = _3ewg->ReadUint8();
4136                pTriggers[i].NoteOff = _3ewg->ReadUint8();
4137                pTriggers[i].Velocity = _3ewg->ReadUint8();
4138                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4139                _3ewg->ReadUint8();
4140            }
4141        }
4142    
4143        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4144            ControllerNumber(0),
4145            Triggers(0) {
4146        }
4147    
4148        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4149            pData[32] = 4;
4150            pData[33] = 16;
4151            pData[36] = Triggers;
4152            pData[40] = ControllerNumber;
4153            for (int i = 0 ; i < Triggers ; i++) {
4154                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4155                pData[47 + i * 8] = pTriggers[i].Descending;
4156                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4157                pData[49 + i * 8] = pTriggers[i].Key;
4158                pData[50 + i * 8] = pTriggers[i].NoteOff;
4159                pData[51 + i * 8] = pTriggers[i].Velocity;
4160                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4161            }
4162        }
4163    
4164        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4165            _3ewg->SetPos(36);
4166            LegatoSamples = _3ewg->ReadUint8(); // always 12
4167            _3ewg->SetPos(40);
4168            BypassUseController = _3ewg->ReadUint8();
4169            BypassKey = _3ewg->ReadUint8();
4170            BypassController = _3ewg->ReadUint8();
4171            ThresholdTime = _3ewg->ReadUint16();
4172            _3ewg->ReadInt16();
4173            ReleaseTime = _3ewg->ReadUint16();
4174            _3ewg->ReadInt16();
4175            KeyRange.low = _3ewg->ReadUint8();
4176            KeyRange.high = _3ewg->ReadUint8();
4177            _3ewg->SetPos(64);
4178            ReleaseTriggerKey = _3ewg->ReadUint8();
4179            AltSustain1Key = _3ewg->ReadUint8();
4180            AltSustain2Key = _3ewg->ReadUint8();
4181        }
4182    
4183        MidiRuleLegato::MidiRuleLegato() :
4184            LegatoSamples(12),
4185            BypassUseController(false),
4186            BypassKey(0),
4187            BypassController(1),
4188            ThresholdTime(20),
4189            ReleaseTime(20),
4190            ReleaseTriggerKey(0),
4191            AltSustain1Key(0),
4192            AltSustain2Key(0)
4193        {
4194            KeyRange.low = KeyRange.high = 0;
4195        }
4196    
4197        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4198            pData[32] = 0;
4199            pData[33] = 16;
4200            pData[36] = LegatoSamples;
4201            pData[40] = BypassUseController;
4202            pData[41] = BypassKey;
4203            pData[42] = BypassController;
4204            store16(&pData[43], ThresholdTime);
4205            store16(&pData[47], ReleaseTime);
4206            pData[51] = KeyRange.low;
4207            pData[52] = KeyRange.high;
4208            pData[64] = ReleaseTriggerKey;
4209            pData[65] = AltSustain1Key;
4210            pData[66] = AltSustain2Key;
4211        }
4212    
4213        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4214            _3ewg->SetPos(36);
4215            Articulations = _3ewg->ReadUint8();
4216            int flags = _3ewg->ReadUint8();
4217            Polyphonic = flags & 8;
4218            Chained = flags & 4;
4219            Selector = (flags & 2) ? selector_controller :
4220                (flags & 1) ? selector_key_switch : selector_none;
4221            Patterns = _3ewg->ReadUint8();
4222            _3ewg->ReadUint8(); // chosen row
4223            _3ewg->ReadUint8(); // unknown
4224            _3ewg->ReadUint8(); // unknown
4225            _3ewg->ReadUint8(); // unknown
4226            KeySwitchRange.low = _3ewg->ReadUint8();
4227            KeySwitchRange.high = _3ewg->ReadUint8();
4228            Controller = _3ewg->ReadUint8();
4229            PlayRange.low = _3ewg->ReadUint8();
4230            PlayRange.high = _3ewg->ReadUint8();
4231    
4232            int n = std::min(int(Articulations), 32);
4233            for (int i = 0 ; i < n ; i++) {
4234                _3ewg->ReadString(pArticulations[i], 32);
4235            }
4236            _3ewg->SetPos(1072);
4237            n = std::min(int(Patterns), 32);
4238            for (int i = 0 ; i < n ; i++) {
4239                _3ewg->ReadString(pPatterns[i].Name, 16);
4240                pPatterns[i].Size = _3ewg->ReadUint8();
4241                _3ewg->Read(&pPatterns[i][0], 1, 32);
4242            }
4243        }
4244    
4245        MidiRuleAlternator::MidiRuleAlternator() :
4246            Articulations(0),
4247            Patterns(0),
4248            Selector(selector_none),
4249            Controller(0),
4250            Polyphonic(false),
4251            Chained(false)
4252        {
4253            PlayRange.low = PlayRange.high = 0;
4254            KeySwitchRange.low = KeySwitchRange.high = 0;
4255        }
4256    
4257        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4258            pData[32] = 3;
4259            pData[33] = 16;
4260            pData[36] = Articulations;
4261            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4262                (Selector == selector_controller ? 2 :
4263                 (Selector == selector_key_switch ? 1 : 0));
4264            pData[38] = Patterns;
4265    
4266            pData[43] = KeySwitchRange.low;
4267            pData[44] = KeySwitchRange.high;
4268            pData[45] = Controller;
4269            pData[46] = PlayRange.low;
4270            pData[47] = PlayRange.high;
4271    
4272            char* str = reinterpret_cast<char*>(pData);
4273            int pos = 48;
4274            int n = std::min(int(Articulations), 32);
4275            for (int i = 0 ; i < n ; i++, pos += 32) {
4276                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4277            }
4278    
4279            pos = 1072;
4280            n = std::min(int(Patterns), 32);
4281            for (int i = 0 ; i < n ; i++, pos += 49) {
4282                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4283                pData[pos + 16] = pPatterns[i].Size;
4284                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4285            }
4286        }
4287    
4288    // *************** Script ***************
4289    // *
4290    
4291        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4292            pGroup = group;
4293            pChunk = ckScri;
4294            if (ckScri) { // object is loaded from file ...
4295                // read header
4296                uint32_t headerSize = ckScri->ReadUint32();
4297                Compression = (Compression_t) ckScri->ReadUint32();
4298                Encoding    = (Encoding_t) ckScri->ReadUint32();
4299                Language    = (Language_t) ckScri->ReadUint32();
4300                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4301                crc         = ckScri->ReadUint32();
4302                uint32_t nameSize = ckScri->ReadUint32();
4303                Name.resize(nameSize, ' ');
4304                for (int i = 0; i < nameSize; ++i)
4305                    Name[i] = ckScri->ReadUint8();
4306                // to handle potential future extensions of the header
4307                ckScri->SetPos(sizeof(int32_t) + headerSize);
4308                // read actual script data
4309                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4310                data.resize(scriptSize);
4311                for (int i = 0; i < scriptSize; ++i)
4312                    data[i] = ckScri->ReadUint8();
4313            } else { // this is a new script object, so just initialize it as such ...
4314                Compression = COMPRESSION_NONE;
4315                Encoding = ENCODING_ASCII;
4316                Language = LANGUAGE_NKSP;
4317                Bypass   = false;
4318                crc      = 0;
4319                Name     = "Unnamed Script";
4320            }
4321        }
4322    
4323        Script::~Script() {
4324        }
4325    
4326        /**
4327         * Returns the current script (i.e. as source code) in text format.
4328         */
4329        String Script::GetScriptAsText() {
4330            String s;
4331            s.resize(data.size(), ' ');
4332            memcpy(&s[0], &data[0], data.size());
4333            return s;
4334        }
4335    
4336        /**
4337         * Replaces the current script with the new script source code text given
4338         * by @a text.
4339         *
4340         * @param text - new script source code
4341         */
4342        void Script::SetScriptAsText(const String& text) {
4343            data.resize(text.size());
4344            memcpy(&data[0], &text[0], text.size());
4345        }
4346    
4347        /**
4348         * Apply this script to the respective RIFF chunks. You have to call
4349         * File::Save() to make changes persistent.
4350         *
4351         * Usually there is absolutely no need to call this method explicitly.
4352         * It will be called automatically when File::Save() was called.
4353         *
4354         * @param pProgress - callback function for progress notification
4355         */
4356        void Script::UpdateChunks(progress_t* pProgress) {
4357            // recalculate CRC32 check sum
4358            __resetCRC(crc);
4359            __calculateCRC(&data[0], data.size(), crc);
4360            __finalizeCRC(crc);
4361            // make sure chunk exists and has the required size
4362            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4363            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4364            else pChunk->Resize(chunkSize);
4365            // fill the chunk data to be written to disk
4366            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4367            int pos = 0;
4368            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4369            pos += sizeof(int32_t);
4370            store32(&pData[pos], Compression);
4371            pos += sizeof(int32_t);
4372            store32(&pData[pos], Encoding);
4373            pos += sizeof(int32_t);
4374            store32(&pData[pos], Language);
4375            pos += sizeof(int32_t);
4376            store32(&pData[pos], Bypass ? 1 : 0);
4377            pos += sizeof(int32_t);
4378            store32(&pData[pos], crc);
4379            pos += sizeof(int32_t);
4380            store32(&pData[pos], (uint32_t) Name.size());
4381            pos += sizeof(int32_t);
4382            for (int i = 0; i < Name.size(); ++i, ++pos)
4383                pData[pos] = Name[i];
4384            for (int i = 0; i < data.size(); ++i, ++pos)
4385                pData[pos] = data[i];
4386        }
4387    
4388        /**
4389         * Move this script from its current ScriptGroup to another ScriptGroup
4390         * given by @a pGroup.
4391         *
4392         * @param pGroup - script's new group
4393         */
4394        void Script::SetGroup(ScriptGroup* pGroup) {
4395            if (this->pGroup == pGroup) return;
4396            if (pChunk)
4397                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4398            this->pGroup = pGroup;
4399        }
4400    
4401        /**
4402         * Returns the script group this script currently belongs to. Each script
4403         * is a member of exactly one ScriptGroup.
4404         *
4405         * @returns current script group
4406         */
4407        ScriptGroup* Script::GetGroup() const {
4408            return pGroup;
4409        }
4410    
4411        /**
4412         * Make a (semi) deep copy of the Script object given by @a orig
4413         * and assign it to this object. Note: the ScriptGroup this Script
4414         * object belongs to remains untouched by this call.
4415         *
4416         * @param orig - original Script object to be copied from
4417         */
4418        void Script::CopyAssign(const Script* orig) {
4419            Name        = orig->Name;
4420            Compression = orig->Compression;
4421            Encoding    = orig->Encoding;
4422            Language    = orig->Language;
4423            Bypass      = orig->Bypass;
4424            data        = orig->data;
4425        }
4426    
4427        void Script::RemoveAllScriptReferences() {
4428            File* pFile = pGroup->pFile;
4429            for (int i = 0; pFile->GetInstrument(i); ++i) {
4430                Instrument* instr = pFile->GetInstrument(i);
4431                instr->RemoveScript(this);
4432            }
4433        }
4434    
4435    // *************** ScriptGroup ***************
4436    // *
4437    
4438        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4439            pFile = file;
4440            pList = lstRTIS;
4441            pScripts = NULL;
4442            if (lstRTIS) {
4443                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4444                ::LoadString(ckName, Name);
4445            } else {
4446                Name = "Default Group";
4447            }
4448        }
4449    
4450        ScriptGroup::~ScriptGroup() {
4451            if (pScripts) {
4452                std::list<Script*>::iterator iter = pScripts->begin();
4453                std::list<Script*>::iterator end  = pScripts->end();
4454                while (iter != end) {
4455                    delete *iter;
4456                    ++iter;
4457                }
4458                delete pScripts;
4459            }
4460        }
4461    
4462        /**
4463         * Apply this script group to the respective RIFF chunks. You have to call
4464         * File::Save() to make changes persistent.
4465         *
4466         * Usually there is absolutely no need to call this method explicitly.
4467         * It will be called automatically when File::Save() was called.
4468         *
4469         * @param pProgress - callback function for progress notification
4470         */
4471        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4472            if (pScripts) {
4473                if (!pList)
4474                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4475    
4476                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4477                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4478    
4479                for (std::list<Script*>::iterator it = pScripts->begin();
4480                     it != pScripts->end(); ++it)
4481                {
4482                    (*it)->UpdateChunks(pProgress);
4483                }
4484          }          }
4485        }
4486    
4487        /** @brief Get instrument script.
4488         *
4489         * Returns the real-time instrument script with the given index.
4490         *
4491         * @param index - number of the sought script (0..n)
4492         * @returns sought script or NULL if there's no such script
4493         */
4494        Script* ScriptGroup::GetScript(uint index) {
4495            if (!pScripts) LoadScripts();
4496            std::list<Script*>::iterator it = pScripts->begin();
4497            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4498                if (i == index) return *it;
4499          return NULL;          return NULL;
4500      }      }
4501    
4502        /** @brief Add new instrument script.
4503         *
4504         * Adds a new real-time instrument script to the file. The script is not
4505         * actually used / executed unless it is referenced by an instrument to be
4506         * used. This is similar to samples, which you can add to a file, without
4507         * an instrument necessarily actually using it.
4508         *
4509         * You have to call Save() to make this persistent to the file.
4510         *
4511         * @return new empty script object
4512         */
4513        Script* ScriptGroup::AddScript() {
4514            if (!pScripts) LoadScripts();
4515            Script* pScript = new Script(this, NULL);
4516            pScripts->push_back(pScript);
4517            return pScript;
4518        }
4519    
4520        /** @brief Delete an instrument script.
4521         *
4522         * This will delete the given real-time instrument script. References of
4523         * instruments that are using that script will be removed accordingly.
4524         *
4525         * You have to call Save() to make this persistent to the file.
4526         *
4527         * @param pScript - script to delete
4528         * @throws gig::Exception if given script could not be found
4529         */
4530        void ScriptGroup::DeleteScript(Script* pScript) {
4531            if (!pScripts) LoadScripts();
4532            std::list<Script*>::iterator iter =
4533                find(pScripts->begin(), pScripts->end(), pScript);
4534            if (iter == pScripts->end())
4535                throw gig::Exception("Could not delete script, could not find given script");
4536            pScripts->erase(iter);
4537            pScript->RemoveAllScriptReferences();
4538            if (pScript->pChunk)
4539                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4540            delete pScript;
4541        }
4542    
4543        void ScriptGroup::LoadScripts() {
4544            if (pScripts) return;
4545            pScripts = new std::list<Script*>;
4546            if (!pList) return;
4547    
4548            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4549                 ck = pList->GetNextSubChunk())
4550            {
4551                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4552                    pScripts->push_back(new Script(this, ck));
4553                }
4554            }
4555        }
4556    
4557  // *************** Instrument ***************  // *************** Instrument ***************
4558  // *  // *
4559    
4560      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) {
4561            static const DLS::Info::string_length_t fixedStringLengths[] = {
4562                { CHUNK_ID_INAM, 64 },
4563                { CHUNK_ID_ISFT, 12 },
4564                { 0, 0 }
4565            };
4566            pInfo->SetFixedStringLengths(fixedStringLengths);
4567    
4568          // Initialization          // Initialization
4569          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4570            EffectSend = 0;
4571            Attenuation = 0;
4572            FineTune = 0;
4573            PitchbendRange = 2;
4574            PianoReleaseMode = false;
4575            DimensionKeyRange.low = 0;
4576            DimensionKeyRange.high = 0;
4577            pMidiRules = new MidiRule*[3];
4578            pMidiRules[0] = NULL;
4579            pScriptRefs = NULL;
4580    
4581          // Loading          // Loading
4582          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2513  namespace { Line 4591  namespace {
4591                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4592                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4593                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4594    
4595                    if (_3ewg->GetSize() > 32) {
4596                        // read MIDI rules
4597                        int i = 0;
4598                        _3ewg->SetPos(32);
4599                        uint8_t id1 = _3ewg->ReadUint8();
4600                        uint8_t id2 = _3ewg->ReadUint8();
4601    
4602                        if (id2 == 16) {
4603                            if (id1 == 4) {
4604                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4605                            } else if (id1 == 0) {
4606                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4607                            } else if (id1 == 3) {
4608                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4609                            } else {
4610                                pMidiRules[i++] = new MidiRuleUnknown;
4611                            }
4612                        }
4613                        else if (id1 != 0 || id2 != 0) {
4614                            pMidiRules[i++] = new MidiRuleUnknown;
4615                        }
4616                        //TODO: all the other types of rules
4617    
4618                        pMidiRules[i] = NULL;
4619                    }
4620                }
4621            }
4622    
4623            if (pFile->GetAutoLoad()) {
4624                if (!pRegions) pRegions = new RegionList;
4625                RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4626                if (lrgn) {
4627                    RIFF::List* rgn = lrgn->GetFirstSubList();
4628                    while (rgn) {
4629                        if (rgn->GetListType() == LIST_TYPE_RGN) {
4630                            __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4631                            pRegions->push_back(new Region(this, rgn));
4632                        }
4633                        rgn = lrgn->GetNextSubList();
4634                    }
4635                    // Creating Region Key Table for fast lookup
4636                    UpdateRegionKeyTable();
4637              }              }
4638          }          }
4639    
4640          if (!pRegions) pRegions = new RegionList;          // own gig format extensions
4641          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4642          if (lrgn) {          if (lst3LS) {
4643              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4644              while (rgn) {              if (ckSCSL) {
4645                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  int headerSize = ckSCSL->ReadUint32();
4646                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                  int slotCount  = ckSCSL->ReadUint32();
4647                      pRegions->push_back(new Region(this, rgn));                  if (slotCount) {
4648                        int slotSize  = ckSCSL->ReadUint32();
4649                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4650                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4651                        for (int i = 0; i < slotCount; ++i) {
4652                            _ScriptPooolEntry e;
4653                            e.fileOffset = ckSCSL->ReadUint32();
4654                            e.bypass     = ckSCSL->ReadUint32() & 1;
4655                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4656                            scriptPoolFileOffsets.push_back(e);
4657                        }
4658                  }                  }
                 rgn = lrgn->GetNextSubList();  
4659              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4660          }          }
4661    
4662          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4663      }      }
4664    
4665      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4666            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4667          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
4668          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
4669          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2546  namespace { Line 4675  namespace {
4675      }      }
4676    
4677      Instrument::~Instrument() {      Instrument::~Instrument() {
4678            for (int i = 0 ; pMidiRules[i] ; i++) {
4679                delete pMidiRules[i];
4680            }
4681            delete[] pMidiRules;
4682            if (pScriptRefs) delete pScriptRefs;
4683      }      }
4684    
4685      /**      /**
# Line 2555  namespace { Line 4689  namespace {
4689       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4690       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4691       *       *
4692         * @param pProgress - callback function for progress notification
4693       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4694       */       */
4695      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4696          // first update base classes' chunks          // first update base classes' chunks
4697          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4698    
4699          // update Regions' chunks          // update Regions' chunks
4700          {          {
4701              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4702              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4703              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4704                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4705          }          }
4706    
4707          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 2574  namespace { Line 4709  namespace {
4709          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4710          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4711          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4712          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4713                File* pFile = (File*) GetParent();
4714    
4715                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4716                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4717                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4718                memset(_3ewg->LoadChunkData(), 0, size);
4719            }
4720          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4721          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4722          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
4723          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
4724          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
4725          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
4726          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4727                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4728          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
4729          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
4730    
4731            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4732                pData[32] = 0;
4733                pData[33] = 0;
4734            } else {
4735                for (int i = 0 ; pMidiRules[i] ; i++) {
4736                    pMidiRules[i]->UpdateChunks(pData);
4737                }
4738            }
4739    
4740            // own gig format extensions
4741           if (ScriptSlotCount()) {
4742               // make sure we have converted the original loaded script file
4743               // offsets into valid Script object pointers
4744               LoadScripts();
4745    
4746               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4747               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4748               const int slotCount = (int) pScriptRefs->size();
4749               const int headerSize = 3 * sizeof(uint32_t);
4750               const int slotSize  = 2 * sizeof(uint32_t);
4751               const int totalChunkSize = headerSize + slotCount * slotSize;
4752               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4753               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4754               else ckSCSL->Resize(totalChunkSize);
4755               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4756               int pos = 0;
4757               store32(&pData[pos], headerSize);
4758               pos += sizeof(uint32_t);
4759               store32(&pData[pos], slotCount);
4760               pos += sizeof(uint32_t);
4761               store32(&pData[pos], slotSize);
4762               pos += sizeof(uint32_t);
4763               for (int i = 0; i < slotCount; ++i) {
4764                   // arbitrary value, the actual file offset will be updated in
4765                   // UpdateScriptFileOffsets() after the file has been resized
4766                   int bogusFileOffset = 0;
4767                   store32(&pData[pos], bogusFileOffset);
4768                   pos += sizeof(uint32_t);
4769                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4770                   pos += sizeof(uint32_t);
4771               }
4772           } else {
4773               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4774               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4775               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4776           }
4777        }
4778    
4779        void Instrument::UpdateScriptFileOffsets() {
4780           // own gig format extensions
4781           if (pScriptRefs && pScriptRefs->size() > 0) {
4782               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4783               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4784               const int slotCount = (int) pScriptRefs->size();
4785               const int headerSize = 3 * sizeof(uint32_t);
4786               ckSCSL->SetPos(headerSize);
4787               for (int i = 0; i < slotCount; ++i) {
4788                   uint32_t fileOffset = uint32_t(
4789                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4790                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4791                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4792                   );
4793                   ckSCSL->WriteUint32(&fileOffset);
4794                   // jump over flags entry (containing the bypass flag)
4795                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4796               }
4797           }        
4798      }      }
4799    
4800      /**      /**
# Line 2595  namespace { Line 4805  namespace {
4805       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4806       */       */
4807      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4808          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4809          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4810    
4811          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2639  namespace { Line 4849  namespace {
4849          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4850          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4851          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4852          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4853          // update Region key table for fast lookup          // update Region key table for fast lookup
4854          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4855          // done          // done
# Line 2653  namespace { Line 4863  namespace {
4863          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4864      }      }
4865    
4866        /**
4867         * Move this instrument at the position before @arg dst.
4868         *
4869         * This method can be used to reorder the sequence of instruments in a
4870         * .gig file. This might be helpful especially on large .gig files which
4871         * contain a large number of instruments within the same .gig file. So
4872         * grouping such instruments to similar ones, can help to keep track of them
4873         * when working with such complex .gig files.
4874         *
4875         * When calling this method, this instrument will be removed from in its
4876         * current position in the instruments list and moved to the requested
4877         * target position provided by @param dst. You may also pass NULL as
4878         * argument to this method, in that case this intrument will be moved to the
4879         * very end of the .gig file's instrument list.
4880         *
4881         * You have to call Save() to make the order change persistent to the .gig
4882         * file.
4883         *
4884         * Currently this method is limited to moving the instrument within the same
4885         * .gig file. Trying to move it to another .gig file by calling this method
4886         * will throw an exception.
4887         *
4888         * @param dst - destination instrument at which this instrument will be
4889         *              moved to, or pass NULL for moving to end of list
4890         * @throw gig::Exception if this instrument and target instrument are not
4891         *                       part of the same file
4892         */
4893        void Instrument::MoveTo(Instrument* dst) {
4894            if (dst && GetParent() != dst->GetParent())
4895                throw Exception(
4896                    "gig::Instrument::MoveTo() can only be used for moving within "
4897                    "the same gig file."
4898                );
4899    
4900            File* pFile = (File*) GetParent();
4901    
4902            // move this instrument within the instrument list
4903            {
4904                File::InstrumentList& list = *pFile->pInstruments;
4905    
4906                File::InstrumentList::iterator itFrom =
4907                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4908    
4909                File::InstrumentList::iterator itTo =
4910                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4911    
4912                list.splice(itTo, list, itFrom);
4913            }
4914    
4915            // move the instrument's actual list RIFF chunk appropriately
4916            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4917            lstCkInstruments->MoveSubChunk(
4918                this->pCkInstrument,
4919                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4920            );
4921        }
4922    
4923        /**
4924         * Returns a MIDI rule of the instrument.
4925         *
4926         * The list of MIDI rules, at least in gig v3, always contains at
4927         * most two rules. The second rule can only be the DEF filter
4928         * (which currently isn't supported by libgig).
4929         *
4930         * @param i - MIDI rule number
4931         * @returns   pointer address to MIDI rule number i or NULL if there is none
4932         */
4933        MidiRule* Instrument::GetMidiRule(int i) {
4934            return pMidiRules[i];
4935        }
4936    
4937        /**
4938         * Adds the "controller trigger" MIDI rule to the instrument.
4939         *
4940         * @returns the new MIDI rule
4941         */
4942        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4943            delete pMidiRules[0];
4944            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4945            pMidiRules[0] = r;
4946            pMidiRules[1] = 0;
4947            return r;
4948        }
4949    
4950        /**
4951         * Adds the legato MIDI rule to the instrument.
4952         *
4953         * @returns the new MIDI rule
4954         */
4955        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4956            delete pMidiRules[0];
4957            MidiRuleLegato* r = new MidiRuleLegato;
4958            pMidiRules[0] = r;
4959            pMidiRules[1] = 0;
4960            return r;
4961        }
4962    
4963        /**
4964         * Adds the alternator MIDI rule to the instrument.
4965         *
4966         * @returns the new MIDI rule
4967         */
4968        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4969            delete pMidiRules[0];
4970            MidiRuleAlternator* r = new MidiRuleAlternator;
4971            pMidiRules[0] = r;
4972            pMidiRules[1] = 0;
4973            return r;
4974        }
4975    
4976        /**
4977         * Deletes a MIDI rule from the instrument.
4978         *
4979         * @param i - MIDI rule number
4980         */
4981        void Instrument::DeleteMidiRule(int i) {
4982            delete pMidiRules[i];
4983            pMidiRules[i] = 0;
4984        }
4985    
4986        void Instrument::LoadScripts() {
4987            if (pScriptRefs) return;
4988            pScriptRefs = new std::vector<_ScriptPooolRef>;
4989            if (scriptPoolFileOffsets.empty()) return;
4990            File* pFile = (File*) GetParent();
4991            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4992                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4993                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4994                    ScriptGroup* group = pFile->GetScriptGroup(i);
4995                    for (uint s = 0; group->GetScript(s); ++s) {
4996                        Script* script = group->GetScript(s);
4997                        if (script->pChunk) {
4998                            uint32_t offset = uint32_t(
4999                                script->pChunk->GetFilePos() -
5000                                script->pChunk->GetPos() -
5001                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5002                            );
5003                            if (offset == soughtOffset)
5004                            {
5005                                _ScriptPooolRef ref;
5006                                ref.script = script;
5007                                ref.bypass = scriptPoolFileOffsets[k].bypass;
5008                                pScriptRefs->push_back(ref);
5009                                break;
5010                            }
5011                        }
5012                    }
5013                }
5014            }
5015            // we don't need that anymore
5016            scriptPoolFileOffsets.clear();
5017        }
5018    
5019        /** @brief Get instrument script (gig format extension).
5020         *
5021         * Returns the real-time instrument script of instrument script slot
5022         * @a index.
5023         *
5024         * @note This is an own format extension which did not exist i.e. in the
5025         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5026         * gigedit.
5027         *
5028         * @param index - instrument script slot index
5029         * @returns script or NULL if index is out of bounds
5030         */
5031        Script* Instrument::GetScriptOfSlot(uint index) {
5032            LoadScripts();
5033            if (index >= pScriptRefs->size()) return NULL;
5034            return pScriptRefs->at(index).script;
5035        }
5036    
5037        /** @brief Add new instrument script slot (gig format extension).
5038         *
5039         * Add the given real-time instrument script reference to this instrument,
5040         * which shall be executed by the sampler for for this instrument. The
5041         * script will be added to the end of the script list of this instrument.
5042         * The positions of the scripts in the Instrument's Script list are
5043         * relevant, because they define in which order they shall be executed by
5044         * the sampler. For this reason it is also legal to add the same script
5045         * twice to an instrument, for example you might have a script called
5046         * "MyFilter" which performs an event filter task, and you might have
5047         * another script called "MyNoteTrigger" which triggers new notes, then you
5048         * might for example have the following list of scripts on the instrument:
5049         *
5050         * 1. Script "MyFilter"
5051         * 2. Script "MyNoteTrigger"
5052         * 3. Script "MyFilter"
5053         *
5054         * Which would make sense, because the 2nd script launched new events, which
5055         * you might need to filter as well.
5056         *
5057         * There are two ways to disable / "bypass" scripts. You can either disable
5058         * a script locally for the respective script slot on an instrument (i.e. by
5059         * passing @c false to the 2nd argument of this method, or by calling
5060         * SetScriptBypassed()). Or you can disable a script globally for all slots
5061         * and all instruments by setting Script::Bypass.
5062         *
5063         * @note This is an own format extension which did not exist i.e. in the
5064         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5065         * gigedit.
5066         *
5067         * @param pScript - script that shall be executed for this instrument
5068         * @param bypass  - if enabled, the sampler shall skip executing this
5069         *                  script (in the respective list position)
5070         * @see SetScriptBypassed()
5071         */
5072        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5073            LoadScripts();
5074            _ScriptPooolRef ref = { pScript, bypass };
5075            pScriptRefs->push_back(ref);
5076        }
5077    
5078        /** @brief Flip two script slots with each other (gig format extension).
5079         *
5080         * Swaps the position of the two given scripts in the Instrument's Script
5081         * list. The positions of the scripts in the Instrument's Script list are
5082         * relevant, because they define in which order they shall be executed by
5083         * the sampler.
5084         *
5085         * @note This is an own format extension which did not exist i.e. in the
5086         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5087         * gigedit.
5088         *
5089         * @param index1 - index of the first script slot to swap
5090         * @param index2 - index of the second script slot to swap
5091         */
5092        void Instrument::SwapScriptSlots(uint index1, uint index2) {
5093            LoadScripts();
5094            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5095                return;
5096            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5097            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5098            (*pScriptRefs)[index2] = tmp;
5099        }
5100    
5101        /** @brief Remove script slot.
5102         *
5103         * Removes the script slot with the given slot index.
5104         *
5105         * @param index - index of script slot to remove
5106         */
5107        void Instrument::RemoveScriptSlot(uint index) {
5108            LoadScripts();
5109            if (index >= pScriptRefs->size()) return;
5110            pScriptRefs->erase( pScriptRefs->begin() + index );
5111        }
5112    
5113        /** @brief Remove reference to given Script (gig format extension).
5114         *
5115         * This will remove all script slots on the instrument which are referencing
5116         * the given script.
5117         *
5118         * @note This is an own format extension which did not exist i.e. in the
5119         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5120         * gigedit.
5121         *
5122         * @param pScript - script reference to remove from this instrument
5123         * @see RemoveScriptSlot()
5124         */
5125        void Instrument::RemoveScript(Script* pScript) {
5126            LoadScripts();
5127            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5128                if ((*pScriptRefs)[i].script == pScript) {
5129                    pScriptRefs->erase( pScriptRefs->begin() + i );
5130                }
5131            }
5132        }
5133    
5134        /** @brief Instrument's amount of script slots.
5135         *
5136         * This method returns the amount of script slots this instrument currently
5137         * uses.
5138         *
5139         * A script slot is a reference of a real-time instrument script to be
5140         * executed by the sampler. The scripts will be executed by the sampler in
5141         * sequence of the slots. One (same) script may be referenced multiple
5142         * times in different slots.
5143         *
5144         * @note This is an own format extension which did not exist i.e. in the
5145         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5146         * gigedit.
5147         */
5148        uint Instrument::ScriptSlotCount() const {
5149            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5150        }
5151    
5152        /** @brief Whether script execution shall be skipped.
5153         *
5154         * Defines locally for the Script reference slot in the Instrument's Script
5155         * list, whether the script shall be skipped by the sampler regarding
5156         * execution.
5157         *
5158         * It is also possible to ignore exeuction of the script globally, for all
5159         * slots and for all instruments by setting Script::Bypass.
5160         *
5161         * @note This is an own format extension which did not exist i.e. in the
5162         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5163         * gigedit.
5164         *
5165         * @param index - index of the script slot on this instrument
5166         * @see Script::Bypass
5167         */
5168        bool Instrument::IsScriptSlotBypassed(uint index) {
5169            if (index >= ScriptSlotCount()) return false;
5170            return pScriptRefs ? pScriptRefs->at(index).bypass
5171                               : scriptPoolFileOffsets.at(index).bypass;
5172            
5173        }
5174    
5175        /** @brief Defines whether execution shall be skipped.
5176         *
5177         * You can call this method to define locally whether or whether not the
5178         * given script slot shall be executed by the sampler.
5179         *
5180         * @note This is an own format extension which did not exist i.e. in the
5181         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5182         * gigedit.
5183         *
5184         * @param index - script slot index on this instrument
5185         * @param bBypass - if true, the script slot will be skipped by the sampler
5186         * @see Script::Bypass
5187         */
5188        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5189            if (index >= ScriptSlotCount()) return;
5190            if (pScriptRefs)
5191                pScriptRefs->at(index).bypass = bBypass;
5192            else
5193                scriptPoolFileOffsets.at(index).bypass = bBypass;
5194        }
5195    
5196        /**
5197         * Make a (semi) deep copy of the Instrument object given by @a orig
5198         * and assign it to this object.
5199         *
5200         * Note that all sample pointers referenced by @a orig are simply copied as
5201         * memory address. Thus the respective samples are shared, not duplicated!
5202         *
5203         * @param orig - original Instrument object to be copied from
5204         */
5205        void Instrument::CopyAssign(const Instrument* orig) {
5206            CopyAssign(orig, NULL);
5207        }
5208            
5209        /**
5210         * Make a (semi) deep copy of the Instrument object given by @a orig
5211         * and assign it to this object.
5212         *
5213         * @param orig - original Instrument object to be copied from
5214         * @param mSamples - crosslink map between the foreign file's samples and
5215         *                   this file's samples
5216         */
5217        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5218            // handle base class
5219            // (without copying DLS region stuff)
5220            DLS::Instrument::CopyAssignCore(orig);
5221            
5222            // handle own member variables
5223            Attenuation = orig->Attenuation;
5224            EffectSend = orig->EffectSend;
5225            FineTune = orig->FineTune;
5226            PitchbendRange = orig->PitchbendRange;
5227            PianoReleaseMode = orig->PianoReleaseMode;
5228            DimensionKeyRange = orig->DimensionKeyRange;
5229            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5230            pScriptRefs = orig->pScriptRefs;
5231            
5232            // free old midi rules
5233            for (int i = 0 ; pMidiRules[i] ; i++) {
5234                delete pMidiRules[i];
5235            }
5236            //TODO: MIDI rule copying
5237            pMidiRules[0] = NULL;
5238            
5239            // delete all old regions
5240            while (Regions) DeleteRegion(GetFirstRegion());
5241            // create new regions and copy them from original
5242            {
5243                RegionList::const_iterator it = orig->pRegions->begin();
5244                for (int i = 0; i < orig->Regions; ++i, ++it) {
5245                    Region* dstRgn = AddRegion();
5246                    //NOTE: Region does semi-deep copy !
5247                    dstRgn->CopyAssign(
5248                        static_cast<gig::Region*>(*it),
5249                        mSamples
5250                    );
5251                }
5252            }
5253    
5254            UpdateRegionKeyTable();
5255        }
5256    
5257    
5258    // *************** Group ***************
5259    // *
5260    
5261        /** @brief Constructor.
5262         *
5263         * @param file   - pointer to the gig::File object
5264         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
5265         *                 NULL if this is a new Group
5266         */
5267        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5268            pFile      = file;
5269            pNameChunk = ck3gnm;
5270            ::LoadString(pNameChunk, Name);
5271        }
5272    
5273        Group::~Group() {
5274            // remove the chunk associated with this group (if any)
5275            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5276        }
5277    
5278        /** @brief Update chunks with current group settings.
5279         *
5280         * Apply current Group field values to the respective chunks. You have
5281         * to call File::Save() to make changes persistent.
5282         *
5283         * Usually there is absolutely no need to call this method explicitly.
5284         * It will be called automatically when File::Save() was called.
5285         *
5286         * @param pProgress - callback function for progress notification
5287         */
5288        void Group::UpdateChunks(progress_t* pProgress) {
5289            // make sure <3gri> and <3gnl> list chunks exist
5290            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5291            if (!_3gri) {
5292                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5293                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5294            }
5295            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5296            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5297    
5298            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5299                // v3 has a fixed list of 128 strings, find a free one
5300                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5301                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5302                        pNameChunk = ck;
5303                        break;
5304                    }
5305                }
5306            }
5307    
5308            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5309            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5310        }
5311    
5312        /**
5313         * Returns the first Sample of this Group. You have to call this method
5314         * once before you use GetNextSample().
5315         *
5316         * <b>Notice:</b> this method might block for a long time, in case the
5317         * samples of this .gig file were not scanned yet
5318         *
5319         * @returns  pointer address to first Sample or NULL if there is none
5320         *           applied to this Group
5321         * @see      GetNextSample()
5322         */
5323        Sample* Group::GetFirstSample() {
5324            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5325            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5326                if (pSample->GetGroup() == this) return pSample;
5327            }
5328            return NULL;
5329        }
5330    
5331        /**
5332         * Returns the next Sample of the Group. You have to call
5333         * GetFirstSample() once before you can use this method. By calling this
5334         * method multiple times it iterates through the Samples assigned to
5335         * this Group.
5336         *
5337         * @returns  pointer address to the next Sample of this Group or NULL if
5338         *           end reached
5339         * @see      GetFirstSample()
5340         */
5341        Sample* Group::GetNextSample() {
5342            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5343            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5344                if (pSample->GetGroup() == this) return pSample;
5345            }
5346            return NULL;
5347        }
5348    
5349        /**
5350         * Move Sample given by \a pSample from another Group to this Group.
5351         */
5352        void Group::AddSample(Sample* pSample) {
5353            pSample->pGroup = this;
5354        }
5355    
5356        /**
5357         * Move all members of this group to another group (preferably the 1st
5358         * one except this). This method is called explicitly by
5359         * File::DeleteGroup() thus when a Group was deleted. This code was
5360         * intentionally not placed in the destructor!
5361         */
5362        void Group::MoveAll() {
5363            // get "that" other group first
5364            Group* pOtherGroup = NULL;
5365            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5366                if (pOtherGroup != this) break;
5367            }
5368            if (!pOtherGroup) throw Exception(
5369                "Could not move samples to another group, since there is no "
5370                "other Group. This is a bug, report it!"
5371            );
5372            // now move all samples of this group to the other group
5373            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5374                pOtherGroup->AddSample(pSample);
5375            }
5376        }
5377    
5378    
5379    
5380  // *************** File ***************  // *************** File ***************
5381  // *  // *
5382    
5383        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5384        const DLS::version_t File::VERSION_2 = {
5385            0, 2, 19980628 & 0xffff, 19980628 >> 16
5386        };
5387    
5388        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5389        const DLS::version_t File::VERSION_3 = {
5390            0, 3, 20030331 & 0xffff, 20030331 >> 16
5391        };
5392    
5393        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5394            { CHUNK_ID_IARL, 256 },
5395            { CHUNK_ID_IART, 128 },
5396            { CHUNK_ID_ICMS, 128 },
5397            { CHUNK_ID_ICMT, 1024 },
5398            { CHUNK_ID_ICOP, 128 },
5399            { CHUNK_ID_ICRD, 128 },
5400            { CHUNK_ID_IENG, 128 },
5401            { CHUNK_ID_IGNR, 128 },
5402            { CHUNK_ID_IKEY, 128 },
5403            { CHUNK_ID_IMED, 128 },
5404            { CHUNK_ID_INAM, 128 },
5405            { CHUNK_ID_IPRD, 128 },
5406            { CHUNK_ID_ISBJ, 128 },
5407            { CHUNK_ID_ISFT, 128 },
5408            { CHUNK_ID_ISRC, 128 },
5409            { CHUNK_ID_ISRF, 128 },
5410            { CHUNK_ID_ITCH, 128 },
5411            { 0, 0 }
5412        };
5413    
5414      File::File() : DLS::File() {      File::File() : DLS::File() {
5415            bAutoLoad = true;
5416            *pVersion = VERSION_3;
5417            pGroups = NULL;
5418            pScriptGroups = NULL;
5419            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5420            pInfo->ArchivalLocation = String(256, ' ');
5421    
5422            // add some mandatory chunks to get the file chunks in right
5423            // order (INFO chunk will be moved to first position later)
5424            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5425            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5426            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5427    
5428            GenerateDLSID();
5429      }      }
5430    
5431      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5432            bAutoLoad = true;
5433            pGroups = NULL;
5434            pScriptGroups = NULL;
5435            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5436      }      }
5437    
5438      File::~File() {      File::~File() {
5439          // free extension files          if (pGroups) {
5440          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)              std::list<Group*>::iterator iter = pGroups->begin();
5441              delete *i;              std::list<Group*>::iterator end  = pGroups->end();
5442                while (iter != end) {
5443                    delete *iter;
5444                    ++iter;
5445                }
5446                delete pGroups;
5447            }
5448            if (pScriptGroups) {
5449                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5450                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5451                while (iter != end) {
5452                    delete *iter;
5453                    ++iter;
5454                }
5455                delete pScriptGroups;
5456            }
5457      }      }
5458    
5459      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2682  namespace { Line 5468  namespace {
5468          SamplesIterator++;          SamplesIterator++;
5469          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5470      }      }
5471        
5472        /**
5473         * Returns Sample object of @a index.
5474         *
5475         * @returns sample object or NULL if index is out of bounds
5476         */
5477        Sample* File::GetSample(uint index) {
5478            if (!pSamples) LoadSamples();
5479            if (!pSamples) return NULL;
5480            DLS::File::SampleList::iterator it = pSamples->begin();
5481            for (int i = 0; i < index; ++i) {
5482                ++it;
5483                if (it == pSamples->end()) return NULL;
5484            }
5485            if (it == pSamples->end()) return NULL;
5486            return static_cast<gig::Sample*>( *it );
5487        }
5488    
5489      /** @brief Add a new sample.      /** @brief Add a new sample.
5490       *       *
# Line 2697  namespace { Line 5500  namespace {
5500         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
5501         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5502         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5503    
5504           // add mandatory chunks to get the chunks in right order
5505           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5506           wave->AddSubList(LIST_TYPE_INFO);
5507    
5508         pSamples->push_back(pSample);         pSamples->push_back(pSample);
5509         return pSample;         return pSample;
5510      }      }
5511    
5512      /** @brief Delete a sample.      /** @brief Delete a sample.
5513       *       *
5514       * This will delete the given Sample object from the gig file. You have       * This will delete the given Sample object from the gig file. Any
5515       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
5516         * removed. You have to call Save() to make this persistent to the file.
5517       *       *
5518       * @param pSample - sample to delete       * @param pSample - sample to delete
5519       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2713  namespace { Line 5522  namespace {
5522          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5523          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5524          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5525            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5526          pSamples->erase(iter);          pSamples->erase(iter);
5527          delete pSample;          delete pSample;
5528    
5529            SampleList::iterator tmp = SamplesIterator;
5530            // remove all references to the sample
5531            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5532                 instrument = GetNextInstrument()) {
5533                for (Region* region = instrument->GetFirstRegion() ; region ;
5534                     region = instrument->GetNextRegion()) {
5535    
5536                    if (region->GetSample() == pSample) region->SetSample(NULL);
5537    
5538                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5539                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5540                        if (d->pSample == pSample) d->pSample = NULL;
5541                    }
5542                }
5543            }
5544            SamplesIterator = tmp; // restore iterator
5545      }      }
5546    
5547      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2722  namespace { Line 5549  namespace {
5549      }      }
5550    
5551      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
5552            // Groups must be loaded before samples, because samples will try
5553            // to resolve the group they belong to
5554            if (!pGroups) LoadGroups();
5555    
5556          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
5557    
5558          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
# Line 2731  namespace { Line 5562  namespace {
5562          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5563    
5564          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5565            // (only for old gig files < 2 GB)
5566          int lastFileNo = 0;          int lastFileNo = 0;
5567          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5568              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5569                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5570                }
5571          }          }
5572          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5573          int nameLen = name.length();          int nameLen = (int) name.length();
5574          char suffix[6];          char suffix[6];
5575          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5576    
5577          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5578              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5579              if (wvpl) {              if (wvpl) {
5580                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5581                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5582                  while (wave) {                  while (wave) {
5583                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 2751  namespace { Line 5585  namespace {
5585                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5586                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5587    
5588                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5589                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5590    
5591                          iSampleIndex++;                          iSampleIndex++;
5592                      }                      }
# Line 2801  namespace { Line 5635  namespace {
5635              progress_t subprogress;              progress_t subprogress;
5636              __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
5637              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5638              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5639                    GetFirstSample(&subprogress); // now force all samples to be loaded
5640              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5641    
5642              // instrument loading subtask              // instrument loading subtask
# Line 2834  namespace { Line 5669  namespace {
5669         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
5670         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5671         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5672    
5673           // add mandatory chunks to get the chunks in right order
5674           lstInstr->AddSubList(LIST_TYPE_INFO);
5675           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5676    
5677         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
5678           pInstrument->GenerateDLSID();
5679    
5680           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5681    
5682           // this string is needed for the gig to be loadable in GSt:
5683           pInstrument->pInfo->Software = "Endless Wave";
5684    
5685         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5686         return pInstrument;         return pInstrument;
5687      }      }
5688        
5689        /** @brief Add a duplicate of an existing instrument.
5690         *
5691         * Duplicates the instrument definition given by @a orig and adds it
5692         * to this file. This allows in an instrument editor application to
5693         * easily create variations of an instrument, which will be stored in
5694         * the same .gig file, sharing i.e. the same samples.
5695         *
5696         * Note that all sample pointers referenced by @a orig are simply copied as
5697         * memory address. Thus the respective samples are shared, not duplicated!
5698         *
5699         * You have to call Save() to make this persistent to the file.
5700         *
5701         * @param orig - original instrument to be copied
5702         * @returns duplicated copy of the given instrument
5703         */
5704        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5705            Instrument* instr = AddInstrument();
5706            instr->CopyAssign(orig);
5707            return instr;
5708        }
5709        
5710        /** @brief Add content of another existing file.
5711         *
5712         * Duplicates the samples, groups and instruments of the original file
5713         * given by @a pFile and adds them to @c this File. In case @c this File is
5714         * a new one that you haven't saved before, then you have to call
5715         * SetFileName() before calling AddContentOf(), because this method will
5716         * automatically save this file during operation, which is required for
5717         * writing the sample waveform data by disk streaming.
5718         *
5719         * @param pFile - original file whose's content shall be copied from
5720         */
5721        void File::AddContentOf(File* pFile) {
5722            static int iCallCount = -1;
5723            iCallCount++;
5724            std::map<Group*,Group*> mGroups;
5725            std::map<Sample*,Sample*> mSamples;
5726            
5727            // clone sample groups
5728            for (int i = 0; pFile->GetGroup(i); ++i) {
5729                Group* g = AddGroup();
5730                g->Name =
5731                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5732                mGroups[pFile->GetGroup(i)] = g;
5733            }
5734            
5735            // clone samples (not waveform data here yet)
5736            for (int i = 0; pFile->GetSample(i); ++i) {
5737                Sample* s = AddSample();
5738                s->CopyAssignMeta(pFile->GetSample(i));
5739                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5740                mSamples[pFile->GetSample(i)] = s;
5741            }
5742    
5743            // clone script groups and their scripts
5744            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5745                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5746                ScriptGroup* dg = AddScriptGroup();
5747                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5748                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5749                    Script* ss = sg->GetScript(iScript);
5750                    Script* ds = dg->AddScript();
5751                    ds->CopyAssign(ss);
5752                }
5753            }
5754    
5755            //BUG: For some reason this method only works with this additional
5756            //     Save() call in between here.
5757            //
5758            // Important: The correct one of the 2 Save() methods has to be called
5759            // here, depending on whether the file is completely new or has been
5760            // saved to disk already, otherwise it will result in data corruption.
5761            if (pRIFF->IsNew())
5762                Save(GetFileName());
5763            else
5764                Save();
5765            
5766            // clone instruments
5767            // (passing the crosslink table here for the cloned samples)
5768            for (int i = 0; pFile->GetInstrument(i); ++i) {
5769                Instrument* instr = AddInstrument();
5770                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5771            }
5772            
5773            // Mandatory: file needs to be saved to disk at this point, so this
5774            // file has the correct size and data layout for writing the samples'
5775            // waveform data to disk.
5776            Save();
5777            
5778            // clone samples' waveform data
5779            // (using direct read & write disk streaming)
5780            for (int i = 0; pFile->GetSample(i); ++i) {
5781                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5782            }
5783        }
5784    
5785      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5786       *       *
# Line 2845  namespace { Line 5788  namespace {
5788       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
5789       *       *
5790       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
5791       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
5792       */       */
5793      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
5794          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
# Line 2885  namespace { Line 5828  namespace {
5828          }          }
5829      }      }
5830    
5831        /// Updates the 3crc chunk with the checksum of a sample. The
5832        /// update is done directly to disk, as this method is called
5833        /// after File::Save()
5834        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5835            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5836            if (!_3crc) return;
5837    
5838            // get the index of the sample
5839            int iWaveIndex = GetWaveTableIndexOf(pSample);
5840            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5841    
5842            // write the CRC-32 checksum to disk
5843            _3crc->SetPos(iWaveIndex * 8);
5844            uint32_t one = 1;
5845            _3crc->WriteUint32(&one); // always 1
5846            _3crc->WriteUint32(&crc);
5847        }
5848    
5849        uint32_t File::GetSampleChecksum(Sample* pSample) {
5850            // get the index of the sample
5851            int iWaveIndex = GetWaveTableIndexOf(pSample);
5852            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5853    
5854            return GetSampleChecksumByIndex(iWaveIndex);
5855        }
5856    
5857        uint32_t File::GetSampleChecksumByIndex(int index) {
5858            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5859    
5860            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5861            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5862            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5863            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5864    
5865            // read the CRC-32 checksum directly from disk
5866            size_t pos = index * 8;
5867            if (pos + 8 > _3crc->GetNewSize())
5868                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5869    
5870            uint32_t one = load32(&pData[pos]); // always 1
5871            if (one != 1)
5872                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5873    
5874            return load32(&pData[pos+4]);
5875        }
5876    
5877        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5878            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5879            File::SampleList::iterator iter = pSamples->begin();
5880            File::SampleList::iterator end  = pSamples->end();
5881            for (int index = 0; iter != end; ++iter, ++index)
5882                if (*iter == pSample)
5883                    return index;
5884            return -1;
5885        }
5886    
5887        /**
5888         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5889         * the CRC32 check sums of all samples' raw wave data.
5890         *
5891         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5892         */
5893        bool File::VerifySampleChecksumTable() {
5894            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5895            if (!_3crc) return false;
5896            if (_3crc->GetNewSize() <= 0) return false;
5897            if (_3crc->GetNewSize() % 8) return false;
5898            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5899            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5900    
5901            const file_offset_t n = _3crc->GetNewSize() / 8;
5902    
5903            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5904            if (!pData) return false;
5905    
5906            for (file_offset_t i = 0; i < n; ++i) {
5907                uint32_t one = pData[i*2];
5908                if (one != 1) return false;
5909            }
5910    
5911            return true;
5912        }
5913    
5914        /**
5915         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5916         * file's checksum table with those new checksums. This might usually
5917         * just be necessary if the checksum table was damaged.
5918         *
5919         * @e IMPORTANT: The current implementation of this method only works
5920         * with files that have not been modified since it was loaded, because
5921         * it expects that no externally caused file structure changes are
5922         * required!
5923         *
5924         * Due to the expectation above, this method is currently protected
5925         * and actually only used by the command line tool "gigdump" yet.
5926         *
5927         * @returns true if Save() is required to be called after this call,
5928         *          false if no further action is required
5929         */
5930        bool File::RebuildSampleChecksumTable() {
5931            // make sure sample chunks were scanned
5932            if (!pSamples) GetFirstSample();
5933    
5934            bool bRequiresSave = false;
5935    
5936            // make sure "3CRC" chunk exists with required size
5937            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5938            if (!_3crc) {
5939                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5940                // the order of einf and 3crc is not the same in v2 and v3
5941                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5942                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5943                bRequiresSave = true;
5944            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5945                _3crc->Resize(pSamples->size() * 8);
5946                bRequiresSave = true;
5947            }
5948    
5949            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5950                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5951                {
5952                    File::SampleList::iterator iter = pSamples->begin();
5953                    File::SampleList::iterator end  = pSamples->end();
5954                    for (; iter != end; ++iter) {
5955                        gig::Sample* pSample = (gig::Sample*) *iter;
5956                        int index = GetWaveTableIndexOf(pSample);
5957                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5958                        pData[index*2]   = 1; // always 1
5959                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5960                    }
5961                }
5962            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5963                // make sure file is in write mode
5964                pRIFF->SetMode(RIFF::stream_mode_read_write);
5965                {
5966                    File::SampleList::iterator iter = pSamples->begin();
5967                    File::SampleList::iterator end  = pSamples->end();
5968                    for (; iter != end; ++iter) {
5969                        gig::Sample* pSample = (gig::Sample*) *iter;
5970                        int index = GetWaveTableIndexOf(pSample);
5971                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5972                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5973                        SetSampleChecksum(pSample, pSample->crc);
5974                    }
5975                }
5976            }
5977    
5978            return bRequiresSave;
5979        }
5980    
5981        Group* File::GetFirstGroup() {
5982            if (!pGroups) LoadGroups();
5983            // there must always be at least one group
5984            GroupsIterator = pGroups->begin();
5985            return *GroupsIterator;
5986        }
5987    
5988        Group* File::GetNextGroup() {
5989            if (!pGroups) return NULL;
5990            ++GroupsIterator;
5991            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5992        }
5993    
5994        /**
5995         * Returns the group with the given index.
5996         *
5997         * @param index - number of the sought group (0..n)
5998         * @returns sought group or NULL if there's no such group
5999         */
6000        Group* File::GetGroup(uint index) {
6001            if (!pGroups) LoadGroups();
6002            GroupsIterator = pGroups->begin();
6003            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
6004                if (i == index) return *GroupsIterator;
6005                ++GroupsIterator;
6006            }
6007            return NULL;
6008        }
6009    
6010        /**
6011         * Returns the group with the given group name.
6012         *
6013         * Note: group names don't have to be unique in the gig format! So there
6014         * can be multiple groups with the same name. This method will simply
6015         * return the first group found with the given name.
6016         *
6017         * @param name - name of the sought group
6018         * @returns sought group or NULL if there's no group with that name
6019         */
6020        Group* File::GetGroup(String name) {
6021            if (!pGroups) LoadGroups();
6022            GroupsIterator = pGroups->begin();
6023            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
6024                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
6025            return NULL;
6026        }
6027    
6028        Group* File::AddGroup() {
6029            if (!pGroups) LoadGroups();
6030            // there must always be at least one group
6031            __ensureMandatoryChunksExist();
6032            Group* pGroup = new Group(this, NULL);
6033            pGroups->push_back(pGroup);
6034            return pGroup;
6035        }
6036    
6037        /** @brief Delete a group and its samples.
6038         *
6039         * This will delete the given Group object and all the samples that
6040         * belong to this group from the gig file. You have to call Save() to
6041         * make this persistent to the file.
6042         *
6043         * @param pGroup - group to delete
6044         * @throws gig::Exception if given group could not be found
6045         */
6046        void File::DeleteGroup(Group* pGroup) {
6047            if (!pGroups) LoadGroups();
6048            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
6049            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
6050            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
6051            // delete all members of this group
6052            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
6053                DeleteSample(pSample);
6054            }
6055            // now delete this group object
6056            pGroups->erase(iter);
6057            delete pGroup;
6058        }
6059    
6060        /** @brief Delete a group.
6061         *
6062         * This will delete the given Group object from the gig file. All the
6063         * samples that belong to this group will not be deleted, but instead
6064         * be moved to another group. You have to call Save() to make this
6065         * persistent to the file.
6066         *
6067         * @param pGroup - group to delete
6068         * @throws gig::Exception if given group could not be found
6069         */
6070        void File::DeleteGroupOnly(Group* pGroup) {
6071            if (!pGroups) LoadGroups();
6072            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
6073            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
6074            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
6075            // move all members of this group to another group
6076            pGroup->MoveAll();
6077            pGroups->erase(iter);
6078            delete pGroup;
6079        }
6080    
6081        void File::LoadGroups() {
6082            if (!pGroups) pGroups = new std::list<Group*>;
6083            // try to read defined groups from file
6084            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6085            if (lst3gri) {
6086                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
6087                if (lst3gnl) {
6088                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
6089                    while (ck) {
6090                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
6091                            if (pVersion && pVersion->major == 3 &&
6092                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
6093    
6094                            pGroups->push_back(new Group(this, ck));
6095                        }
6096                        ck = lst3gnl->GetNextSubChunk();
6097                    }
6098                }
6099            }
6100            // if there were no group(s), create at least the mandatory default group
6101            if (!pGroups->size()) {
6102                Group* pGroup = new Group(this, NULL);
6103                pGroup->Name = "Default Group";
6104                pGroups->push_back(pGroup);
6105            }
6106        }
6107    
6108        /** @brief Get instrument script group (by index).
6109         *
6110         * Returns the real-time instrument script group with the given index.
6111         *
6112         * @param index - number of the sought group (0..n)
6113         * @returns sought script group or NULL if there's no such group
6114         */
6115        ScriptGroup* File::GetScriptGroup(uint index) {
6116            if (!pScriptGroups) LoadScriptGroups();
6117            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6118            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6119                if (i == index) return *it;
6120            return NULL;
6121        }
6122    
6123        /** @brief Get instrument script group (by name).
6124         *
6125         * Returns the first real-time instrument script group found with the given
6126         * group name. Note that group names may not necessarily be unique.
6127         *
6128         * @param name - name of the sought script group
6129         * @returns sought script group or NULL if there's no such group
6130         */
6131        ScriptGroup* File::GetScriptGroup(const String& name) {
6132            if (!pScriptGroups) LoadScriptGroups();
6133            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6134            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6135                if ((*it)->Name == name) return *it;
6136            return NULL;
6137        }
6138    
6139        /** @brief Add new instrument script group.
6140         *
6141         * Adds a new, empty real-time instrument script group to the file.
6142         *
6143         * You have to call Save() to make this persistent to the file.
6144         *
6145         * @return new empty script group
6146         */
6147        ScriptGroup* File::AddScriptGroup() {
6148            if (!pScriptGroups) LoadScriptGroups();
6149            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6150            pScriptGroups->push_back(pScriptGroup);
6151            return pScriptGroup;
6152        }
6153    
6154        /** @brief Delete an instrument script group.
6155         *
6156         * This will delete the given real-time instrument script group and all its
6157         * instrument scripts it contains. References inside instruments that are
6158         * using the deleted scripts will be removed from the respective instruments
6159         * accordingly.
6160         *
6161         * You have to call Save() to make this persistent to the file.
6162         *
6163         * @param pScriptGroup - script group to delete
6164         * @throws gig::Exception if given script group could not be found
6165         */
6166        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6167            if (!pScriptGroups) LoadScriptGroups();
6168            std::list<ScriptGroup*>::iterator iter =
6169                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6170            if (iter == pScriptGroups->end())
6171                throw gig::Exception("Could not delete script group, could not find given script group");
6172            pScriptGroups->erase(iter);
6173            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6174                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6175            if (pScriptGroup->pList)
6176                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6177            delete pScriptGroup;
6178        }
6179    
6180        void File::LoadScriptGroups() {
6181            if (pScriptGroups) return;
6182            pScriptGroups = new std::list<ScriptGroup*>;
6183            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6184            if (lstLS) {
6185                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6186                     lst = lstLS->GetNextSubList())
6187                {
6188                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6189                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6190                    }
6191                }
6192            }
6193        }
6194    
6195        /**
6196         * Apply all the gig file's current instruments, samples, groups and settings
6197         * to the respective RIFF chunks. You have to call Save() to make changes
6198         * persistent.
6199         *
6200         * Usually there is absolutely no need to call this method explicitly.
6201         * It will be called automatically when File::Save() was called.
6202         *
6203         * @param pProgress - callback function for progress notification
6204         * @throws Exception - on errors
6205         */
6206        void File::UpdateChunks(progress_t* pProgress) {
6207            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6208    
6209            // update own gig format extension chunks
6210            // (not part of the GigaStudio 4 format)
6211            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6212            if (!lst3LS) {
6213                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6214            }
6215            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6216            // location of <3LS > is irrelevant, however it should be located
6217            // before  the actual wave data
6218            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6219            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6220    
6221            // This must be performed before writing the chunks for instruments,
6222            // because the instruments' script slots will write the file offsets
6223            // of the respective instrument script chunk as reference.
6224            if (pScriptGroups) {
6225                // Update instrument script (group) chunks.
6226                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6227                     it != pScriptGroups->end(); ++it)
6228                {
6229                    (*it)->UpdateChunks(pProgress);
6230                }
6231            }
6232    
6233            // in case no libgig custom format data was added, then remove the
6234            // custom "3LS " chunk again
6235            if (!lst3LS->CountSubChunks()) {
6236                pRIFF->DeleteSubChunk(lst3LS);
6237                lst3LS = NULL;
6238            }
6239    
6240            // first update base class's chunks
6241            DLS::File::UpdateChunks(pProgress);
6242    
6243            if (newFile) {
6244                // INFO was added by Resource::UpdateChunks - make sure it
6245                // is placed first in file
6246                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
6247                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
6248                if (first != info) {
6249                    pRIFF->MoveSubChunk(info, first);
6250                }
6251            }
6252    
6253            // update group's chunks
6254            if (pGroups) {
6255                // make sure '3gri' and '3gnl' list chunks exist
6256                // (before updating the Group chunks)
6257                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6258                if (!_3gri) {
6259                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6260                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6261                }
6262                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6263                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6264    
6265                // v3: make sure the file has 128 3gnm chunks
6266                // (before updating the Group chunks)
6267                if (pVersion && pVersion->major == 3) {
6268                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6269                    for (int i = 0 ; i < 128 ; i++) {
6270                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6271                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6272                    }
6273                }
6274    
6275                std::list<Group*>::iterator iter = pGroups->begin();
6276                std::list<Group*>::iterator end  = pGroups->end();
6277                for (; iter != end; ++iter) {
6278                    (*iter)->UpdateChunks(pProgress);
6279                }
6280            }
6281    
6282            // update einf chunk
6283    
6284            // The einf chunk contains statistics about the gig file, such
6285            // as the number of regions and samples used by each
6286            // instrument. It is divided in equally sized parts, where the
6287            // first part contains information about the whole gig file,
6288            // and the rest of the parts map to each instrument in the
6289            // file.
6290            //
6291            // At the end of each part there is a bit map of each sample
6292            // in the file, where a set bit means that the sample is used
6293            // by the file/instrument.
6294            //
6295            // Note that there are several fields with unknown use. These
6296            // are set to zero.
6297    
6298            int sublen = int(pSamples->size() / 8 + 49);
6299            int einfSize = (Instruments + 1) * sublen;
6300    
6301            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6302            if (einf) {
6303                if (einf->GetSize() != einfSize) {
6304                    einf->Resize(einfSize);
6305                    memset(einf->LoadChunkData(), 0, einfSize);
6306                }
6307            } else if (newFile) {
6308                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
6309            }
6310            if (einf) {
6311                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
6312    
6313                std::map<gig::Sample*,int> sampleMap;
6314                int sampleIdx = 0;
6315                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
6316                    sampleMap[pSample] = sampleIdx++;
6317                }
6318    
6319                int totnbusedsamples = 0;
6320                int totnbusedchannels = 0;
6321                int totnbregions = 0;
6322                int totnbdimregions = 0;
6323                int totnbloops = 0;
6324                int instrumentIdx = 0;
6325    
6326                memset(&pData[48], 0, sublen - 48);
6327    
6328                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
6329                     instrument = GetNextInstrument()) {
6330                    int nbusedsamples = 0;
6331                    int nbusedchannels = 0;
6332                    int nbdimregions = 0;
6333                    int nbloops = 0;
6334    
6335                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
6336    
6337                    for (Region* region = instrument->GetFirstRegion() ; region ;
6338                         region = instrument->GetNextRegion()) {
6339                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
6340                            gig::DimensionRegion *d = region->pDimensionRegions[i];
6341                            if (d->pSample) {
6342                                int sampleIdx = sampleMap[d->pSample];
6343                                int byte = 48 + sampleIdx / 8;
6344                                int bit = 1 << (sampleIdx & 7);
6345                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6346                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6347                                    nbusedsamples++;
6348                                    nbusedchannels += d->pSample->Channels;
6349    
6350                                    if ((pData[byte] & bit) == 0) {
6351                                        pData[byte] |= bit;
6352                                        totnbusedsamples++;
6353                                        totnbusedchannels += d->pSample->Channels;
6354                                    }
6355                                }
6356                            }
6357                            if (d->SampleLoops) nbloops++;
6358                        }
6359                        nbdimregions += region->DimensionRegions;
6360                    }
6361                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6362                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6363                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6364                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6365                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6366                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6367                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6368                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6369                    // next 8 bytes unknown
6370                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6371                    store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6372                    // next 4 bytes unknown
6373    
6374                    totnbregions += instrument->Regions;
6375                    totnbdimregions += nbdimregions;
6376                    totnbloops += nbloops;
6377                    instrumentIdx++;
6378                }
6379                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6380                // store32(&pData[0], sublen);
6381                store32(&pData[4], totnbusedchannels);
6382                store32(&pData[8], totnbusedsamples);
6383                store32(&pData[12], Instruments);
6384                store32(&pData[16], totnbregions);
6385                store32(&pData[20], totnbdimregions);
6386                store32(&pData[24], totnbloops);
6387                // next 8 bytes unknown
6388                // next 4 bytes unknown, not always 0
6389                store32(&pData[40], (uint32_t) pSamples->size());
6390                // next 4 bytes unknown
6391            }
6392    
6393            // update 3crc chunk
6394    
6395            // The 3crc chunk contains CRC-32 checksums for the
6396            // samples. When saving a gig file to disk, we first update the 3CRC
6397            // chunk here (in RAM) with the old crc values which we read from the
6398            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6399            // member variable). This step is required, because samples might have
6400            // been deleted by the user since the file was opened, which in turn
6401            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6402            // If a sample was conciously modified by the user (that is if
6403            // Sample::Write() was called later on) then Sample::Write() will just
6404            // update the respective individual checksum(s) directly on disk and
6405            // leaves all other sample checksums untouched.
6406    
6407            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6408            if (_3crc) {
6409                _3crc->Resize(pSamples->size() * 8);
6410            } else /*if (newFile)*/ {
6411                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6412                // the order of einf and 3crc is not the same in v2 and v3
6413                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6414            }
6415            { // must be performed in RAM here ...
6416                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6417                if (pData) {
6418                    File::SampleList::iterator iter = pSamples->begin();
6419                    File::SampleList::iterator end  = pSamples->end();
6420                    for (int index = 0; iter != end; ++iter, ++index) {
6421                        gig::Sample* pSample = (gig::Sample*) *iter;
6422                        pData[index*2]   = 1; // always 1
6423                        pData[index*2+1] = pSample->crc;
6424                    }
6425                }
6426            }
6427        }
6428        
6429        void File::UpdateFileOffsets() {
6430            DLS::File::UpdateFileOffsets();
6431    
6432            for (Instrument* instrument = GetFirstInstrument(); instrument;
6433                 instrument = GetNextInstrument())
6434            {
6435                instrument->UpdateScriptFileOffsets();
6436            }
6437        }
6438    
6439        /**
6440         * Enable / disable automatic loading. By default this properyt is
6441         * enabled and all informations are loaded automatically. However
6442         * loading all Regions, DimensionRegions and especially samples might
6443         * take a long time for large .gig files, and sometimes one might only
6444         * be interested in retrieving very superficial informations like the
6445         * amount of instruments and their names. In this case one might disable
6446         * automatic loading to avoid very slow response times.
6447         *
6448         * @e CAUTION: by disabling this property many pointers (i.e. sample
6449         * references) and informations will have invalid or even undefined
6450         * data! This feature is currently only intended for retrieving very
6451         * superficial informations in a very fast way. Don't use it to retrieve
6452         * details like synthesis informations or even to modify .gig files!
6453         */
6454        void File::SetAutoLoad(bool b) {
6455            bAutoLoad = b;
6456        }
6457    
6458        /**
6459         * Returns whether automatic loading is enabled.
6460         * @see SetAutoLoad()
6461         */
6462        bool File::GetAutoLoad() {
6463            return bAutoLoad;
6464        }
6465    
6466    
6467    
6468  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.823  
changed lines
  Added in v.3140

  ViewVC Help
Powered by ViewVC