/[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 858 by persson, Sat May 6 11:29:29 2006 UTC revision 2484 by schoenebeck, Tue Dec 31 00:13:20 2013 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-2013 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 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    
# Line 111  namespace { Line 112  namespace {
112          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
113      }      }
114    
115        inline void store24(unsigned char* pDst, int x)
116        {
117            pDst[0] = x;
118            pDst[1] = x >> 8;
119            pDst[2] = x >> 16;
120        }
121    
122      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
123                        int srcStep, int dstStep,                        int srcStep, int dstStep,
124                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
# Line 150  namespace { Line 158  namespace {
158      }      }
159    
160      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
161                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
162                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
163                        unsigned long copysamples, int truncatedBits)                        unsigned long copysamples, int truncatedBits)
164      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
165          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
166    
167  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
168          y    = get24(params);                   \          y    = get24(params);                   \
# Line 173  namespace { Line 178  namespace {
178    
179  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
180          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
181          *pDst = y >> shift;                     \          store24(pDst, y << truncatedBits);      \
182          pDst += dstStep          pDst += dstStep
183    
184          switch (compressionmode) {          switch (compressionmode) {
185              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
186                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
187                  while (copysamples) {                  while (copysamples) {
188                      *pDst = get24(pSrc) >> shift;                      store24(pDst, get24(pSrc) << truncatedBits);
189                      pDst += dstStep;                      pDst += dstStep;
190                      pSrc += 3;                      pSrc += 3;
191                      copysamples--;                      copysamples--;
# Line 250  namespace { Line 255  namespace {
255  }  }
256    
257    
258    
259    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
260    // *
261    
262        static uint32_t* __initCRCTable() {
263            static uint32_t res[256];
264    
265            for (int i = 0 ; i < 256 ; i++) {
266                uint32_t c = i;
267                for (int j = 0 ; j < 8 ; j++) {
268                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269                }
270                res[i] = c;
271            }
272            return res;
273        }
274    
275        static const uint32_t* __CRCTable = __initCRCTable();
276    
277        /**
278         * Initialize a CRC variable.
279         *
280         * @param crc - variable to be initialized
281         */
282        inline static void __resetCRC(uint32_t& crc) {
283            crc = 0xffffffff;
284        }
285    
286        /**
287         * Used to calculate checksums of the sample data in a gig file. The
288         * checksums are stored in the 3crc chunk of the gig file and
289         * automatically updated when a sample is written with Sample::Write().
290         *
291         * One should call __resetCRC() to initialize the CRC variable to be
292         * used before calling this function the first time.
293         *
294         * After initializing the CRC variable one can call this function
295         * arbitrary times, i.e. to split the overall CRC calculation into
296         * steps.
297         *
298         * Once the whole data was processed by __calculateCRC(), one should
299         * call __encodeCRC() to get the final CRC result.
300         *
301         * @param buf     - pointer to data the CRC shall be calculated of
302         * @param bufSize - size of the data to be processed
303         * @param crc     - variable the CRC sum shall be stored to
304         */
305        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306            for (int i = 0 ; i < bufSize ; i++) {
307                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308            }
309        }
310    
311        /**
312         * Returns the final CRC result.
313         *
314         * @param crc - variable previously passed to __calculateCRC()
315         */
316        inline static uint32_t __encodeCRC(const uint32_t& crc) {
317            return crc ^ 0xffffffff;
318        }
319    
320    
321    
322    // *************** Other Internal functions  ***************
323    // *
324    
325        static split_type_t __resolveSplitType(dimension_t dimension) {
326            return (
327                dimension == dimension_layer ||
328                dimension == dimension_samplechannel ||
329                dimension == dimension_releasetrigger ||
330                dimension == dimension_keyboard ||
331                dimension == dimension_roundrobin ||
332                dimension == dimension_random ||
333                dimension == dimension_smartmidi ||
334                dimension == dimension_roundrobinkeyboard
335            ) ? split_type_bit : split_type_normal;
336        }
337    
338        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
339            return (dimension_definition.split_type == split_type_normal)
340            ? int(128.0 / dimension_definition.zones) : 0;
341        }
342    
343    
344    
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
# Line 275  namespace { Line 367  namespace {
367       *                         is located, 0 otherwise       *                         is located, 0 otherwise
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, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
370            static const DLS::Info::string_length_t fixedStringLengths[] = {
371                { CHUNK_ID_INAM, 64 },
372                { 0, 0 }
373            };
374            pInfo->SetFixedStringLengths(fixedStringLengths);
375          Instances++;          Instances++;
376          FileNo = fileNo;          FileNo = fileNo;
377    
378            __resetCRC(crc);
379    
380          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381          if (pCk3gix) {          if (pCk3gix) {
382              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
383                pGroup = pFile->GetGroup(iSampleGroup);
384          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
385              // use default value(s)              // by default assigned to that mandatory "Default Group"
386              SampleGroup = 0;              pGroup = pFile->GetGroup(0);
387          }          }
388    
389          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 307  namespace { Line 407  namespace {
407              // use default values              // use default values
408              Manufacturer  = 0;              Manufacturer  = 0;
409              Product       = 0;              Product       = 0;
410              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
411              MIDIUnityNote = 64;              MIDIUnityNote = 60;
412              FineTune      = 0;              FineTune      = 0;
413                SMPTEFormat   = smpte_format_no_offset;
414              SMPTEOffset   = 0;              SMPTEOffset   = 0;
415              Loops         = 0;              Loops         = 0;
416              LoopID        = 0;              LoopID        = 0;
417                LoopType      = loop_type_normal;
418              LoopStart     = 0;              LoopStart     = 0;
419              LoopEnd       = 0;              LoopEnd       = 0;
420              LoopFraction  = 0;              LoopFraction  = 0;
# Line 348  namespace { Line 450  namespace {
450          }          }
451          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
452    
453          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
454        }
455    
456        /**
457         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518            }
519            pOrig->SetPos(restorePos);
520            delete [] buf;
521      }      }
522    
523      /**      /**
# Line 358  namespace { Line 527  namespace {
527       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
528       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
529       *       *
530       * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
531       *                        was provided yet       *                        was provided yet
532       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
533       */       */
# Line 368  namespace { Line 537  namespace {
537    
538          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
539          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
540          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
541                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
542                memset(pCkSmpl->LoadChunkData(), 0, 60);
543            }
544          // update 'smpl' chunk          // update 'smpl' chunk
545          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
546          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
547          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
548          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
549          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
550          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
551          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
552          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
553          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
554          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
555    
556          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
557    
558          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
559          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
560          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
561          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
562          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
563          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
564    
565          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
566          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
567          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
568            // determine appropriate sample group index (to be stored in chunk)
569            uint16_t iSampleGroup = 0; // 0 refers to default sample group
570            File* pFile = static_cast<File*>(pParent);
571            if (pFile->pGroups) {
572                std::list<Group*>::iterator iter = pFile->pGroups->begin();
573                std::list<Group*>::iterator end  = pFile->pGroups->end();
574                for (int i = 0; iter != end; i++, iter++) {
575                    if (*iter == pGroup) {
576                        iSampleGroup = i;
577                        break; // found
578                    }
579                }
580            }
581          // update '3gix' chunk          // update '3gix' chunk
582          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
583          memcpy(&pData[0], &SampleGroup, 2);          store16(&pData[0], iSampleGroup);
584    
585            // if the library user toggled the "Compressed" attribute from true to
586            // false, then the EWAV chunk associated with compressed samples needs
587            // to be deleted
588            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
589            if (ewav && !Compressed) {
590                pWaveList->DeleteSubChunk(ewav);
591            }
592      }      }
593    
594      /// 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).
# Line 559  namespace { Line 752  namespace {
752          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
753          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
754          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
755            SetPos(0); // reset read position to begin of sample
756          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
757          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
758          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 596  namespace { Line 790  namespace {
790          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
791          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
792          RAMCache.Size   = 0;          RAMCache.Size   = 0;
793            RAMCache.NullExtensionSize = 0;
794      }      }
795    
796      /** @brief Resize sample.      /** @brief Resize sample.
# Line 616  namespace { Line 811  namespace {
811       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
812       * current sample's boundary!       * current sample's boundary!
813       *       *
814       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
815       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
816       * other formats will fail!       * other formats will fail!
817       *       *
818       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
819       *                   greater than zero)       *                   greater than zero)
820       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
821       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
822       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
823       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 688  namespace { Line 883  namespace {
883      /**      /**
884       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
885       */       */
886      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
887          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
888          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
889      }      }
# Line 722  namespace { Line 917  namespace {
917       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
918       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
919       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
920         * @param pDimRgn          dimension region with looping information
921       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
922       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
923       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
924       */       */
925      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
926                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
927          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
928          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
929    
930          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
931    
932          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
933    
934              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
935                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
936    
937                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
938                      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  
939    
940                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
941                              // determine the end position within the loop first,                          do {
942                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
943                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
944                              // backward playback  
945                                if (!pPlaybackState->reverse) { // forward playback
946                              unsigned long swapareastart       = totalreadsamples;                                  do {
947                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
948                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
949                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
950                                        totalreadsamples += readsamples;
951                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
952                                            pPlaybackState->reverse = true;
953                              // read samples for backward playback                                          break;
954                              do {                                      }
955                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
956                                  samplestoreadinloop -= readsamples;                              }
957                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
958    
959                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
960                                    // determine the end position within the loop first,
961                                    // read forward from that 'end' and finally after
962                                    // reading, swap all sample frames so it reflects
963                                    // backward playback
964    
965                                    unsigned long swapareastart       = totalreadsamples;
966                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
967                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
968                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
969    
970                                    SetPos(reverseplaybackend);
971    
972                                    // read samples for backward playback
973                                    do {
974                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
975                                        samplestoreadinloop -= readsamples;
976                                        samplestoread       -= readsamples;
977                                        totalreadsamples    += readsamples;
978                                    } while (samplestoreadinloop && readsamples);
979    
980                                    SetPos(reverseplaybackend); // pretend we really read backwards
981    
982                                    if (reverseplaybackend == loop.LoopStart) {
983                                        pPlaybackState->loop_cycles_left--;
984                                        pPlaybackState->reverse = false;
985                                    }
986    
987                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
988                                  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!
989                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
990                              }                              }
991                            } while (samplestoread && readsamples);
992                            break;
993                        }
994    
995                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
996                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
997                          }                          if (!pPlaybackState->reverse) do {
998                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
999                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1000                  }                              samplestoread    -= readsamples;
1001                                totalreadsamples += readsamples;
1002                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
1003                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
1004                      if (!pPlaybackState->reverse) do {                                  break;
1005                          samplestoloopend  = this->LoopEnd - GetPos();                              }
1006                          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);  
1007    
1008                      if (!samplestoread) break;                          if (!samplestoread) break;
1009    
1010                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
1011                      // determine the end position within the loop first,                          // determine the end position within the loop first,
1012                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
1013                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1014                      // backward playback                          // backward playback
1015    
1016                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
1017                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
1018                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1019                                                                                : samplestoread;                                                                                    : samplestoread;
1020                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1021    
1022                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1023    
1024                      // read samples for backward playback                          // read samples for backward playback
1025                      do {                          do {
1026                          // 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
1027                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1028                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
1029                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1030                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1031                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1032                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1033                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1034                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1035                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1036                          }                              }
1037                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1038    
1039                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1040    
1041                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1042                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1043                      break;                          break;
1044                  }                      }
1045    
1046                  default: case loop_type_normal: {                      default: case loop_type_normal: {
1047                      do {                          do {
1048                          // 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
1049                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1050                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
1051                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1052                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1053                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1054                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1055                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1056                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1057                          }                              }
1058                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1059                      break;                          break;
1060                        }
1061                  }                  }
1062              }              }
1063          }          }
# Line 884  namespace { Line 1087  namespace {
1087       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
1088       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
1089       *       *
1090         * For 16 bit samples, the data in the buffer will be int16_t
1091         * (using native endianness). For 24 bit, the buffer will
1092         * contain three bytes per sample, little-endian.
1093         *
1094       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1095       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1096       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 894  namespace { Line 1101  namespace {
1101          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1102          if (!Compressed) {          if (!Compressed) {
1103              if (BitDepth == 24) {              if (BitDepth == 24) {
1104                  // 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);  
                 }  
1105              }              }
1106              else { // 16 bit              else { // 16 bit
1107                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 944  namespace { Line 1131  namespace {
1131    
1132              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1133              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1134                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1135              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1136    
1137              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 1025  namespace { Line 1213  namespace {
1213                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1214                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1215    
1216                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1217                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1218                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1219                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1220                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1221                          }                          }
1222                          else { // Mono                          else { // Mono
1223                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1224                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1225                              pDst += copysamples;                              pDst24 += copysamples * 3;
1226                          }                          }
1227                      }                      }
1228                      else { // 16 bit                      else { // 16 bit
# Line 1088  namespace { Line 1276  namespace {
1276       *       *
1277       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1278       *       *
1279         * For 16 bit samples, the data in the source buffer should be
1280         * int16_t (using native endianness). For 24 bit, the buffer
1281         * should contain three bytes per sample, little-endian.
1282         *
1283       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1284       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1285       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1096  namespace { Line 1288  namespace {
1288       */       */
1289      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1290          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)");
1291          return DLS::Sample::Write(pBuffer, SampleCount);  
1292            // if this is the first write in this sample, reset the
1293            // checksum calculator
1294            if (pCkData->GetPos() == 0) {
1295                __resetCRC(crc);
1296            }
1297            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1298            unsigned long res;
1299            if (BitDepth == 24) {
1300                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1301            } else { // 16 bit
1302                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1303                                    : pCkData->Write(pBuffer, SampleCount, 2);
1304            }
1305            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1306    
1307            // if this is the last write, update the checksum chunk in the
1308            // file
1309            if (pCkData->GetPos() == pCkData->GetSize()) {
1310                File* pFile = static_cast<File*>(GetParent());
1311                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1312            }
1313            return res;
1314      }      }
1315    
1316      /**      /**
# Line 1141  namespace { Line 1355  namespace {
1355          }          }
1356      }      }
1357    
1358        /**
1359         * Returns pointer to the Group this Sample belongs to. In the .gig
1360         * format a sample always belongs to one group. If it wasn't explicitly
1361         * assigned to a certain group, it will be automatically assigned to a
1362         * default group.
1363         *
1364         * @returns Sample's Group (never NULL)
1365         */
1366        Group* Sample::GetGroup() const {
1367            return pGroup;
1368        }
1369    
1370      Sample::~Sample() {      Sample::~Sample() {
1371          Instances--;          Instances--;
1372          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1160  namespace { Line 1386  namespace {
1386      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1387      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1388    
1389      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1390          Instances++;          Instances++;
1391    
1392          pSample = NULL;          pSample = NULL;
1393            pRegion = pParent;
1394    
1395            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1396            else memset(&Crossfade, 0, 4);
1397    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1398          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1399    
1400          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1401          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1402              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1403              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1404              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1405              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1279  namespace { Line 1508  namespace {
1508                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1509              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1510              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1511                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1512              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1513              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1514              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1315  namespace { Line 1544  namespace {
1544                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1545                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1546              }              }
1547                if (_3ewa->RemainingBytes() >= 8) {
1548                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1549                } else {
1550                    memset(DimensionUpperLimits, 0, 8);
1551                }
1552          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1553              // use default values              // use default values
1554              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1324  namespace { Line 1558  namespace {
1558              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1559              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1560              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1561              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1562              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1563              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1564              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1565              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1566              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1341  namespace { Line 1575  namespace {
1575              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1576              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1577              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1578              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1579              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1580              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1581              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1582              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1583              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1584              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1585              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1586              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1587              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1588              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1589              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1590              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1591              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1592              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1395  namespace { Line 1629  namespace {
1629              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1630              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1631              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1632                memset(DimensionUpperLimits, 127, 8);
1633          }          }
1634    
1635          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1636                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1637                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1638    
1639          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1640          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1641                                        ReleaseVelocityResponseDepth
1642                                    );
1643    
1644            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1645                                                          VCFVelocityDynamicRange,
1646                                                          VCFVelocityScale,
1647                                                          VCFCutoffController);
1648    
1649          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1650          // velocity response curves for release time are not used even          VelocityTable = 0;
1651          // if specified, instead another curve is chosen.      }
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_nonlinear;  
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1652    
1653          curveType = VCFVelocityCurve;      /*
1654          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1655         * another DimensionRegion
1656         */
1657        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1658            Instances++;
1659            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1660            *this = src; // default memberwise shallow copy of all parameters
1661            pParentList = _3ewl; // restore the chunk pointer
1662    
1663            // deep copy of owned structures
1664            if (src.VelocityTable) {
1665                VelocityTable = new uint8_t[128];
1666                for (int k = 0 ; k < 128 ; k++)
1667                    VelocityTable[k] = src.VelocityTable[k];
1668            }
1669            if (src.pSampleLoops) {
1670                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1671                for (int k = 0 ; k < src.SampleLoops ; k++)
1672                    pSampleLoops[k] = src.pSampleLoops[k];
1673            }
1674        }
1675        
1676        /**
1677         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1678         * and assign it to this object.
1679         *
1680         * Note that all sample pointers referenced by @a orig are simply copied as
1681         * memory address. Thus the respective samples are shared, not duplicated!
1682         *
1683         * @param orig - original DimensionRegion object to be copied from
1684         */
1685        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1686            CopyAssign(orig, NULL);
1687        }
1688    
1689          // even stranger GSt: two of the velocity response curves for      /**
1690          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1691          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1692          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1693              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1694              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1695              depth = 5;       *                   this file's samples
1696         */
1697        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1698            // delete all allocated data first
1699            if (VelocityTable) delete [] VelocityTable;
1700            if (pSampleLoops) delete [] pSampleLoops;
1701            
1702            // backup parent list pointer
1703            RIFF::List* p = pParentList;
1704            
1705            gig::Sample* pOriginalSample = pSample;
1706            gig::Region* pOriginalRegion = pRegion;
1707            
1708            //NOTE: copy code copied from assignment constructor above, see comment there as well
1709            
1710            *this = *orig; // default memberwise shallow copy of all parameters
1711            pParentList = p; // restore the chunk pointer
1712            
1713            // only take the raw sample reference & parent region reference if the
1714            // two DimensionRegion objects are part of the same file
1715            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1716                pRegion = pOriginalRegion;
1717                pSample = pOriginalSample;
1718            }
1719            
1720            if (mSamples && mSamples->count(orig->pSample)) {
1721                pSample = mSamples->find(orig->pSample)->second;
1722            }
1723    
1724            // deep copy of owned structures
1725            if (orig->VelocityTable) {
1726                VelocityTable = new uint8_t[128];
1727                for (int k = 0 ; k < 128 ; k++)
1728                    VelocityTable[k] = orig->VelocityTable[k];
1729            }
1730            if (orig->pSampleLoops) {
1731                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1732                for (int k = 0 ; k < orig->SampleLoops ; k++)
1733                    pSampleLoops[k] = orig->pSampleLoops[k];
1734          }          }
1735          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1736    
1737        /**
1738         * Updates the respective member variable and updates @c SampleAttenuation
1739         * which depends on this value.
1740         */
1741        void DimensionRegion::SetGain(int32_t gain) {
1742            DLS::Sampler::SetGain(gain);
1743          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1744      }      }
1745    
1746      /**      /**
# Line 1443  namespace { Line 1754  namespace {
1754          // first update base class's chunk          // first update base class's chunk
1755          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1756    
1757            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1758            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1759            pData[12] = Crossfade.in_start;
1760            pData[13] = Crossfade.in_end;
1761            pData[14] = Crossfade.out_start;
1762            pData[15] = Crossfade.out_end;
1763    
1764          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1765          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1766          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1767          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1768                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1769                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1770            }
1771            pData = (uint8_t*) _3ewa->LoadChunkData();
1772    
1773          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1774    
1775          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t chunksize = _3ewa->GetNewSize();
1776          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1777    
1778          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1779          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1780    
1781          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1782          memcpy(&pData[4], &eg3attack, 4);          store32(&pData[8], eg3attack);
1783    
1784          // next 2 bytes unknown          // next 2 bytes unknown
1785    
1786          memcpy(&pData[10], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1787    
1788          // next 2 bytes unknown          // next 2 bytes unknown
1789    
1790          memcpy(&pData[14], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1791    
1792          // next 2 bytes unknown          // next 2 bytes unknown
1793    
1794          memcpy(&pData[18], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1795    
1796          // next 2 bytes unknown          // next 2 bytes unknown
1797    
1798          memcpy(&pData[22], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1799    
1800          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1801          memcpy(&pData[24], &eg1attack, 4);          store32(&pData[28], eg1attack);
1802    
1803          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1804          memcpy(&pData[28], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1805    
1806          // next 2 bytes unknown          // next 2 bytes unknown
1807    
1808          memcpy(&pData[34], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1809    
1810          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1811          memcpy(&pData[36], &eg1release, 4);          store32(&pData[40], eg1release);
1812    
1813          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1814          memcpy(&pData[40], &eg1ctl, 1);          pData[44] = eg1ctl;
1815    
1816          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1817              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1818              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1819              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1820              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1821          memcpy(&pData[41], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1822    
1823          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1824          memcpy(&pData[42], &eg2ctl, 1);          pData[46] = eg2ctl;
1825    
1826          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1827              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1828              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1829              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1830              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1831          memcpy(&pData[43], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1832    
1833          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1834          memcpy(&pData[44], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1835    
1836          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1837          memcpy(&pData[48], &eg2attack, 4);          store32(&pData[52], eg2attack);
1838    
1839          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1840          memcpy(&pData[52], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1841    
1842          // next 2 bytes unknown          // next 2 bytes unknown
1843    
1844          memcpy(&pData[58], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1845    
1846          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1847          memcpy(&pData[60], &eg2release, 4);          store32(&pData[64], eg2release);
1848    
1849          // next 2 bytes unknown          // next 2 bytes unknown
1850    
1851          memcpy(&pData[66], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1852    
1853          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1854          memcpy(&pData[68], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1855    
1856          // next 2 bytes unknown          // next 2 bytes unknown
1857    
1858          memcpy(&pData[72], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1859    
1860          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);
1861          memcpy(&pData[74], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1862    
1863          // next 2 bytes unknown          // next 2 bytes unknown
1864    
1865          memcpy(&pData[80], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1866    
1867          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);
1868          memcpy(&pData[82], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1869    
1870          // next 2 bytes unknown          // next 2 bytes unknown
1871    
1872          memcpy(&pData[88], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1873    
1874          {          {
1875              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 1565  namespace { Line 1887  namespace {
1887                  default:                  default:
1888                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1889              }              }
1890              memcpy(&pData[90], &velocityresponse, 1);              pData[96] = velocityresponse;
1891          }          }
1892    
1893          {          {
# Line 1584  namespace { Line 1906  namespace {
1906                  default:                  default:
1907                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1908              }              }
1909              memcpy(&pData[91], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1910          }          }
1911    
1912          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1913    
1914          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1915    
1916          // next 4 bytes unknown          // next 4 bytes unknown
1917    
1918          memcpy(&pData[98], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1919    
1920          // next 2 bytes unknown          // next 2 bytes unknown
1921    
# Line 1612  namespace { Line 1934  namespace {
1934                  default:                  default:
1935                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1936              }              }
1937              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1938          }          }
1939    
1940          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
1941          memcpy(&pData[103], &pan, 1);          pData[109] = pan;
1942    
1943          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1944          memcpy(&pData[104], &selfmask, 1);          pData[110] = selfmask;
1945    
1946          // next byte unknown          // next byte unknown
1947    
# Line 1628  namespace { Line 1950  namespace {
1950              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1951              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1952              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1953              memcpy(&pData[106], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1954          }          }
1955    
1956          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1957          memcpy(&pData[107], &attenctl, 1);          pData[113] = attenctl;
1958    
1959          {          {
1960              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1961              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1962              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1963              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1964              memcpy(&pData[108], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1965          }          }
1966    
1967          {          {
# Line 1648  namespace { Line 1970  namespace {
1970              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1971              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1972                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1973              memcpy(&pData[109], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1974          }          }
1975    
1976          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1977                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1978          memcpy(&pData[110], &eg3depth, 1);          store16(&pData[116], eg3depth);
1979    
1980          // next 2 bytes unknown          // next 2 bytes unknown
1981    
1982          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1983          memcpy(&pData[113], &channeloffset, 1);          pData[120] = channeloffset;
1984    
1985          {          {
1986              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1987              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1988              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1989              memcpy(&pData[114], &regoptions, 1);              pData[121] = regoptions;
1990          }          }
1991    
1992          // next 2 bytes unknown          // next 2 bytes unknown
1993    
1994          memcpy(&pData[117], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1995    
1996          // next 3 bytes unknown          // next 3 bytes unknown
1997    
1998          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1999    
2000          // next 2 bytes unknown          // next 2 bytes unknown
2001    
2002          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2003          memcpy(&pData[124], &eg1hold, 1);          pData[131] = eg1hold;
2004    
2005          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2006                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2007          memcpy(&pData[125], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2008    
2009          memcpy(&pData[126], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2010    
2011          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2012                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2013          memcpy(&pData[127], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2014    
2015          // next byte unknown          // next byte unknown
2016    
2017          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2018                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2019          memcpy(&pData[129], &vcfresonance, 1);          pData[136] = vcfresonance;
2020    
2021          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2022                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2023          memcpy(&pData[130], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2024    
2025          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2026                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2027          memcpy(&pData[131], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2028    
2029          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2030          memcpy(&pData[132], &vcftype, 1);          pData[139] = vcftype;
2031    
2032            if (chunksize >= 148) {
2033                memcpy(&pData[140], DimensionUpperLimits, 8);
2034            }
2035        }
2036    
2037        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2038            curve_type_t curveType = releaseVelocityResponseCurve;
2039            uint8_t depth = releaseVelocityResponseDepth;
2040            // this models a strange behaviour or bug in GSt: two of the
2041            // velocity response curves for release time are not used even
2042            // if specified, instead another curve is chosen.
2043            if ((curveType == curve_type_nonlinear && depth == 0) ||
2044                (curveType == curve_type_special   && depth == 4)) {
2045                curveType = curve_type_nonlinear;
2046                depth = 3;
2047            }
2048            return GetVelocityTable(curveType, depth, 0);
2049        }
2050    
2051        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2052                                                        uint8_t vcfVelocityDynamicRange,
2053                                                        uint8_t vcfVelocityScale,
2054                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2055        {
2056            curve_type_t curveType = vcfVelocityCurve;
2057            uint8_t depth = vcfVelocityDynamicRange;
2058            // even stranger GSt: two of the velocity response curves for
2059            // filter cutoff are not used, instead another special curve
2060            // is chosen. This curve is not used anywhere else.
2061            if ((curveType == curve_type_nonlinear && depth == 0) ||
2062                (curveType == curve_type_special   && depth == 4)) {
2063                curveType = curve_type_special;
2064                depth = 5;
2065            }
2066            return GetVelocityTable(curveType, depth,
2067                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2068                                        ? vcfVelocityScale : 0);
2069      }      }
2070    
2071      // 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 1723  namespace { Line 2083  namespace {
2083          return table;          return table;
2084      }      }
2085    
2086        Region* DimensionRegion::GetParent() const {
2087            return pRegion;
2088        }
2089    
2090      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2091          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2092          switch (EncodedController) {          switch (EncodedController) {
# Line 1930  namespace { Line 2294  namespace {
2294                      default:                      default:
2295                          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");
2296                  }                  }
2297                    break;
2298              default:              default:
2299                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2300          }          }
# Line 1975  namespace { Line 2340  namespace {
2340          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2341      }      }
2342    
2343        /**
2344         * Updates the respective member variable and the lookup table / cache
2345         * that depends on this value.
2346         */
2347        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2348            pVelocityAttenuationTable =
2349                GetVelocityTable(
2350                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2351                );
2352            VelocityResponseCurve = curve;
2353        }
2354    
2355        /**
2356         * Updates the respective member variable and the lookup table / cache
2357         * that depends on this value.
2358         */
2359        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2360            pVelocityAttenuationTable =
2361                GetVelocityTable(
2362                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2363                );
2364            VelocityResponseDepth = depth;
2365        }
2366    
2367        /**
2368         * Updates the respective member variable and the lookup table / cache
2369         * that depends on this value.
2370         */
2371        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2372            pVelocityAttenuationTable =
2373                GetVelocityTable(
2374                    VelocityResponseCurve, VelocityResponseDepth, scaling
2375                );
2376            VelocityResponseCurveScaling = scaling;
2377        }
2378    
2379        /**
2380         * Updates the respective member variable and the lookup table / cache
2381         * that depends on this value.
2382         */
2383        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2384            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2385            ReleaseVelocityResponseCurve = curve;
2386        }
2387    
2388        /**
2389         * Updates the respective member variable and the lookup table / cache
2390         * that depends on this value.
2391         */
2392        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2393            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2394            ReleaseVelocityResponseDepth = depth;
2395        }
2396    
2397        /**
2398         * Updates the respective member variable and the lookup table / cache
2399         * that depends on this value.
2400         */
2401        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2402            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2403            VCFCutoffController = controller;
2404        }
2405    
2406        /**
2407         * Updates the respective member variable and the lookup table / cache
2408         * that depends on this value.
2409         */
2410        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2411            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2412            VCFVelocityCurve = curve;
2413        }
2414    
2415        /**
2416         * Updates the respective member variable and the lookup table / cache
2417         * that depends on this value.
2418         */
2419        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2420            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2421            VCFVelocityDynamicRange = range;
2422        }
2423    
2424        /**
2425         * Updates the respective member variable and the lookup table / cache
2426         * that depends on this value.
2427         */
2428        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2429            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2430            VCFVelocityScale = scaling;
2431        }
2432    
2433      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) {
2434    
2435          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2058  namespace { Line 2513  namespace {
2513    
2514          // Actual Loading          // Actual Loading
2515    
2516            if (!file->GetAutoLoad()) return;
2517    
2518          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2519    
2520          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2066  namespace { Line 2523  namespace {
2523              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2524                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2525                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2526                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2527                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2528                  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)
2529                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2530                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2080  namespace { Line 2537  namespace {
2537                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2538                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2539                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2540                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2541                                                             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].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2542                      Dimensions++;                      Dimensions++;
2543    
2544                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2108  namespace { Line 2558  namespace {
2558              else              else
2559                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2560    
2561              // load sample references              // load sample references (if auto loading is enabled)
2562              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2563                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2564                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2565                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2566                    }
2567                    GetSample(); // load global region sample reference
2568                }
2569            } else {
2570                DimensionRegions = 0;
2571                for (int i = 0 ; i < 8 ; i++) {
2572                    pDimensionDefinitions[i].dimension  = dimension_none;
2573                    pDimensionDefinitions[i].bits       = 0;
2574                    pDimensionDefinitions[i].zones      = 0;
2575              }              }
2576          }          }
2577    
# Line 2120  namespace { Line 2580  namespace {
2580              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2581              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2582              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2583              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2584              DimensionRegions = 1;              DimensionRegions = 1;
2585          }          }
2586      }      }
# Line 2135  namespace { Line 2595  namespace {
2595       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
2596       */       */
2597      void Region::UpdateChunks() {      void Region::UpdateChunks() {
2598            // in the gig format we don't care about the Region's sample reference
2599            // but we still have to provide some existing one to not corrupt the
2600            // file, so to avoid the latter we simply always assign the sample of
2601            // the first dimension region of this region
2602            pSample = pDimensionRegions[0]->pSample;
2603    
2604          // first update base class's chunks          // first update base class's chunks
2605          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2606    
# Line 2144  namespace { Line 2610  namespace {
2610          }          }
2611    
2612          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2613          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2614          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
2615            const int iMaxDimensionRegions = version3 ? 256 : 32;
2616    
2617          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
2618          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2619          if (!_3lnk) {          if (!_3lnk) {
2620              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
2621              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2622                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2623    
2624                // move 3prg to last position
2625                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2626          }          }
2627    
2628          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2629          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2630            store32(&pData[0], DimensionRegions);
2631            int shift = 0;
2632          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2633              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2634              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2635              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2636              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2637              // next 3 bytes unknown              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2638                // next 3 bytes unknown, always zero?
2639    
2640                shift += pDimensionDefinitions[i].bits;
2641          }          }
2642    
2643          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
2644          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
2645          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2646              int iWaveIndex = -1;              int iWaveIndex = -1;
2647              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2178  namespace { Line 2654  namespace {
2654                          break;                          break;
2655                      }                      }
2656                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
2657              }              }
2658              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2659          }          }
2660      }      }
2661    
# Line 2191  namespace { Line 2666  namespace {
2666              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2667              while (_3ewl) {              while (_3ewl) {
2668                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2669                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2670                      dimensionRegionNr++;                      dimensionRegionNr++;
2671                  }                  }
2672                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2200  namespace { Line 2675  namespace {
2675          }          }
2676      }      }
2677    
2678        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2679            // update KeyRange struct and make sure regions are in correct order
2680            DLS::Region::SetKeyRange(Low, High);
2681            // update Region key table for fast lookup
2682            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2683        }
2684    
2685      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
2686          // get velocity dimension's index          // get velocity dimension's index
2687          int veldim = -1;          int veldim = -1;
# Line 2220  namespace { Line 2702  namespace {
2702          int dim[8] = { 0 };          int dim[8] = { 0 };
2703          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
2704    
2705              if (pDimensionRegions[i]->VelocityUpperLimit) {              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2706                    pDimensionRegions[i]->VelocityUpperLimit) {
2707                  // create the velocity table                  // create the velocity table
2708                  uint8_t* table = pDimensionRegions[i]->VelocityTable;                  uint8_t* table = pDimensionRegions[i]->VelocityTable;
2709                  if (!table) {                  if (!table) {
# Line 2229  namespace { Line 2712  namespace {
2712                  }                  }
2713                  int tableidx = 0;                  int tableidx = 0;
2714                  int velocityZone = 0;                  int velocityZone = 0;
2715                  for (int k = i ; k < end ; k += step) {                  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2716                      DimensionRegion *d = pDimensionRegions[k];                      for (int k = i ; k < end ; k += step) {
2717                      for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;                          DimensionRegion *d = pDimensionRegions[k];
2718                      velocityZone++;                          for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2719                            velocityZone++;
2720                        }
2721                    } else { // gig2
2722                        for (int k = i ; k < end ; k += step) {
2723                            DimensionRegion *d = pDimensionRegions[k];
2724                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2725                            velocityZone++;
2726                        }
2727                  }                  }
2728              } else {              } else {
2729                  if (pDimensionRegions[i]->VelocityTable) {                  if (pDimensionRegions[i]->VelocityTable) {
# Line 2296  namespace { Line 2787  namespace {
2787              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2788                  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");
2789    
2790            // pos is where the new dimension should be placed, normally
2791            // last in list, except for the samplechannel dimension which
2792            // has to be first in list
2793            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2794            int bitpos = 0;
2795            for (int i = 0 ; i < pos ; i++)
2796                bitpos += pDimensionDefinitions[i].bits;
2797    
2798            // make room for the new dimension
2799            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2800            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2801                for (int j = Dimensions ; j > pos ; j--) {
2802                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2803                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2804                }
2805            }
2806    
2807          // assign definition of new dimension          // assign definition of new dimension
2808          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
2809    
2810          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
2811          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
2812              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
2813              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
2814              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
2815              DimensionRegions++;  
2816            // create new dimension region(s) for this new dimension, and make
2817            // sure that the dimension regions are placed correctly in both the
2818            // RIFF list and the pDimensionRegions array
2819            RIFF::Chunk* moveTo = NULL;
2820            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2821            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2822                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2823                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2824                }
2825                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2826                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2827                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2828                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2829                        // create a new dimension region and copy all parameter values from
2830                        // an existing dimension region
2831                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2832                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2833    
2834                        DimensionRegions++;
2835                    }
2836                }
2837                moveTo = pDimensionRegions[i]->pParentList;
2838            }
2839    
2840            // initialize the upper limits for this dimension
2841            int mask = (1 << bitpos) - 1;
2842            for (int z = 0 ; z < pDimDef->zones ; z++) {
2843                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2844                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2845                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2846                                      (z << bitpos) |
2847                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2848                }
2849          }          }
2850    
2851          Dimensions++;          Dimensions++;
# Line 2347  namespace { Line 2888  namespace {
2888          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
2889              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
2890    
2891            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2892    
2893          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
2894          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
2895          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2355  namespace { Line 2898  namespace {
2898                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2899                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
2900                                      iLowerBit;                                      iLowerBit;
2901    
2902                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2903                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
2904                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
2905                      DimensionRegions--;                      DimensionRegions--;
# Line 2375  namespace { Line 2920  namespace {
2920              }              }
2921          }          }
2922    
2923            // remove the this dimension from the upper limits arrays
2924            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2925                DimensionRegion* d = pDimensionRegions[j];
2926                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2927                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2928                }
2929                d->DimensionUpperLimits[Dimensions - 1] = 127;
2930            }
2931    
2932          // 'remove' dimension definition          // 'remove' dimension definition
2933          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2934              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2427  namespace { Line 2981  namespace {
2981              } else {              } else {
2982                  switch (pDimensionDefinitions[i].split_type) {                  switch (pDimensionDefinitions[i].split_type) {
2983                      case split_type_normal:                      case split_type_normal:
2984                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2985                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2986                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2987                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2988                                }
2989                            } else {
2990                                // gig2: evenly sized zones
2991                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2992                            }
2993                          break;                          break;
2994                      case split_type_bit: // the value is already the sought dimension bit number                      case split_type_bit: // the value is already the sought dimension bit number
2995                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
# Line 2441  namespace { Line 3003  namespace {
3003          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3004          if (veldim != -1) {          if (veldim != -1) {
3005              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3006              if (dimreg->VelocityUpperLimit) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3007                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim]];
3008              else // normal split type              else // normal split type
3009                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
# Line 2489  namespace { Line 3051  namespace {
3051      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3052          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3053          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3054            if (!file->pWavePoolTable) return NULL;
3055          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3056          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3057          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
3058          while (sample) {          while (sample) {
3059              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
3060                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3061              sample = file->GetNextSample();              sample = file->GetNextSample();
3062          }          }
3063          return NULL;          return NULL;
3064      }      }
3065        
3066        /**
3067         * Make a (semi) deep copy of the Region object given by @a orig
3068         * and assign it to this object.
3069         *
3070         * Note that all sample pointers referenced by @a orig are simply copied as
3071         * memory address. Thus the respective samples are shared, not duplicated!
3072         *
3073         * @param orig - original Region object to be copied from
3074         */
3075        void Region::CopyAssign(const Region* orig) {
3076            CopyAssign(orig, NULL);
3077        }
3078        
3079        /**
3080         * Make a (semi) deep copy of the Region object given by @a orig and
3081         * assign it to this object
3082         *
3083         * @param mSamples - crosslink map between the foreign file's samples and
3084         *                   this file's samples
3085         */
3086        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3087            // handle base classes
3088            DLS::Region::CopyAssign(orig);
3089            
3090            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3091                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3092            }
3093            
3094            // handle own member variables
3095            for (int i = Dimensions - 1; i >= 0; --i) {
3096                DeleteDimension(&pDimensionDefinitions[i]);
3097            }
3098            Layers = 0; // just to be sure
3099            for (int i = 0; i < orig->Dimensions; i++) {
3100                // we need to copy the dim definition here, to avoid the compiler
3101                // complaining about const-ness issue
3102                dimension_def_t def = orig->pDimensionDefinitions[i];
3103                AddDimension(&def);
3104            }
3105            for (int i = 0; i < 256; i++) {
3106                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3107                    pDimensionRegions[i]->CopyAssign(
3108                        orig->pDimensionRegions[i],
3109                        mSamples
3110                    );
3111                }
3112            }
3113            Layers = orig->Layers;
3114        }
3115    
3116    
3117    // *************** MidiRule ***************
3118    // *
3119    
3120        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3121            _3ewg->SetPos(36);
3122            Triggers = _3ewg->ReadUint8();
3123            _3ewg->SetPos(40);
3124            ControllerNumber = _3ewg->ReadUint8();
3125            _3ewg->SetPos(46);
3126            for (int i = 0 ; i < Triggers ; i++) {
3127                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3128                pTriggers[i].Descending = _3ewg->ReadUint8();
3129                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3130                pTriggers[i].Key = _3ewg->ReadUint8();
3131                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3132                pTriggers[i].Velocity = _3ewg->ReadUint8();
3133                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3134                _3ewg->ReadUint8();
3135            }
3136        }
3137    
3138        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3139            ControllerNumber(0),
3140            Triggers(0) {
3141        }
3142    
3143        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3144            pData[32] = 4;
3145            pData[33] = 16;
3146            pData[36] = Triggers;
3147            pData[40] = ControllerNumber;
3148            for (int i = 0 ; i < Triggers ; i++) {
3149                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3150                pData[47 + i * 8] = pTriggers[i].Descending;
3151                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3152                pData[49 + i * 8] = pTriggers[i].Key;
3153                pData[50 + i * 8] = pTriggers[i].NoteOff;
3154                pData[51 + i * 8] = pTriggers[i].Velocity;
3155                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3156            }
3157        }
3158    
3159        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3160            _3ewg->SetPos(36);
3161            LegatoSamples = _3ewg->ReadUint8(); // always 12
3162            _3ewg->SetPos(40);
3163            BypassUseController = _3ewg->ReadUint8();
3164            BypassKey = _3ewg->ReadUint8();
3165            BypassController = _3ewg->ReadUint8();
3166            ThresholdTime = _3ewg->ReadUint16();
3167            _3ewg->ReadInt16();
3168            ReleaseTime = _3ewg->ReadUint16();
3169            _3ewg->ReadInt16();
3170            KeyRange.low = _3ewg->ReadUint8();
3171            KeyRange.high = _3ewg->ReadUint8();
3172            _3ewg->SetPos(64);
3173            ReleaseTriggerKey = _3ewg->ReadUint8();
3174            AltSustain1Key = _3ewg->ReadUint8();
3175            AltSustain2Key = _3ewg->ReadUint8();
3176        }
3177    
3178        MidiRuleLegato::MidiRuleLegato() :
3179            LegatoSamples(12),
3180            BypassUseController(false),
3181            BypassKey(0),
3182            BypassController(1),
3183            ThresholdTime(20),
3184            ReleaseTime(20),
3185            ReleaseTriggerKey(0),
3186            AltSustain1Key(0),
3187            AltSustain2Key(0)
3188        {
3189            KeyRange.low = KeyRange.high = 0;
3190        }
3191    
3192        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3193            pData[32] = 0;
3194            pData[33] = 16;
3195            pData[36] = LegatoSamples;
3196            pData[40] = BypassUseController;
3197            pData[41] = BypassKey;
3198            pData[42] = BypassController;
3199            store16(&pData[43], ThresholdTime);
3200            store16(&pData[47], ReleaseTime);
3201            pData[51] = KeyRange.low;
3202            pData[52] = KeyRange.high;
3203            pData[64] = ReleaseTriggerKey;
3204            pData[65] = AltSustain1Key;
3205            pData[66] = AltSustain2Key;
3206        }
3207    
3208        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3209            _3ewg->SetPos(36);
3210            Articulations = _3ewg->ReadUint8();
3211            int flags = _3ewg->ReadUint8();
3212            Polyphonic = flags & 8;
3213            Chained = flags & 4;
3214            Selector = (flags & 2) ? selector_controller :
3215                (flags & 1) ? selector_key_switch : selector_none;
3216            Patterns = _3ewg->ReadUint8();
3217            _3ewg->ReadUint8(); // chosen row
3218            _3ewg->ReadUint8(); // unknown
3219            _3ewg->ReadUint8(); // unknown
3220            _3ewg->ReadUint8(); // unknown
3221            KeySwitchRange.low = _3ewg->ReadUint8();
3222            KeySwitchRange.high = _3ewg->ReadUint8();
3223            Controller = _3ewg->ReadUint8();
3224            PlayRange.low = _3ewg->ReadUint8();
3225            PlayRange.high = _3ewg->ReadUint8();
3226    
3227            int n = std::min(int(Articulations), 32);
3228            for (int i = 0 ; i < n ; i++) {
3229                _3ewg->ReadString(pArticulations[i], 32);
3230            }
3231            _3ewg->SetPos(1072);
3232            n = std::min(int(Patterns), 32);
3233            for (int i = 0 ; i < n ; i++) {
3234                _3ewg->ReadString(pPatterns[i].Name, 16);
3235                pPatterns[i].Size = _3ewg->ReadUint8();
3236                _3ewg->Read(&pPatterns[i][0], 1, 32);
3237            }
3238        }
3239    
3240        MidiRuleAlternator::MidiRuleAlternator() :
3241            Articulations(0),
3242            Patterns(0),
3243            Selector(selector_none),
3244            Controller(0),
3245            Polyphonic(false),
3246            Chained(false)
3247        {
3248            PlayRange.low = PlayRange.high = 0;
3249            KeySwitchRange.low = KeySwitchRange.high = 0;
3250        }
3251    
3252        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3253            pData[32] = 3;
3254            pData[33] = 16;
3255            pData[36] = Articulations;
3256            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3257                (Selector == selector_controller ? 2 :
3258                 (Selector == selector_key_switch ? 1 : 0));
3259            pData[38] = Patterns;
3260    
3261            pData[43] = KeySwitchRange.low;
3262            pData[44] = KeySwitchRange.high;
3263            pData[45] = Controller;
3264            pData[46] = PlayRange.low;
3265            pData[47] = PlayRange.high;
3266    
3267            char* str = reinterpret_cast<char*>(pData);
3268            int pos = 48;
3269            int n = std::min(int(Articulations), 32);
3270            for (int i = 0 ; i < n ; i++, pos += 32) {
3271                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3272            }
3273    
3274            pos = 1072;
3275            n = std::min(int(Patterns), 32);
3276            for (int i = 0 ; i < n ; i++, pos += 49) {
3277                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3278                pData[pos + 16] = pPatterns[i].Size;
3279                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3280            }
3281        }
3282    
3283  // *************** Instrument ***************  // *************** Instrument ***************
3284  // *  // *
3285    
3286      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) {
3287            static const DLS::Info::string_length_t fixedStringLengths[] = {
3288                { CHUNK_ID_INAM, 64 },
3289                { CHUNK_ID_ISFT, 12 },
3290                { 0, 0 }
3291            };
3292            pInfo->SetFixedStringLengths(fixedStringLengths);
3293    
3294          // Initialization          // Initialization
3295          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3296            EffectSend = 0;
3297            Attenuation = 0;
3298            FineTune = 0;
3299            PitchbendRange = 0;
3300            PianoReleaseMode = false;
3301            DimensionKeyRange.low = 0;
3302            DimensionKeyRange.high = 0;
3303            pMidiRules = new MidiRule*[3];
3304            pMidiRules[0] = NULL;
3305    
3306          // Loading          // Loading
3307          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2522  namespace { Line 3316  namespace {
3316                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3317                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3318                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3319    
3320                    if (_3ewg->GetSize() > 32) {
3321                        // read MIDI rules
3322                        int i = 0;
3323                        _3ewg->SetPos(32);
3324                        uint8_t id1 = _3ewg->ReadUint8();
3325                        uint8_t id2 = _3ewg->ReadUint8();
3326    
3327                        if (id2 == 16) {
3328                            if (id1 == 4) {
3329                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3330                            } else if (id1 == 0) {
3331                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3332                            } else if (id1 == 3) {
3333                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3334                            } else {
3335                                pMidiRules[i++] = new MidiRuleUnknown;
3336                            }
3337                        }
3338                        else if (id1 != 0 || id2 != 0) {
3339                            pMidiRules[i++] = new MidiRuleUnknown;
3340                        }
3341                        //TODO: all the other types of rules
3342    
3343                        pMidiRules[i] = NULL;
3344                    }
3345              }              }
3346          }          }
3347    
3348          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3349          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3350          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3351              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3352              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3353                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3354                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3355                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3356                            pRegions->push_back(new Region(this, rgn));
3357                        }
3358                        rgn = lrgn->GetNextSubList();
3359                  }                  }
3360                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3361                    UpdateRegionKeyTable();
3362              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3363          }          }
3364    
3365          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3366      }      }
3367    
3368      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3369            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3370          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3371          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3372          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2555  namespace { Line 3378  namespace {
3378      }      }
3379    
3380      Instrument::~Instrument() {      Instrument::~Instrument() {
3381            for (int i = 0 ; pMidiRules[i] ; i++) {
3382                delete pMidiRules[i];
3383            }
3384            delete[] pMidiRules;
3385      }      }
3386    
3387      /**      /**
# Line 2583  namespace { Line 3410  namespace {
3410          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3411          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3412          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3413          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3414                File* pFile = (File*) GetParent();
3415    
3416                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3417                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3418                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3419                memset(_3ewg->LoadChunkData(), 0, size);
3420            }
3421          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3422          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3423          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
3424          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
3425          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
3426          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
3427          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3428                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3429          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
3430          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
3431    
3432            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3433                pData[32] = 0;
3434                pData[33] = 0;
3435            } else {
3436                for (int i = 0 ; pMidiRules[i] ; i++) {
3437                    pMidiRules[i]->UpdateChunks(pData);
3438                }
3439            }
3440      }      }
3441    
3442      /**      /**
# Line 2604  namespace { Line 3447  namespace {
3447       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3448       */       */
3449      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3450          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3451          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3452    
3453          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2662  namespace { Line 3505  namespace {
3505          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3506      }      }
3507    
3508        /**
3509         * Returns a MIDI rule of the instrument.
3510         *
3511         * The list of MIDI rules, at least in gig v3, always contains at
3512         * most two rules. The second rule can only be the DEF filter
3513         * (which currently isn't supported by libgig).
3514         *
3515         * @param i - MIDI rule number
3516         * @returns   pointer address to MIDI rule number i or NULL if there is none
3517         */
3518        MidiRule* Instrument::GetMidiRule(int i) {
3519            return pMidiRules[i];
3520        }
3521    
3522        /**
3523         * Adds the "controller trigger" MIDI rule to the instrument.
3524         *
3525         * @returns the new MIDI rule
3526         */
3527        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3528            delete pMidiRules[0];
3529            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3530            pMidiRules[0] = r;
3531            pMidiRules[1] = 0;
3532            return r;
3533        }
3534    
3535        /**
3536         * Adds the legato MIDI rule to the instrument.
3537         *
3538         * @returns the new MIDI rule
3539         */
3540        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3541            delete pMidiRules[0];
3542            MidiRuleLegato* r = new MidiRuleLegato;
3543            pMidiRules[0] = r;
3544            pMidiRules[1] = 0;
3545            return r;
3546        }
3547    
3548        /**
3549         * Adds the alternator MIDI rule to the instrument.
3550         *
3551         * @returns the new MIDI rule
3552         */
3553        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3554            delete pMidiRules[0];
3555            MidiRuleAlternator* r = new MidiRuleAlternator;
3556            pMidiRules[0] = r;
3557            pMidiRules[1] = 0;
3558            return r;
3559        }
3560    
3561        /**
3562         * Deletes a MIDI rule from the instrument.
3563         *
3564         * @param i - MIDI rule number
3565         */
3566        void Instrument::DeleteMidiRule(int i) {
3567            delete pMidiRules[i];
3568            pMidiRules[i] = 0;
3569        }
3570    
3571        /**
3572         * Make a (semi) deep copy of the Instrument object given by @a orig
3573         * and assign it to this object.
3574         *
3575         * Note that all sample pointers referenced by @a orig are simply copied as
3576         * memory address. Thus the respective samples are shared, not duplicated!
3577         *
3578         * @param orig - original Instrument object to be copied from
3579         */
3580        void Instrument::CopyAssign(const Instrument* orig) {
3581            CopyAssign(orig, NULL);
3582        }
3583            
3584        /**
3585         * Make a (semi) deep copy of the Instrument object given by @a orig
3586         * and assign it to this object.
3587         *
3588         * @param orig - original Instrument object to be copied from
3589         * @param mSamples - crosslink map between the foreign file's samples and
3590         *                   this file's samples
3591         */
3592        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3593            // handle base class
3594            // (without copying DLS region stuff)
3595            DLS::Instrument::CopyAssignCore(orig);
3596            
3597            // handle own member variables
3598            Attenuation = orig->Attenuation;
3599            EffectSend = orig->EffectSend;
3600            FineTune = orig->FineTune;
3601            PitchbendRange = orig->PitchbendRange;
3602            PianoReleaseMode = orig->PianoReleaseMode;
3603            DimensionKeyRange = orig->DimensionKeyRange;
3604            
3605            // free old midi rules
3606            for (int i = 0 ; pMidiRules[i] ; i++) {
3607                delete pMidiRules[i];
3608            }
3609            //TODO: MIDI rule copying
3610            pMidiRules[0] = NULL;
3611            
3612            // delete all old regions
3613            while (Regions) DeleteRegion(GetFirstRegion());
3614            // create new regions and copy them from original
3615            {
3616                RegionList::const_iterator it = orig->pRegions->begin();
3617                for (int i = 0; i < orig->Regions; ++i, ++it) {
3618                    Region* dstRgn = AddRegion();
3619                    //NOTE: Region does semi-deep copy !
3620                    dstRgn->CopyAssign(
3621                        static_cast<gig::Region*>(*it),
3622                        mSamples
3623                    );
3624                }
3625            }
3626    
3627            UpdateRegionKeyTable();
3628        }
3629    
3630    
3631    // *************** Group ***************
3632    // *
3633    
3634        /** @brief Constructor.
3635         *
3636         * @param file   - pointer to the gig::File object
3637         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
3638         *                 NULL if this is a new Group
3639         */
3640        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
3641            pFile      = file;
3642            pNameChunk = ck3gnm;
3643            ::LoadString(pNameChunk, Name);
3644        }
3645    
3646        Group::~Group() {
3647            // remove the chunk associated with this group (if any)
3648            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3649        }
3650    
3651        /** @brief Update chunks with current group settings.
3652         *
3653         * Apply current Group field values to the respective chunks. You have
3654         * to call File::Save() to make changes persistent.
3655         *
3656         * Usually there is absolutely no need to call this method explicitly.
3657         * It will be called automatically when File::Save() was called.
3658         */
3659        void Group::UpdateChunks() {
3660            // make sure <3gri> and <3gnl> list chunks exist
3661            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3662            if (!_3gri) {
3663                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3664                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3665            }
3666            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3667            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3668    
3669            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3670                // v3 has a fixed list of 128 strings, find a free one
3671                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3672                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3673                        pNameChunk = ck;
3674                        break;
3675                    }
3676                }
3677            }
3678    
3679            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3680            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3681        }
3682    
3683        /**
3684         * Returns the first Sample of this Group. You have to call this method
3685         * once before you use GetNextSample().
3686         *
3687         * <b>Notice:</b> this method might block for a long time, in case the
3688         * samples of this .gig file were not scanned yet
3689         *
3690         * @returns  pointer address to first Sample or NULL if there is none
3691         *           applied to this Group
3692         * @see      GetNextSample()
3693         */
3694        Sample* Group::GetFirstSample() {
3695            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3696            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
3697                if (pSample->GetGroup() == this) return pSample;
3698            }
3699            return NULL;
3700        }
3701    
3702        /**
3703         * Returns the next Sample of the Group. You have to call
3704         * GetFirstSample() once before you can use this method. By calling this
3705         * method multiple times it iterates through the Samples assigned to
3706         * this Group.
3707         *
3708         * @returns  pointer address to the next Sample of this Group or NULL if
3709         *           end reached
3710         * @see      GetFirstSample()
3711         */
3712        Sample* Group::GetNextSample() {
3713            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3714            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
3715                if (pSample->GetGroup() == this) return pSample;
3716            }
3717            return NULL;
3718        }
3719    
3720        /**
3721         * Move Sample given by \a pSample from another Group to this Group.
3722         */
3723        void Group::AddSample(Sample* pSample) {
3724            pSample->pGroup = this;
3725        }
3726    
3727        /**
3728         * Move all members of this group to another group (preferably the 1st
3729         * one except this). This method is called explicitly by
3730         * File::DeleteGroup() thus when a Group was deleted. This code was
3731         * intentionally not placed in the destructor!
3732         */
3733        void Group::MoveAll() {
3734            // get "that" other group first
3735            Group* pOtherGroup = NULL;
3736            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
3737                if (pOtherGroup != this) break;
3738            }
3739            if (!pOtherGroup) throw Exception(
3740                "Could not move samples to another group, since there is no "
3741                "other Group. This is a bug, report it!"
3742            );
3743            // now move all samples of this group to the other group
3744            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3745                pOtherGroup->AddSample(pSample);
3746            }
3747        }
3748    
3749    
3750    
3751  // *************** File ***************  // *************** File ***************
3752  // *  // *
3753    
3754        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3755        const DLS::version_t File::VERSION_2 = {
3756            0, 2, 19980628 & 0xffff, 19980628 >> 16
3757        };
3758    
3759        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3760        const DLS::version_t File::VERSION_3 = {
3761            0, 3, 20030331 & 0xffff, 20030331 >> 16
3762        };
3763    
3764        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3765            { CHUNK_ID_IARL, 256 },
3766            { CHUNK_ID_IART, 128 },
3767            { CHUNK_ID_ICMS, 128 },
3768            { CHUNK_ID_ICMT, 1024 },
3769            { CHUNK_ID_ICOP, 128 },
3770            { CHUNK_ID_ICRD, 128 },
3771            { CHUNK_ID_IENG, 128 },
3772            { CHUNK_ID_IGNR, 128 },
3773            { CHUNK_ID_IKEY, 128 },
3774            { CHUNK_ID_IMED, 128 },
3775            { CHUNK_ID_INAM, 128 },
3776            { CHUNK_ID_IPRD, 128 },
3777            { CHUNK_ID_ISBJ, 128 },
3778            { CHUNK_ID_ISFT, 128 },
3779            { CHUNK_ID_ISRC, 128 },
3780            { CHUNK_ID_ISRF, 128 },
3781            { CHUNK_ID_ITCH, 128 },
3782            { 0, 0 }
3783        };
3784    
3785      File::File() : DLS::File() {      File::File() : DLS::File() {
3786            bAutoLoad = true;
3787            *pVersion = VERSION_3;
3788            pGroups = NULL;
3789            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3790            pInfo->ArchivalLocation = String(256, ' ');
3791    
3792            // add some mandatory chunks to get the file chunks in right
3793            // order (INFO chunk will be moved to first position later)
3794            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3795            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3796            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3797    
3798            GenerateDLSID();
3799      }      }
3800    
3801      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3802            bAutoLoad = true;
3803            pGroups = NULL;
3804            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3805        }
3806    
3807        File::~File() {
3808            if (pGroups) {
3809                std::list<Group*>::iterator iter = pGroups->begin();
3810                std::list<Group*>::iterator end  = pGroups->end();
3811                while (iter != end) {
3812                    delete *iter;
3813                    ++iter;
3814                }
3815                delete pGroups;
3816            }
3817      }      }
3818    
3819      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2685  namespace { Line 3828  namespace {
3828          SamplesIterator++;          SamplesIterator++;
3829          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3830      }      }
3831        
3832        /**
3833         * Returns Sample object of @a index.
3834         *
3835         * @returns sample object or NULL if index is out of bounds
3836         */
3837        Sample* File::GetSample(uint index) {
3838            if (!pSamples) LoadSamples();
3839            if (!pSamples) return NULL;
3840            DLS::File::SampleList::iterator it = pSamples->begin();
3841            for (int i = 0; i < index; ++i) {
3842                ++it;
3843                if (it == pSamples->end()) return NULL;
3844            }
3845            if (it == pSamples->end()) return NULL;
3846            return static_cast<gig::Sample*>( *it );
3847        }
3848    
3849      /** @brief Add a new sample.      /** @brief Add a new sample.
3850       *       *
# Line 2700  namespace { Line 3860  namespace {
3860         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
3861         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3862         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*/);
3863    
3864           // add mandatory chunks to get the chunks in right order
3865           wave->AddSubChunk(CHUNK_ID_FMT, 16);
3866           wave->AddSubList(LIST_TYPE_INFO);
3867    
3868         pSamples->push_back(pSample);         pSamples->push_back(pSample);
3869         return pSample;         return pSample;
3870      }      }
3871    
3872      /** @brief Delete a sample.      /** @brief Delete a sample.
3873       *       *
3874       * 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
3875       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
3876         * removed. You have to call Save() to make this persistent to the file.
3877       *       *
3878       * @param pSample - sample to delete       * @param pSample - sample to delete
3879       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2716  namespace { Line 3882  namespace {
3882          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");
3883          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
3884          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");
3885            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3886          pSamples->erase(iter);          pSamples->erase(iter);
3887          delete pSample;          delete pSample;
3888    
3889            SampleList::iterator tmp = SamplesIterator;
3890            // remove all references to the sample
3891            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3892                 instrument = GetNextInstrument()) {
3893                for (Region* region = instrument->GetFirstRegion() ; region ;
3894                     region = instrument->GetNextRegion()) {
3895    
3896                    if (region->GetSample() == pSample) region->SetSample(NULL);
3897    
3898                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3899                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3900                        if (d->pSample == pSample) d->pSample = NULL;
3901                    }
3902                }
3903            }
3904            SamplesIterator = tmp; // restore iterator
3905      }      }
3906    
3907      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2725  namespace { Line 3909  namespace {
3909      }      }
3910    
3911      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
3912            // Groups must be loaded before samples, because samples will try
3913            // to resolve the group they belong to
3914            if (!pGroups) LoadGroups();
3915    
3916          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
3917    
3918          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
# Line 2804  namespace { Line 3992  namespace {
3992              progress_t subprogress;              progress_t subprogress;
3993              __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
3994              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3995              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3996                    GetFirstSample(&subprogress); // now force all samples to be loaded
3997              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3998    
3999              // instrument loading subtask              // instrument loading subtask
# Line 2837  namespace { Line 4026  namespace {
4026         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
4027         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4028         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4029    
4030           // add mandatory chunks to get the chunks in right order
4031           lstInstr->AddSubList(LIST_TYPE_INFO);
4032           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4033    
4034         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
4035           pInstrument->GenerateDLSID();
4036    
4037           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4038    
4039           // this string is needed for the gig to be loadable in GSt:
4040           pInstrument->pInfo->Software = "Endless Wave";
4041    
4042         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4043         return pInstrument;         return pInstrument;
4044      }      }
4045        
4046        /** @brief Add a duplicate of an existing instrument.
4047         *
4048         * Duplicates the instrument definition given by @a orig and adds it
4049         * to this file. This allows in an instrument editor application to
4050         * easily create variations of an instrument, which will be stored in
4051         * the same .gig file, sharing i.e. the same samples.
4052         *
4053         * Note that all sample pointers referenced by @a orig are simply copied as
4054         * memory address. Thus the respective samples are shared, not duplicated!
4055         *
4056         * You have to call Save() to make this persistent to the file.
4057         *
4058         * @param orig - original instrument to be copied
4059         * @returns duplicated copy of the given instrument
4060         */
4061        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4062            Instrument* instr = AddInstrument();
4063            instr->CopyAssign(orig);
4064            return instr;
4065        }
4066        
4067        /** @brief Add content of another existing file.
4068         *
4069         * Duplicates the samples, groups and instruments of the original file
4070         * given by @a pFile and adds them to @c this File. In case @c this File is
4071         * a new one that you haven't saved before, then you have to call
4072         * SetFileName() before calling AddContentOf(), because this method will
4073         * automatically save this file during operation, which is required for
4074         * writing the sample waveform data by disk streaming.
4075         *
4076         * @param pFile - original file whose's content shall be copied from
4077         */
4078        void File::AddContentOf(File* pFile) {
4079            static int iCallCount = -1;
4080            iCallCount++;
4081            std::map<Group*,Group*> mGroups;
4082            std::map<Sample*,Sample*> mSamples;
4083            
4084            // clone sample groups
4085            for (int i = 0; pFile->GetGroup(i); ++i) {
4086                Group* g = AddGroup();
4087                g->Name =
4088                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4089                mGroups[pFile->GetGroup(i)] = g;
4090            }
4091            
4092            // clone samples (not waveform data here yet)
4093            for (int i = 0; pFile->GetSample(i); ++i) {
4094                Sample* s = AddSample();
4095                s->CopyAssignMeta(pFile->GetSample(i));
4096                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4097                mSamples[pFile->GetSample(i)] = s;
4098            }
4099            
4100            //BUG: For some reason this method only works with this additional
4101            //     Save() call in between here.
4102            //
4103            // Important: The correct one of the 2 Save() methods has to be called
4104            // here, depending on whether the file is completely new or has been
4105            // saved to disk already, otherwise it will result in data corruption.
4106            if (pRIFF->IsNew())
4107                Save(GetFileName());
4108            else
4109                Save();
4110            
4111            // clone instruments
4112            // (passing the crosslink table here for the cloned samples)
4113            for (int i = 0; pFile->GetInstrument(i); ++i) {
4114                Instrument* instr = AddInstrument();
4115                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4116            }
4117            
4118            // Mandatory: file needs to be saved to disk at this point, so this
4119            // file has the correct size and data layout for writing the samples'
4120            // waveform data to disk.
4121            Save();
4122            
4123            // clone samples' waveform data
4124            // (using direct read & write disk streaming)
4125            for (int i = 0; pFile->GetSample(i); ++i) {
4126                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4127            }
4128        }
4129    
4130      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4131       *       *
# Line 2848  namespace { Line 4133  namespace {
4133       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
4134       *       *
4135       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
4136       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
4137       */       */
4138      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
4139          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 2888  namespace { Line 4173  namespace {
4173          }          }
4174      }      }
4175    
4176        /// Updates the 3crc chunk with the checksum of a sample. The
4177        /// update is done directly to disk, as this method is called
4178        /// after File::Save()
4179        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4180            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4181            if (!_3crc) return;
4182    
4183            // get the index of the sample
4184            int iWaveIndex = -1;
4185            File::SampleList::iterator iter = pSamples->begin();
4186            File::SampleList::iterator end  = pSamples->end();
4187            for (int index = 0; iter != end; ++iter, ++index) {
4188                if (*iter == pSample) {
4189                    iWaveIndex = index;
4190                    break;
4191                }
4192            }
4193            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4194    
4195            // write the CRC-32 checksum to disk
4196            _3crc->SetPos(iWaveIndex * 8);
4197            uint32_t tmp = 1;
4198            _3crc->WriteUint32(&tmp); // unknown, always 1?
4199            _3crc->WriteUint32(&crc);
4200        }
4201    
4202        Group* File::GetFirstGroup() {
4203            if (!pGroups) LoadGroups();
4204            // there must always be at least one group
4205            GroupsIterator = pGroups->begin();
4206            return *GroupsIterator;
4207        }
4208    
4209        Group* File::GetNextGroup() {
4210            if (!pGroups) return NULL;
4211            ++GroupsIterator;
4212            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
4213        }
4214    
4215        /**
4216         * Returns the group with the given index.
4217         *
4218         * @param index - number of the sought group (0..n)
4219         * @returns sought group or NULL if there's no such group
4220         */
4221        Group* File::GetGroup(uint index) {
4222            if (!pGroups) LoadGroups();
4223            GroupsIterator = pGroups->begin();
4224            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4225                if (i == index) return *GroupsIterator;
4226                ++GroupsIterator;
4227            }
4228            return NULL;
4229        }
4230    
4231        Group* File::AddGroup() {
4232            if (!pGroups) LoadGroups();
4233            // there must always be at least one group
4234            __ensureMandatoryChunksExist();
4235            Group* pGroup = new Group(this, NULL);
4236            pGroups->push_back(pGroup);
4237            return pGroup;
4238        }
4239    
4240        /** @brief Delete a group and its samples.
4241         *
4242         * This will delete the given Group object and all the samples that
4243         * belong to this group from the gig file. You have to call Save() to
4244         * make this persistent to the file.
4245         *
4246         * @param pGroup - group to delete
4247         * @throws gig::Exception if given group could not be found
4248         */
4249        void File::DeleteGroup(Group* pGroup) {
4250            if (!pGroups) LoadGroups();
4251            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4252            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4253            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4254            // delete all members of this group
4255            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
4256                DeleteSample(pSample);
4257            }
4258            // now delete this group object
4259            pGroups->erase(iter);
4260            delete pGroup;
4261        }
4262    
4263        /** @brief Delete a group.
4264         *
4265         * This will delete the given Group object from the gig file. All the
4266         * samples that belong to this group will not be deleted, but instead
4267         * be moved to another group. You have to call Save() to make this
4268         * persistent to the file.
4269         *
4270         * @param pGroup - group to delete
4271         * @throws gig::Exception if given group could not be found
4272         */
4273        void File::DeleteGroupOnly(Group* pGroup) {
4274            if (!pGroups) LoadGroups();
4275            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4276            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4277            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4278            // move all members of this group to another group
4279            pGroup->MoveAll();
4280            pGroups->erase(iter);
4281            delete pGroup;
4282        }
4283    
4284        void File::LoadGroups() {
4285            if (!pGroups) pGroups = new std::list<Group*>;
4286            // try to read defined groups from file
4287            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4288            if (lst3gri) {
4289                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
4290                if (lst3gnl) {
4291                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4292                    while (ck) {
4293                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4294                            if (pVersion && pVersion->major == 3 &&
4295                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4296    
4297                            pGroups->push_back(new Group(this, ck));
4298                        }
4299                        ck = lst3gnl->GetNextSubChunk();
4300                    }
4301                }
4302            }
4303            // if there were no group(s), create at least the mandatory default group
4304            if (!pGroups->size()) {
4305                Group* pGroup = new Group(this, NULL);
4306                pGroup->Name = "Default Group";
4307                pGroups->push_back(pGroup);
4308            }
4309        }
4310    
4311        /**
4312         * Apply all the gig file's current instruments, samples, groups and settings
4313         * to the respective RIFF chunks. You have to call Save() to make changes
4314         * persistent.
4315         *
4316         * Usually there is absolutely no need to call this method explicitly.
4317         * It will be called automatically when File::Save() was called.
4318         *
4319         * @throws Exception - on errors
4320         */
4321        void File::UpdateChunks() {
4322            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4323    
4324            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4325    
4326            // first update base class's chunks
4327            DLS::File::UpdateChunks();
4328    
4329            if (newFile) {
4330                // INFO was added by Resource::UpdateChunks - make sure it
4331                // is placed first in file
4332                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4333                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4334                if (first != info) {
4335                    pRIFF->MoveSubChunk(info, first);
4336                }
4337            }
4338    
4339            // update group's chunks
4340            if (pGroups) {
4341                // make sure '3gri' and '3gnl' list chunks exist
4342                // (before updating the Group chunks)
4343                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4344                if (!_3gri) {
4345                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4346                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4347                }
4348                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4349                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4350    
4351                // v3: make sure the file has 128 3gnm chunks
4352                // (before updating the Group chunks)
4353                if (pVersion && pVersion->major == 3) {
4354                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4355                    for (int i = 0 ; i < 128 ; i++) {
4356                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4357                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4358                    }
4359                }
4360    
4361                std::list<Group*>::iterator iter = pGroups->begin();
4362                std::list<Group*>::iterator end  = pGroups->end();
4363                for (; iter != end; ++iter) {
4364                    (*iter)->UpdateChunks();
4365                }
4366            }
4367    
4368            // update einf chunk
4369    
4370            // The einf chunk contains statistics about the gig file, such
4371            // as the number of regions and samples used by each
4372            // instrument. It is divided in equally sized parts, where the
4373            // first part contains information about the whole gig file,
4374            // and the rest of the parts map to each instrument in the
4375            // file.
4376            //
4377            // At the end of each part there is a bit map of each sample
4378            // in the file, where a set bit means that the sample is used
4379            // by the file/instrument.
4380            //
4381            // Note that there are several fields with unknown use. These
4382            // are set to zero.
4383    
4384            int sublen = pSamples->size() / 8 + 49;
4385            int einfSize = (Instruments + 1) * sublen;
4386    
4387            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4388            if (einf) {
4389                if (einf->GetSize() != einfSize) {
4390                    einf->Resize(einfSize);
4391                    memset(einf->LoadChunkData(), 0, einfSize);
4392                }
4393            } else if (newFile) {
4394                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4395            }
4396            if (einf) {
4397                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4398    
4399                std::map<gig::Sample*,int> sampleMap;
4400                int sampleIdx = 0;
4401                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4402                    sampleMap[pSample] = sampleIdx++;
4403                }
4404    
4405                int totnbusedsamples = 0;
4406                int totnbusedchannels = 0;
4407                int totnbregions = 0;
4408                int totnbdimregions = 0;
4409                int totnbloops = 0;
4410                int instrumentIdx = 0;
4411    
4412                memset(&pData[48], 0, sublen - 48);
4413    
4414                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4415                     instrument = GetNextInstrument()) {
4416                    int nbusedsamples = 0;
4417                    int nbusedchannels = 0;
4418                    int nbdimregions = 0;
4419                    int nbloops = 0;
4420    
4421                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4422    
4423                    for (Region* region = instrument->GetFirstRegion() ; region ;
4424                         region = instrument->GetNextRegion()) {
4425                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
4426                            gig::DimensionRegion *d = region->pDimensionRegions[i];
4427                            if (d->pSample) {
4428                                int sampleIdx = sampleMap[d->pSample];
4429                                int byte = 48 + sampleIdx / 8;
4430                                int bit = 1 << (sampleIdx & 7);
4431                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4432                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4433                                    nbusedsamples++;
4434                                    nbusedchannels += d->pSample->Channels;
4435    
4436                                    if ((pData[byte] & bit) == 0) {
4437                                        pData[byte] |= bit;
4438                                        totnbusedsamples++;
4439                                        totnbusedchannels += d->pSample->Channels;
4440                                    }
4441                                }
4442                            }
4443                            if (d->SampleLoops) nbloops++;
4444                        }
4445                        nbdimregions += region->DimensionRegions;
4446                    }
4447                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4448                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4449                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4450                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4451                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4452                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4453                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4454                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4455                    // next 8 bytes unknown
4456                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4457                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4458                    // next 4 bytes unknown
4459    
4460                    totnbregions += instrument->Regions;
4461                    totnbdimregions += nbdimregions;
4462                    totnbloops += nbloops;
4463                    instrumentIdx++;
4464                }
4465                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4466                // store32(&pData[0], sublen);
4467                store32(&pData[4], totnbusedchannels);
4468                store32(&pData[8], totnbusedsamples);
4469                store32(&pData[12], Instruments);
4470                store32(&pData[16], totnbregions);
4471                store32(&pData[20], totnbdimregions);
4472                store32(&pData[24], totnbloops);
4473                // next 8 bytes unknown
4474                // next 4 bytes unknown, not always 0
4475                store32(&pData[40], pSamples->size());
4476                // next 4 bytes unknown
4477            }
4478    
4479            // update 3crc chunk
4480    
4481            // The 3crc chunk contains CRC-32 checksums for the
4482            // samples. The actual checksum values will be filled in
4483            // later, by Sample::Write.
4484    
4485            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4486            if (_3crc) {
4487                _3crc->Resize(pSamples->size() * 8);
4488            } else if (newFile) {
4489                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4490                _3crc->LoadChunkData();
4491    
4492                // the order of einf and 3crc is not the same in v2 and v3
4493                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4494            }
4495        }
4496    
4497        /**
4498         * Enable / disable automatic loading. By default this properyt is
4499         * enabled and all informations are loaded automatically. However
4500         * loading all Regions, DimensionRegions and especially samples might
4501         * take a long time for large .gig files, and sometimes one might only
4502         * be interested in retrieving very superficial informations like the
4503         * amount of instruments and their names. In this case one might disable
4504         * automatic loading to avoid very slow response times.
4505         *
4506         * @e CAUTION: by disabling this property many pointers (i.e. sample
4507         * references) and informations will have invalid or even undefined
4508         * data! This feature is currently only intended for retrieving very
4509         * superficial informations in a very fast way. Don't use it to retrieve
4510         * details like synthesis informations or even to modify .gig files!
4511         */
4512        void File::SetAutoLoad(bool b) {
4513            bAutoLoad = b;
4514        }
4515    
4516        /**
4517         * Returns whether automatic loading is enabled.
4518         * @see SetAutoLoad()
4519         */
4520        bool File::GetAutoLoad() {
4521            return bAutoLoad;
4522        }
4523    
4524    
4525    
4526  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.858  
changed lines
  Added in v.2484

  ViewVC Help
Powered by ViewVC