/[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 352 by schoenebeck, Sat Jan 29 14:24:11 2005 UTC revision 1076 by persson, Tue Mar 6 18:33:30 2007 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, 2004 by Christian Schoenebeck                     *   *   Copyright (C) 2003-2007 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  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26    #include "helper.h"
27    
28    #include <math.h>
29    #include <iostream>
30    
31    /// Initial size of the sample buffer which is used for decompression of
32    /// compressed sample wave streams - this value should always be bigger than
33    /// the biggest sample piece expected to be read by the sampler engine,
34    /// otherwise the buffer size will be raised at runtime and thus the buffer
35    /// reallocated which is time consuming and unefficient.
36    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
37    
38    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
40    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
41    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
42    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
43    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
44    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
45    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
46    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
47    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
49    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
50    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
51    
52  namespace gig {  namespace gig {
53    
54    // *************** progress_t ***************
55    // *
56    
57        progress_t::progress_t() {
58            callback    = NULL;
59            custom      = NULL;
60            __range_min = 0.0f;
61            __range_max = 1.0f;
62        }
63    
64        // private helper function to convert progress of a subprocess into the global progress
65        static void __notify_progress(progress_t* pProgress, float subprogress) {
66            if (pProgress && pProgress->callback) {
67                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
68                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
69                pProgress->factor         = totalprogress;
70                pProgress->callback(pProgress); // now actually notify about the progress
71            }
72        }
73    
74        // private helper function to divide a progress into subprogresses
75        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
76            if (pParentProgress && pParentProgress->callback) {
77                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
78                pSubProgress->callback    = pParentProgress->callback;
79                pSubProgress->custom      = pParentProgress->custom;
80                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
81                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
82            }
83        }
84    
85    
86    // *************** Internal functions for sample decompression ***************
87    // *
88    
89    namespace {
90    
91        inline int get12lo(const unsigned char* pSrc)
92        {
93            const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
94            return x & 0x800 ? x - 0x1000 : x;
95        }
96    
97        inline int get12hi(const unsigned char* pSrc)
98        {
99            const int x = pSrc[1] >> 4 | pSrc[2] << 4;
100            return x & 0x800 ? x - 0x1000 : x;
101        }
102    
103        inline int16_t get16(const unsigned char* pSrc)
104        {
105            return int16_t(pSrc[0] | pSrc[1] << 8);
106        }
107    
108        inline int get24(const unsigned char* pSrc)
109        {
110            const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
111            return x & 0x800000 ? x - 0x1000000 : x;
112        }
113    
114        inline void store24(unsigned char* pDst, int x)
115        {
116            pDst[0] = x;
117            pDst[1] = x >> 8;
118            pDst[2] = x >> 16;
119        }
120    
121        void Decompress16(int compressionmode, const unsigned char* params,
122                          int srcStep, int dstStep,
123                          const unsigned char* pSrc, int16_t* pDst,
124                          unsigned long currentframeoffset,
125                          unsigned long copysamples)
126        {
127            switch (compressionmode) {
128                case 0: // 16 bit uncompressed
129                    pSrc += currentframeoffset * srcStep;
130                    while (copysamples) {
131                        *pDst = get16(pSrc);
132                        pDst += dstStep;
133                        pSrc += srcStep;
134                        copysamples--;
135                    }
136                    break;
137    
138                case 1: // 16 bit compressed to 8 bit
139                    int y  = get16(params);
140                    int dy = get16(params + 2);
141                    while (currentframeoffset) {
142                        dy -= int8_t(*pSrc);
143                        y  -= dy;
144                        pSrc += srcStep;
145                        currentframeoffset--;
146                    }
147                    while (copysamples) {
148                        dy -= int8_t(*pSrc);
149                        y  -= dy;
150                        *pDst = y;
151                        pDst += dstStep;
152                        pSrc += srcStep;
153                        copysamples--;
154                    }
155                    break;
156            }
157        }
158    
159        void Decompress24(int compressionmode, const unsigned char* params,
160                          int dstStep, const unsigned char* pSrc, uint8_t* pDst,
161                          unsigned long currentframeoffset,
162                          unsigned long copysamples, int truncatedBits)
163        {
164            int y, dy, ddy, dddy;
165    
166    #define GET_PARAMS(params)                      \
167            y    = get24(params);                   \
168            dy   = y - get24((params) + 3);         \
169            ddy  = get24((params) + 6);             \
170            dddy = get24((params) + 9)
171    
172    #define SKIP_ONE(x)                             \
173            dddy -= (x);                            \
174            ddy  -= dddy;                           \
175            dy   =  -dy - ddy;                      \
176            y    += dy
177    
178    #define COPY_ONE(x)                             \
179            SKIP_ONE(x);                            \
180            store24(pDst, y << truncatedBits);      \
181            pDst += dstStep
182    
183            switch (compressionmode) {
184                case 2: // 24 bit uncompressed
185                    pSrc += currentframeoffset * 3;
186                    while (copysamples) {
187                        store24(pDst, get24(pSrc) << truncatedBits);
188                        pDst += dstStep;
189                        pSrc += 3;
190                        copysamples--;
191                    }
192                    break;
193    
194                case 3: // 24 bit compressed to 16 bit
195                    GET_PARAMS(params);
196                    while (currentframeoffset) {
197                        SKIP_ONE(get16(pSrc));
198                        pSrc += 2;
199                        currentframeoffset--;
200                    }
201                    while (copysamples) {
202                        COPY_ONE(get16(pSrc));
203                        pSrc += 2;
204                        copysamples--;
205                    }
206                    break;
207    
208                case 4: // 24 bit compressed to 12 bit
209                    GET_PARAMS(params);
210                    while (currentframeoffset > 1) {
211                        SKIP_ONE(get12lo(pSrc));
212                        SKIP_ONE(get12hi(pSrc));
213                        pSrc += 3;
214                        currentframeoffset -= 2;
215                    }
216                    if (currentframeoffset) {
217                        SKIP_ONE(get12lo(pSrc));
218                        currentframeoffset--;
219                        if (copysamples) {
220                            COPY_ONE(get12hi(pSrc));
221                            pSrc += 3;
222                            copysamples--;
223                        }
224                    }
225                    while (copysamples > 1) {
226                        COPY_ONE(get12lo(pSrc));
227                        COPY_ONE(get12hi(pSrc));
228                        pSrc += 3;
229                        copysamples -= 2;
230                    }
231                    if (copysamples) {
232                        COPY_ONE(get12lo(pSrc));
233                    }
234                    break;
235    
236                case 5: // 24 bit compressed to 8 bit
237                    GET_PARAMS(params);
238                    while (currentframeoffset) {
239                        SKIP_ONE(int8_t(*pSrc++));
240                        currentframeoffset--;
241                    }
242                    while (copysamples) {
243                        COPY_ONE(int8_t(*pSrc++));
244                        copysamples--;
245                    }
246                    break;
247            }
248        }
249    
250        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
251        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
252        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
253        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
254    }
255    
256    
257  // *************** Sample ***************  // *************** Sample ***************
258  // *  // *
259    
260      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
261      void*         Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
262    
263      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
264         *
265         * Load an existing sample or create a new one. A 'wave' list chunk must
266         * be given to this constructor. In case the given 'wave' list chunk
267         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
268         * format and sample data will be loaded from there, otherwise default
269         * values will be used and those chunks will be created when
270         * File::Save() will be called later on.
271         *
272         * @param pFile          - pointer to gig::File where this sample is
273         *                         located (or will be located)
274         * @param waveList       - pointer to 'wave' list chunk which is (or
275         *                         will be) associated with this sample
276         * @param WavePoolOffset - offset of this sample data from wave pool
277         *                         ('wvpl') list chunk
278         * @param fileNo         - number of an extension file where this sample
279         *                         is located, 0 otherwise
280         */
281        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
282            pInfo->UseFixedLengthStrings = true;
283          Instances++;          Instances++;
284            FileNo = fileNo;
285    
286          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
287          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
288          SampleGroup = _3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
289                pGroup = pFile->GetGroup(iSampleGroup);
290          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          } else { // '3gix' chunk missing
291          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              // by default assigned to that mandatory "Default Group"
292          Manufacturer      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
293          Product           = smpl->ReadInt32();          }
294          SamplePeriod      = smpl->ReadInt32();  
295          MIDIUnityNote     = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
296          FineTune          = smpl->ReadInt32();          if (pCkSmpl) {
297          smpl->Read(&SMPTEFormat, 1, 4);              Manufacturer  = pCkSmpl->ReadInt32();
298          SMPTEOffset       = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
299          Loops             = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
300          uint32_t manufByt = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
301          LoopID            = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
302          smpl->Read(&LoopType, 1, 4);              pCkSmpl->Read(&SMPTEFormat, 1, 4);
303          LoopStart         = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
304          LoopEnd           = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
305          LoopFraction      = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
306          LoopPlayCount     = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
307                pCkSmpl->Read(&LoopType, 1, 4);
308                LoopStart     = pCkSmpl->ReadInt32();
309                LoopEnd       = pCkSmpl->ReadInt32();
310                LoopFraction  = pCkSmpl->ReadInt32();
311                LoopPlayCount = pCkSmpl->ReadInt32();
312            } else { // 'smpl' chunk missing
313                // use default values
314                Manufacturer  = 0;
315                Product       = 0;
316                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
317                MIDIUnityNote = 64;
318                FineTune      = 0;
319                SMPTEOffset   = 0;
320                Loops         = 0;
321                LoopID        = 0;
322                LoopStart     = 0;
323                LoopEnd       = 0;
324                LoopFraction  = 0;
325                LoopPlayCount = 0;
326            }
327    
328          FrameTable                 = NULL;          FrameTable                 = NULL;
329          SamplePos                  = 0;          SamplePos                  = 0;
# Line 63  namespace gig { Line 331  namespace gig {
331          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
332          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
333    
334          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
335    
336            RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
337            Compressed        = ewav;
338            Dithered          = false;
339            TruncatedBits     = 0;
340          if (Compressed) {          if (Compressed) {
341                uint32_t version = ewav->ReadInt32();
342                if (version == 3 && BitDepth == 24) {
343                    Dithered = ewav->ReadInt32();
344                    ewav->SetPos(Channels == 2 ? 84 : 64);
345                    TruncatedBits = ewav->ReadInt32();
346                }
347              ScanCompressedSample();              ScanCompressedSample();
348          }          }
349    
         if (BitDepth > 24)                throw gig::Exception("Only samples up to 24 bit supported");  
         if (Compressed && Channels == 1)  throw gig::Exception("Mono compressed samples not yet supported");  
         if (Compressed && BitDepth == 24) throw gig::Exception("24 bit compressed samples not yet supported");  
   
350          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
351          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
352              pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
353              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
354          }          }
355          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
356    
357            LoopSize = LoopEnd - LoopStart + 1;
358        }
359    
360          LoopSize = LoopEnd - LoopStart;      /**
361         * Apply sample and its settings to the respective RIFF chunks. You have
362         * to call File::Save() to make changes persistent.
363         *
364         * Usually there is absolutely no need to call this method explicitly.
365         * It will be called automatically when File::Save() was called.
366         *
367         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
368         *                        was provided yet
369         * @throws gig::Exception if there is any invalid sample setting
370         */
371        void Sample::UpdateChunks() {
372            // first update base class's chunks
373            DLS::Sample::UpdateChunks();
374    
375            // make sure 'smpl' chunk exists
376            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
377            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
378            // update 'smpl' chunk
379            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
380            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
381            memcpy(&pData[0], &Manufacturer, 4);
382            memcpy(&pData[4], &Product, 4);
383            memcpy(&pData[8], &SamplePeriod, 4);
384            memcpy(&pData[12], &MIDIUnityNote, 4);
385            memcpy(&pData[16], &FineTune, 4);
386            memcpy(&pData[20], &SMPTEFormat, 4);
387            memcpy(&pData[24], &SMPTEOffset, 4);
388            memcpy(&pData[28], &Loops, 4);
389    
390            // we skip 'manufByt' for now (4 bytes)
391    
392            memcpy(&pData[36], &LoopID, 4);
393            memcpy(&pData[40], &LoopType, 4);
394            memcpy(&pData[44], &LoopStart, 4);
395            memcpy(&pData[48], &LoopEnd, 4);
396            memcpy(&pData[52], &LoopFraction, 4);
397            memcpy(&pData[56], &LoopPlayCount, 4);
398    
399            // make sure '3gix' chunk exists
400            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
401            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
402            // determine appropriate sample group index (to be stored in chunk)
403            uint16_t iSampleGroup = 0; // 0 refers to default sample group
404            File* pFile = static_cast<File*>(pParent);
405            if (pFile->pGroups) {
406                std::list<Group*>::iterator iter = pFile->pGroups->begin();
407                std::list<Group*>::iterator end  = pFile->pGroups->end();
408                for (int i = 0; iter != end; i++, iter++) {
409                    if (*iter == pGroup) {
410                        iSampleGroup = i;
411                        break; // found
412                    }
413                }
414            }
415            // update '3gix' chunk
416            pData = (uint8_t*) pCk3gix->LoadChunkData();
417            memcpy(&pData[0], &iSampleGroup, 2);
418      }      }
419    
420      /// 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 88  namespace gig { Line 423  namespace gig {
423          this->SamplesTotal = 0;          this->SamplesTotal = 0;
424          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
425    
426            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
427            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
428    
429          // Scanning          // Scanning
430          pCkData->SetPos(0);          pCkData->SetPos(0);
431          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
432              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
433              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
434              this->SamplesTotal += 2048;                  // stored, to save some memory
435              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
436                  case 1:   // left channel compressed  
437                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
438                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
439                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
440                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
441    
442                    if (pCkData->RemainingBytes() <= frameSize) {
443                        SamplesInLastFrame =
444                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
445                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
446                        SamplesTotal += SamplesInLastFrame;
447                      break;                      break;
448                  case 257: // both channels compressed                  }
449                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
450                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
451                }
452            }
453            else { // Mono
454                for (int i = 0 ; ; i++) {
455                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
456    
457                    const int mode = pCkData->ReadUint8();
458                    if (mode > 5) throw gig::Exception("Unknown compression mode");
459                    const unsigned long frameSize = bytesPerFrame[mode];
460    
461                    if (pCkData->RemainingBytes() <= frameSize) {
462                        SamplesInLastFrame =
463                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
464                        SamplesTotal += SamplesInLastFrame;
465                      break;                      break;
466                  default: // both channels uncompressed                  }
467                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
468                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
469              }              }
470          }          }
471          pCkData->SetPos(0);          pCkData->SetPos(0);
472    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
473          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
474          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
475          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 147  namespace gig { Line 505  namespace gig {
505       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
506       * that the size is given in bytes! You get the number of actually cached       * that the size is given in bytes! You get the number of actually cached
507       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
508       *       * @code
509       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
510       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
511         * @endcode
512       *       *
513       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
514       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 195  namespace gig { Line 554  namespace gig {
554       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
555       * that the size is given in bytes! You get the number of actually cached       * that the size is given in bytes! You get the number of actually cached
556       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
557       *       * @code
558       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
559       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
560       *       * @endcode
561       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
562       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
563       * buffer_t structure, that means 'Size' always reflects the size of the       * buffer_t structure, that means 'Size' always reflects the size of the
# Line 258  namespace gig { Line 617  namespace gig {
617          RAMCache.Size   = 0;          RAMCache.Size   = 0;
618      }      }
619    
620        /** @brief Resize sample.
621         *
622         * Resizes the sample's wave form data, that is the actual size of
623         * sample wave data possible to be written for this sample. This call
624         * will return immediately and just schedule the resize operation. You
625         * should call File::Save() to actually perform the resize operation(s)
626         * "physically" to the file. As this can take a while on large files, it
627         * is recommended to call Resize() first on all samples which have to be
628         * resized and finally to call File::Save() to perform all those resize
629         * operations in one rush.
630         *
631         * The actual size (in bytes) is dependant to the current FrameSize
632         * value. You may want to set FrameSize before calling Resize().
633         *
634         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
635         * enlarged samples before calling File::Save() as this might exceed the
636         * current sample's boundary!
637         *
638         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
639         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
640         * other formats will fail!
641         *
642         * @param iNewSize - new sample wave data size in sample points (must be
643         *                   greater than zero)
644         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
645         *                         or if \a iNewSize is less than 1
646         * @throws gig::Exception if existing sample is compressed
647         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
648         *      DLS::Sample::FormatTag, File::Save()
649         */
650        void Sample::Resize(int iNewSize) {
651            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
652            DLS::Sample::Resize(iNewSize);
653        }
654    
655      /**      /**
656       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
657       * bytes). Use this method and <i>Read()</i> if you don't want to load       * bytes). Use this method and <i>Read()</i> if you don't want to load
# Line 329  namespace gig { Line 723  namespace gig {
723       * for the next time you call this method is stored in \a pPlaybackState.       * for the next time you call this method is stored in \a pPlaybackState.
724       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
725       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
726       *       * @code
727       * <i>       * gig::playback_state_t playbackstate;
728       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
729       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
730       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
731       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
732       * You don't have to take care of things like if there is actually a loop       * You don't have to take care of things like if there is actually a loop
733       * defined or if the current read position is located within a loop area.       * defined or if the current read position is located within a loop area.
734       * The method already handles such cases by itself.       * The method already handles such cases by itself.
735       *       *
736         * <b>Caution:</b> If you are using more than one streaming thread, you
737         * have to use an external decompression buffer for <b>EACH</b>
738         * streaming thread to avoid race conditions and crashes!
739         *
740       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
741       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
742       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
743       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
744         * @param pDimRgn          dimension region with looping information
745         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
746       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
747         * @see                    CreateDecompressionBuffer()
748       */       */
749      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
750                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
751          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
752          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
753    
754          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
755    
756          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
757    
758              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
759                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
760    
761                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
762                      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));  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
763    
764                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
765                              // determine the end position within the loop first,                          do {
766                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
767                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
768                              // backward playback  
769                                if (!pPlaybackState->reverse) { // forward playback
770                              unsigned long swapareastart       = totalreadsamples;                                  do {
771                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
772                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
773                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
774                                        totalreadsamples += readsamples;
775                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
776                                            pPlaybackState->reverse = true;
777                              // read samples for backward playback                                          break;
778                              do {                                      }
779                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  } while (samplestoread && readsamples);
780                                  samplestoreadinloop -= readsamples;                              }
781                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
782    
783                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
784                                    // determine the end position within the loop first,
785                                    // read forward from that 'end' and finally after
786                                    // reading, swap all sample frames so it reflects
787                                    // backward playback
788    
789                                    unsigned long swapareastart       = totalreadsamples;
790                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
791                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
792                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
793    
794                                    SetPos(reverseplaybackend);
795    
796                                    // read samples for backward playback
797                                    do {
798                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
799                                        samplestoreadinloop -= readsamples;
800                                        samplestoread       -= readsamples;
801                                        totalreadsamples    += readsamples;
802                                    } while (samplestoreadinloop && readsamples);
803    
804                                    SetPos(reverseplaybackend); // pretend we really read backwards
805    
806                                    if (reverseplaybackend == loop.LoopStart) {
807                                        pPlaybackState->loop_cycles_left--;
808                                        pPlaybackState->reverse = false;
809                                    }
810    
811                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
812                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
813                              }                              }
814                            } while (samplestoread && readsamples);
815                            break;
816                        }
817    
818                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
819                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
820                          }                          if (!pPlaybackState->reverse) do {
821                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
822                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
823                  }                              samplestoread    -= readsamples;
824                                totalreadsamples += readsamples;
825                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
826                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
827                      if (!pPlaybackState->reverse) do {                                  break;
828                          samplestoloopend  = this->LoopEnd - GetPos();                              }
829                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
830    
831                      if (!samplestoread) break;                          if (!samplestoread) break;
832    
833                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
834                      // determine the end position within the loop first,                          // determine the end position within the loop first,
835                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
836                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
837                      // backward playback                          // backward playback
838    
839                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
840                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
841                      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)
842                                                                                : samplestoread;                                                                                    : samplestoread;
843                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
844    
845                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
846    
847                      // read samples for backward playback                          // read samples for backward playback
848                      do {                          do {
849                          // 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
850                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
851                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
852                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
853                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
854                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
855                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
856                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
857                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
858                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
859                          }                              }
860                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
861    
862                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
863    
864                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
865                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
866                      break;                          break;
867                  }                      }
868    
869                  default: case loop_type_normal: {                      default: case loop_type_normal: {
870                      do {                          do {
871                          // 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
872                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
873                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
874                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
875                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
876                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
877                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
878                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
879                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
880                          }                              }
881                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
882                      break;                          break;
883                        }
884                  }                  }
885              }              }
886          }          }
887    
888          // read on without looping          // read on without looping
889          if (samplestoread) do {          if (samplestoread) do {
890              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
891              samplestoread    -= readsamples;              samplestoread    -= readsamples;
892              totalreadsamples += readsamples;              totalreadsamples += readsamples;
893          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 501  namespace gig { Line 906  namespace gig {
906       * and <i>SetPos()</i> if you don't want to load the sample into RAM,       * and <i>SetPos()</i> if you don't want to load the sample into RAM,
907       * thus for disk streaming.       * thus for disk streaming.
908       *       *
909         * <b>Caution:</b> If you are using more than one streaming thread, you
910         * have to use an external decompression buffer for <b>EACH</b>
911         * streaming thread to avoid race conditions and crashes!
912         *
913         * For 16 bit samples, the data in the buffer will be int16_t
914         * (using native endianness). For 24 bit, the buffer will
915         * contain three bytes per sample, little-endian.
916         *
917       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
918       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
919         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
920       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
921       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
922       */       */
923      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
924          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
925          if (!Compressed) {          if (!Compressed) {
926              if (BitDepth == 24) {              if (BitDepth == 24) {
927                  // 24 bit sample. For now just truncate to 16 bit.                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
928                  int8_t* pSrc = (int8_t*)this->pDecompressionBuffer;              }
929                  int8_t* pDst = (int8_t*)pBuffer;              else { // 16 bit
930                  unsigned long n = pCkData->Read(pSrc, SampleCount, FrameSize);                  // (pCkData->Read does endian correction)
931                  for (int i = SampleCount * (FrameSize / 3) ; i > 0 ; i--) {                  return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
932                      pSrc++;                                       : pCkData->Read(pBuffer, SampleCount, 2);
                     *pDst++ = *pSrc++;  
                     *pDst++ = *pSrc++;  
                 }  
                 return SampleCount;  
             } else {  
                 return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?  
933              }              }
934          }          }
935          else { //FIXME: no support for mono compressed samples yet, are there any?          else {
936              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
937              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
938              // best case needed buffer size (all frames compressed)              unsigned long assumedsize      = GuessSize(SampleCount),
             unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                              (SampleCount >> 10) + // 10 bytes header per 2048 sample points  
                                              8194,                 // at least one worst case sample frame  
939                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
940                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
941                            copysamples;                            copysamples, skipsamples,
942              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
943              this->FrameOffset = 0;              this->FrameOffset = 0;
944    
945              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
946                  // local buffer reallocation - hope this won't happen  
947                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
948                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
949                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
950                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
951                    remainingsamples = SampleCount;
952                    assumedsize      = GuessSize(SampleCount);
953              }              }
954    
955              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
956              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
957              int16_t* pDst = (int16_t*) pBuffer;              uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
958              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
959    
960              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
961                    unsigned long framesamples = SamplesPerFrame;
962                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
963                  if (remainingbytes < 8194) {  
964                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
965                          this->SamplePos = this->SamplesTotal;  
966                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
967                        mode_r = *pSrc++;
968                        framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
969                        rightChannelOffset = bytesPerFrameNoHdr[mode_l];
970                        nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
971                        if (remainingbytes < framebytes) { // last frame in sample
972                            framesamples = SamplesInLastFrame;
973                            if (mode_l == 4 && (framesamples & 1)) {
974                                rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
975                            }
976                            else {
977                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
978                            }
979                        }
980                    }
981                    else {
982                        framebytes = bytesPerFrame[mode_l] + 1;
983                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
984                        if (remainingbytes < framebytes) {
985                            framesamples = SamplesInLastFrame;
986                      }                      }
                     assumedsize    = remainingsamples;  
                     assumedsize    = (assumedsize << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                      (assumedsize >> 10) + // 10 bytes header per 2048 sample points  
                                      8194;                 // at least one worst case sample frame  
                     pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
                     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();  
                     remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);  
                     pSrc = (int8_t*) this->pDecompressionBuffer;  
987                  }                  }
988    
989                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
990                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
991                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
992                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
993                            skipsamples = currentframeoffset;
994                        }
995                        else {
996                            copysamples = 0;
997                            skipsamples = framesamples;
998                        }
999                  }                  }
1000                  else {                  else {
1001                        // This frame has enough data for pBuffer, but not
1002                        // all of the frame is needed. Set file position
1003                        // to start of this frame for next call to Read.
1004                      copysamples = remainingsamples;                      copysamples = remainingsamples;
1005                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
1006                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1007                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
1008                      }                  }
1009                      else {                  remainingsamples -= copysamples;
1010    
1011                    if (remainingbytes > framebytes) {
1012                        remainingbytes -= framebytes;
1013                        if (remainingsamples == 0 &&
1014                            currentframeoffset + copysamples == framesamples) {
1015                            // This frame has enough data for pBuffer, and
1016                            // all of the frame is needed. Set file
1017                            // position to start of next frame for next
1018                            // call to Read. FrameOffset is 0.
1019                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
1020                      }                      }
1021                  }                  }
1022                    else remainingbytes = 0;
1023    
1024                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
1025                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
1026                  switch (compressionmode) {                  if (copysamples == 0) {
1027                      case 1: // left channel compressed                      // skip this frame
1028                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
1029                          if (!remainingsamples && copysamples == 2048)                  }
1030                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
1031                        const unsigned char* const param_l = pSrc;
1032                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
1033                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
1034                          while (currentframeoffset) {  
1035                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
1036                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
1037                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
1038                              currentframeoffset--;  
1039                          }                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1040                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
1041                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1042                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
1043                              *pDst = left; pDst++;                              pDst24 += copysamples * 6;
                             *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;  
                             copysamples--;  
                         }  
                         break;  
                     case 256: // right channel compressed  
                         remainingbytes -= 6150; // (left 16 bit, right 8 bit, +6 byte header)  
                         if (!remainingsamples && copysamples == 2048)  
                             pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
   
                         right  = *(int16_t*)pSrc; pSrc+=2;  
                         dright = *(int16_t*)pSrc; pSrc+=2;  
                         if (currentframeoffset) {  
                             pSrc+=2; // skip uncompressed left channel, now we can increment by 3  
                             while (currentframeoffset) {  
                                 dright -= *pSrc;  
                                 right  -= dright;  
                                 pSrc+=3; // 8 bit right channel, skip uncompressed left channel (16 bit)  
                                 currentframeoffset--;  
                             }  
                             pSrc-=2; // back aligned to left channel  
1044                          }                          }
1045                          while (copysamples) {                          else { // Mono
1046                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1047                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
1048                              right  -= dright;                              pDst24 += copysamples * 3;
                             *pDst = right; pDst++;  
                             copysamples--;  
1049                          }                          }
1050                          break;                      }
1051                      case 257: // both channels compressed                      else { // 16 bit
1052                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
1053                          if (!remainingsamples && copysamples == 2048)  
1054                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
1055                            if (Channels == 2) { // Stereo
1056                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
1057                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
1058                          right  = *(int16_t*)pSrc; pSrc+=2;  
1059                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
1060                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1061                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1062                              left   -= dleft;                                           skipsamples, copysamples);
1063                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
1064                          }                          }
1065                          while (copysamples) {                          else { // Mono
1066                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
1067                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1068                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
1069                          }                          }
1070                          break;                      }
1071                      default: // both channels uncompressed                      pSrc += nextFrameOffset;
                         remainingbytes -= 8194; // (left 16 bit, right 16 bit, +2 byte header)  
                         if (!remainingsamples && copysamples == 2048)  
                             pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
   
                         pSrc += currentframeoffset << 2;  
                         currentframeoffset = 0;  
                         memcpy(pDst, pSrc, copysamples << 2);  
                         pDst += copysamples << 1;  
                         pSrc += copysamples << 2;  
                         break;  
1072                  }                  }
1073              }  
1074                    // reload from disk to local buffer if needed
1075                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1076                        assumedsize    = GuessSize(remainingsamples);
1077                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1078                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1079                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1080                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1081                    }
1082                } // while
1083    
1084              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
1085              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1086              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
1087          }          }
1088      }      }
1089    
1090        /** @brief Write sample wave data.
1091         *
1092         * Writes \a SampleCount number of sample points from the buffer pointed
1093         * by \a pBuffer and increments the position within the sample. Use this
1094         * method to directly write the sample data to disk, i.e. if you don't
1095         * want or cannot load the whole sample data into RAM.
1096         *
1097         * You have to Resize() the sample to the desired size and call
1098         * File::Save() <b>before</b> using Write().
1099         *
1100         * Note: there is currently no support for writing compressed samples.
1101         *
1102         * @param pBuffer     - source buffer
1103         * @param SampleCount - number of sample points to write
1104         * @throws DLS::Exception if current sample size is too small
1105         * @throws gig::Exception if sample is compressed
1106         * @see DLS::LoadSampleData()
1107         */
1108        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1109            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1110            return DLS::Sample::Write(pBuffer, SampleCount);
1111        }
1112    
1113        /**
1114         * Allocates a decompression buffer for streaming (compressed) samples
1115         * with Sample::Read(). If you are using more than one streaming thread
1116         * in your application you <b>HAVE</b> to create a decompression buffer
1117         * for <b>EACH</b> of your streaming threads and provide it with the
1118         * Sample::Read() call in order to avoid race conditions and crashes.
1119         *
1120         * You should free the memory occupied by the allocated buffer(s) once
1121         * you don't need one of your streaming threads anymore by calling
1122         * DestroyDecompressionBuffer().
1123         *
1124         * @param MaxReadSize - the maximum size (in sample points) you ever
1125         *                      expect to read with one Read() call
1126         * @returns allocated decompression buffer
1127         * @see DestroyDecompressionBuffer()
1128         */
1129        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1130            buffer_t result;
1131            const double worstCaseHeaderOverhead =
1132                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1133            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1134            result.pStart            = new int8_t[result.Size];
1135            result.NullExtensionSize = 0;
1136            return result;
1137        }
1138    
1139        /**
1140         * Free decompression buffer, previously created with
1141         * CreateDecompressionBuffer().
1142         *
1143         * @param DecompressionBuffer - previously allocated decompression
1144         *                              buffer to free
1145         */
1146        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1147            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1148                delete[] (int8_t*) DecompressionBuffer.pStart;
1149                DecompressionBuffer.pStart = NULL;
1150                DecompressionBuffer.Size   = 0;
1151                DecompressionBuffer.NullExtensionSize = 0;
1152            }
1153        }
1154    
1155        /**
1156         * Returns pointer to the Group this Sample belongs to. In the .gig
1157         * format a sample always belongs to one group. If it wasn't explicitly
1158         * assigned to a certain group, it will be automatically assigned to a
1159         * default group.
1160         *
1161         * @returns Sample's Group (never NULL)
1162         */
1163        Group* Sample::GetGroup() const {
1164            return pGroup;
1165        }
1166    
1167      Sample::~Sample() {      Sample::~Sample() {
1168          Instances--;          Instances--;
1169          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
1170                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1171                InternalDecompressionBuffer.pStart = NULL;
1172                InternalDecompressionBuffer.Size   = 0;
1173            }
1174          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1175          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1176      }      }
# Line 697  namespace gig { Line 1186  namespace gig {
1186      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1187          Instances++;          Instances++;
1188    
1189            pSample = NULL;
1190    
1191          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1192          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1193    
1194          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1195          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1196          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1197          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1198          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1199          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1200          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1201          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1202          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1203          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1204          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1205          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1206          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1207          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1208          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1210          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1211          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1212          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1213          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1214          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1215          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1216          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1217          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1218          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1219          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1220          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1221          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1222          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1223          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1224          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1225          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1226          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1227          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1228          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1229          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1230          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1231          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1232          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1233          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1234          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1235          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1236          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1237          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1238          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1239          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1240          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1241          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1242          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1243          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1244          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1245          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1246              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1247              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1248          }                  VelocityResponseDepth = velocityresponse;
1249          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1250              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1251              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1252          }              } else if (velocityresponse < 15) {
1253          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1254              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1255              VelocityResponseDepth = velocityresponse - 10;              } else {
1256                    VelocityResponseCurve = curve_type_unknown;
1257                    VelocityResponseDepth = 0;
1258                }
1259                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1260                if (releasevelocityresponse < 5) {
1261                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1262                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1263                } else if (releasevelocityresponse < 10) {
1264                    ReleaseVelocityResponseCurve = curve_type_linear;
1265                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1266                } else if (releasevelocityresponse < 15) {
1267                    ReleaseVelocityResponseCurve = curve_type_special;
1268                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1269                } else {
1270                    ReleaseVelocityResponseCurve = curve_type_unknown;
1271                    ReleaseVelocityResponseDepth = 0;
1272                }
1273                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1274                AttenuationControllerThreshold = _3ewa->ReadInt8();
1275                _3ewa->ReadInt32(); // unknown
1276                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1277                _3ewa->ReadInt16(); // unknown
1278                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1279                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1280                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1281                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1282                else                                       DimensionBypass = dim_bypass_ctrl_none;
1283                uint8_t pan = _3ewa->ReadUint8();
1284                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1285                SelfMask = _3ewa->ReadInt8() & 0x01;
1286                _3ewa->ReadInt8(); // unknown
1287                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1288                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1289                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1290                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1291                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1292                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1293                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1294                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1295                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1296                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1297                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1298                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1299                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1300                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1301                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1302                                                            : vcf_res_ctrl_none;
1303                uint16_t eg3depth = _3ewa->ReadUint16();
1304                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1305                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1306                _3ewa->ReadInt16(); // unknown
1307                ChannelOffset = _3ewa->ReadUint8() / 4;
1308                uint8_t regoptions = _3ewa->ReadUint8();
1309                MSDecode           = regoptions & 0x01; // bit 0
1310                SustainDefeat      = regoptions & 0x02; // bit 1
1311                _3ewa->ReadInt16(); // unknown
1312                VelocityUpperLimit = _3ewa->ReadInt8();
1313                _3ewa->ReadInt8(); // unknown
1314                _3ewa->ReadInt16(); // unknown
1315                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1316                _3ewa->ReadInt8(); // unknown
1317                _3ewa->ReadInt8(); // unknown
1318                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1319                uint8_t vcfcutoff = _3ewa->ReadUint8();
1320                VCFEnabled = vcfcutoff & 0x80; // bit 7
1321                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1322                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1323                uint8_t vcfvelscale = _3ewa->ReadUint8();
1324                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1325                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1326                _3ewa->ReadInt8(); // unknown
1327                uint8_t vcfresonance = _3ewa->ReadUint8();
1328                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1329                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1330                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1331                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1332                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1333                uint8_t vcfvelocity = _3ewa->ReadUint8();
1334                VCFVelocityDynamicRange = vcfvelocity % 5;
1335                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1336                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1337                if (VCFType == vcf_type_lowpass) {
1338                    if (lfo3ctrl & 0x40) // bit 6
1339                        VCFType = vcf_type_lowpassturbo;
1340                }
1341                if (_3ewa->RemainingBytes() >= 8) {
1342                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1343                } else {
1344                    memset(DimensionUpperLimits, 0, 8);
1345                }
1346            } else { // '3ewa' chunk does not exist yet
1347                // use default values
1348                LFO3Frequency                   = 1.0;
1349                EG3Attack                       = 0.0;
1350                LFO1InternalDepth               = 0;
1351                LFO3InternalDepth               = 0;
1352                LFO1ControlDepth                = 0;
1353                LFO3ControlDepth                = 0;
1354                EG1Attack                       = 0.0;
1355                EG1Decay1                       = 0.0;
1356                EG1Sustain                      = 0;
1357                EG1Release                      = 0.0;
1358                EG1Controller.type              = eg1_ctrl_t::type_none;
1359                EG1Controller.controller_number = 0;
1360                EG1ControllerInvert             = false;
1361                EG1ControllerAttackInfluence    = 0;
1362                EG1ControllerDecayInfluence     = 0;
1363                EG1ControllerReleaseInfluence   = 0;
1364                EG2Controller.type              = eg2_ctrl_t::type_none;
1365                EG2Controller.controller_number = 0;
1366                EG2ControllerInvert             = false;
1367                EG2ControllerAttackInfluence    = 0;
1368                EG2ControllerDecayInfluence     = 0;
1369                EG2ControllerReleaseInfluence   = 0;
1370                LFO1Frequency                   = 1.0;
1371                EG2Attack                       = 0.0;
1372                EG2Decay1                       = 0.0;
1373                EG2Sustain                      = 0;
1374                EG2Release                      = 0.0;
1375                LFO2ControlDepth                = 0;
1376                LFO2Frequency                   = 1.0;
1377                LFO2InternalDepth               = 0;
1378                EG1Decay2                       = 0.0;
1379                EG1InfiniteSustain              = false;
1380                EG1PreAttack                    = 1000;
1381                EG2Decay2                       = 0.0;
1382                EG2InfiniteSustain              = false;
1383                EG2PreAttack                    = 1000;
1384                VelocityResponseCurve           = curve_type_nonlinear;
1385                VelocityResponseDepth           = 3;
1386                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1387                ReleaseVelocityResponseDepth    = 3;
1388                VelocityResponseCurveScaling    = 32;
1389                AttenuationControllerThreshold  = 0;
1390                SampleStartOffset               = 0;
1391                PitchTrack                      = true;
1392                DimensionBypass                 = dim_bypass_ctrl_none;
1393                Pan                             = 0;
1394                SelfMask                        = true;
1395                LFO3Controller                  = lfo3_ctrl_modwheel;
1396                LFO3Sync                        = false;
1397                InvertAttenuationController     = false;
1398                AttenuationController.type      = attenuation_ctrl_t::type_none;
1399                AttenuationController.controller_number = 0;
1400                LFO2Controller                  = lfo2_ctrl_internal;
1401                LFO2FlipPhase                   = false;
1402                LFO2Sync                        = false;
1403                LFO1Controller                  = lfo1_ctrl_internal;
1404                LFO1FlipPhase                   = false;
1405                LFO1Sync                        = false;
1406                VCFResonanceController          = vcf_res_ctrl_none;
1407                EG3Depth                        = 0;
1408                ChannelOffset                   = 0;
1409                MSDecode                        = false;
1410                SustainDefeat                   = false;
1411                VelocityUpperLimit              = 0;
1412                ReleaseTriggerDecay             = 0;
1413                EG1Hold                         = false;
1414                VCFEnabled                      = false;
1415                VCFCutoff                       = 0;
1416                VCFCutoffController             = vcf_cutoff_ctrl_none;
1417                VCFCutoffControllerInvert       = false;
1418                VCFVelocityScale                = 0;
1419                VCFResonance                    = 0;
1420                VCFResonanceDynamic             = false;
1421                VCFKeyboardTracking             = false;
1422                VCFKeyboardTrackingBreakpoint   = 0;
1423                VCFVelocityDynamicRange         = 0x04;
1424                VCFVelocityCurve                = curve_type_linear;
1425                VCFType                         = vcf_type_lowpass;
1426                memset(DimensionUpperLimits, 0, 8);
1427            }
1428    
1429            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1430                                                         VelocityResponseDepth,
1431                                                         VelocityResponseCurveScaling);
1432    
1433            curve_type_t curveType = ReleaseVelocityResponseCurve;
1434            uint8_t depth = ReleaseVelocityResponseDepth;
1435    
1436            // this models a strange behaviour or bug in GSt: two of the
1437            // velocity response curves for release time are not used even
1438            // if specified, instead another curve is chosen.
1439            if ((curveType == curve_type_nonlinear && depth == 0) ||
1440                (curveType == curve_type_special   && depth == 4)) {
1441                curveType = curve_type_nonlinear;
1442                depth = 3;
1443            }
1444            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1445    
1446            curveType = VCFVelocityCurve;
1447            depth = VCFVelocityDynamicRange;
1448    
1449            // even stranger GSt: two of the velocity response curves for
1450            // filter cutoff are not used, instead another special curve
1451            // is chosen. This curve is not used anywhere else.
1452            if ((curveType == curve_type_nonlinear && depth == 0) ||
1453                (curveType == curve_type_special   && depth == 4)) {
1454                curveType = curve_type_special;
1455                depth = 5;
1456          }          }
1457          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1458              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1459              VelocityResponseDepth = 0;  
1460            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1461            VelocityTable = 0;
1462        }
1463    
1464        /**
1465         * Apply dimension region settings to the respective RIFF chunks. You
1466         * have to call File::Save() to make changes persistent.
1467         *
1468         * Usually there is absolutely no need to call this method explicitly.
1469         * It will be called automatically when File::Save() was called.
1470         */
1471        void DimensionRegion::UpdateChunks() {
1472            // first update base class's chunk
1473            DLS::Sampler::UpdateChunks();
1474    
1475            // make sure '3ewa' chunk exists
1476            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1477            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1478            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1479    
1480            // update '3ewa' chunk with DimensionRegion's current settings
1481    
1482            const uint32_t chunksize = _3ewa->GetSize();
1483            memcpy(&pData[0], &chunksize, 4); // unknown, always chunk size?
1484    
1485            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1486            memcpy(&pData[4], &lfo3freq, 4);
1487    
1488            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1489            memcpy(&pData[8], &eg3attack, 4);
1490    
1491            // next 2 bytes unknown
1492    
1493            memcpy(&pData[14], &LFO1InternalDepth, 2);
1494    
1495            // next 2 bytes unknown
1496    
1497            memcpy(&pData[18], &LFO3InternalDepth, 2);
1498    
1499            // next 2 bytes unknown
1500    
1501            memcpy(&pData[22], &LFO1ControlDepth, 2);
1502    
1503            // next 2 bytes unknown
1504    
1505            memcpy(&pData[26], &LFO3ControlDepth, 2);
1506    
1507            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1508            memcpy(&pData[28], &eg1attack, 4);
1509    
1510            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1511            memcpy(&pData[32], &eg1decay1, 4);
1512    
1513            // next 2 bytes unknown
1514    
1515            memcpy(&pData[38], &EG1Sustain, 2);
1516    
1517            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1518            memcpy(&pData[40], &eg1release, 4);
1519    
1520            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1521            memcpy(&pData[44], &eg1ctl, 1);
1522    
1523            const uint8_t eg1ctrloptions =
1524                (EG1ControllerInvert) ? 0x01 : 0x00 |
1525                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1526                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1527                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1528            memcpy(&pData[45], &eg1ctrloptions, 1);
1529    
1530            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1531            memcpy(&pData[46], &eg2ctl, 1);
1532    
1533            const uint8_t eg2ctrloptions =
1534                (EG2ControllerInvert) ? 0x01 : 0x00 |
1535                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1536                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1537                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1538            memcpy(&pData[47], &eg2ctrloptions, 1);
1539    
1540            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1541            memcpy(&pData[48], &lfo1freq, 4);
1542    
1543            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1544            memcpy(&pData[52], &eg2attack, 4);
1545    
1546            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1547            memcpy(&pData[56], &eg2decay1, 4);
1548    
1549            // next 2 bytes unknown
1550    
1551            memcpy(&pData[62], &EG2Sustain, 2);
1552    
1553            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1554            memcpy(&pData[64], &eg2release, 4);
1555    
1556            // next 2 bytes unknown
1557    
1558            memcpy(&pData[70], &LFO2ControlDepth, 2);
1559    
1560            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1561            memcpy(&pData[72], &lfo2freq, 4);
1562    
1563            // next 2 bytes unknown
1564    
1565            memcpy(&pData[78], &LFO2InternalDepth, 2);
1566    
1567            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1568            memcpy(&pData[80], &eg1decay2, 4);
1569    
1570            // next 2 bytes unknown
1571    
1572            memcpy(&pData[86], &EG1PreAttack, 2);
1573    
1574            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1575            memcpy(&pData[88], &eg2decay2, 4);
1576    
1577            // next 2 bytes unknown
1578    
1579            memcpy(&pData[94], &EG2PreAttack, 2);
1580    
1581            {
1582                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1583                uint8_t velocityresponse = VelocityResponseDepth;
1584                switch (VelocityResponseCurve) {
1585                    case curve_type_nonlinear:
1586                        break;
1587                    case curve_type_linear:
1588                        velocityresponse += 5;
1589                        break;
1590                    case curve_type_special:
1591                        velocityresponse += 10;
1592                        break;
1593                    case curve_type_unknown:
1594                    default:
1595                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1596                }
1597                memcpy(&pData[96], &velocityresponse, 1);
1598          }          }
1599          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1600          if (releasevelocityresponse < 5) {          {
1601              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1602              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1603          }              switch (ReleaseVelocityResponseCurve) {
1604          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1605              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1606              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1607          }                      releasevelocityresponse += 5;
1608          else if (releasevelocityresponse < 15) {                      break;
1609              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1610              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1611                        break;
1612                    case curve_type_unknown:
1613                    default:
1614                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1615                }
1616                memcpy(&pData[97], &releasevelocityresponse, 1);
1617          }          }
1618          else {  
1619              ReleaseVelocityResponseCurve = curve_type_unknown;          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);
1620              ReleaseVelocityResponseDepth = 0;  
1621            memcpy(&pData[99], &AttenuationControllerThreshold, 1);
1622    
1623            // next 4 bytes unknown
1624    
1625            memcpy(&pData[104], &SampleStartOffset, 2);
1626    
1627            // next 2 bytes unknown
1628    
1629            {
1630                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1631                switch (DimensionBypass) {
1632                    case dim_bypass_ctrl_94:
1633                        pitchTrackDimensionBypass |= 0x10;
1634                        break;
1635                    case dim_bypass_ctrl_95:
1636                        pitchTrackDimensionBypass |= 0x20;
1637                        break;
1638                    case dim_bypass_ctrl_none:
1639                        //FIXME: should we set anything here?
1640                        break;
1641                    default:
1642                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1643                }
1644                memcpy(&pData[108], &pitchTrackDimensionBypass, 1);
1645            }
1646    
1647            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1648            memcpy(&pData[109], &pan, 1);
1649    
1650            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1651            memcpy(&pData[110], &selfmask, 1);
1652    
1653            // next byte unknown
1654    
1655            {
1656                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1657                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1658                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1659                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1660                memcpy(&pData[112], &lfo3ctrl, 1);
1661            }
1662    
1663            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1664            memcpy(&pData[113], &attenctl, 1);
1665    
1666            {
1667                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1668                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1669                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1670                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1671                memcpy(&pData[114], &lfo2ctrl, 1);
1672            }
1673    
1674            {
1675                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1676                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1677                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1678                if (VCFResonanceController != vcf_res_ctrl_none)
1679                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1680                memcpy(&pData[115], &lfo1ctrl, 1);
1681            }
1682    
1683            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1684                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1685            memcpy(&pData[116], &eg3depth, 1);
1686    
1687            // next 2 bytes unknown
1688    
1689            const uint8_t channeloffset = ChannelOffset * 4;
1690            memcpy(&pData[120], &channeloffset, 1);
1691    
1692            {
1693                uint8_t regoptions = 0;
1694                if (MSDecode)      regoptions |= 0x01; // bit 0
1695                if (SustainDefeat) regoptions |= 0x02; // bit 1
1696                memcpy(&pData[121], &regoptions, 1);
1697          }          }
1698          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1699          AttenuationControllerThreshold = _3ewa->ReadInt8();          // next 2 bytes unknown
1700          _3ewa->ReadInt32(); // unknown  
1701          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();          memcpy(&pData[124], &VelocityUpperLimit, 1);
1702          _3ewa->ReadInt16(); // unknown  
1703          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          // next 3 bytes unknown
1704          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1705          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          memcpy(&pData[128], &ReleaseTriggerDecay, 1);
1706          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1707          else                                       DimensionBypass = dim_bypass_ctrl_none;          // next 2 bytes unknown
1708          uint8_t pan = _3ewa->ReadUint8();  
1709          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1710          SelfMask = _3ewa->ReadInt8() & 0x01;          memcpy(&pData[131], &eg1hold, 1);
1711          _3ewa->ReadInt8(); // unknown  
1712          uint8_t lfo3ctrl = _3ewa->ReadUint8();          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1713          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1714          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5          memcpy(&pData[132], &vcfcutoff, 1);
1715          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
1716          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          memcpy(&pData[133], &VCFCutoffController, 1);
1717          uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
1718          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1719          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1720          LFO2Sync               = lfo2ctrl & 0x20; // bit 5          memcpy(&pData[134], &vcfvelscale, 1);
1721          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
1722          uint8_t lfo1ctrl       = _3ewa->ReadUint8();          // next byte unknown
1723          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
1724          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1725          LFO1Sync               = lfo1ctrl & 0x40; // bit 6                                       (VCFResonance & 0x7f); /* lower 7 bits */
1726          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))          memcpy(&pData[136], &vcfresonance, 1);
1727                                                      : vcf_res_ctrl_none;  
1728          uint16_t eg3depth = _3ewa->ReadUint16();          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1729          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1730                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */          memcpy(&pData[137], &vcfbreakpoint, 1);
1731          _3ewa->ReadInt16(); // unknown  
1732          ChannelOffset = _3ewa->ReadUint8() / 4;          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1733          uint8_t regoptions = _3ewa->ReadUint8();                                      VCFVelocityCurve * 5;
1734          MSDecode           = regoptions & 0x01; // bit 0          memcpy(&pData[138], &vcfvelocity, 1);
1735          SustainDefeat      = regoptions & 0x02; // bit 1  
1736          _3ewa->ReadInt16(); // unknown          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1737          VelocityUpperLimit = _3ewa->ReadInt8();          memcpy(&pData[139], &vcftype, 1);
1738          _3ewa->ReadInt8(); // unknown  
1739          _3ewa->ReadInt16(); // unknown          if (chunksize >= 148) {
1740          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay              memcpy(&pData[140], DimensionUpperLimits, 8);
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
1741          }          }
1742        }
1743    
1744          // get the corresponding velocity->volume 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
1745          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1746        {
1747            double* table;
1748            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1749          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1750              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1751          }          }
1752          else {          else {
1753              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1754                  CreateVelocityTable(VelocityResponseCurve,              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
                                     VelocityResponseDepth,  
                                     VelocityResponseCurveScaling);  
             (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map  
1755          }          }
1756            return table;
1757      }      }
1758    
1759      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 983  namespace gig { Line 1874  namespace gig {
1874          return decodedcontroller;          return decodedcontroller;
1875      }      }
1876    
1877        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1878            _lev_ctrl_t encodedcontroller;
1879            switch (DecodedController.type) {
1880                // special controller
1881                case leverage_ctrl_t::type_none:
1882                    encodedcontroller = _lev_ctrl_none;
1883                    break;
1884                case leverage_ctrl_t::type_velocity:
1885                    encodedcontroller = _lev_ctrl_velocity;
1886                    break;
1887                case leverage_ctrl_t::type_channelaftertouch:
1888                    encodedcontroller = _lev_ctrl_channelaftertouch;
1889                    break;
1890    
1891                // ordinary MIDI control change controller
1892                case leverage_ctrl_t::type_controlchange:
1893                    switch (DecodedController.controller_number) {
1894                        case 1:
1895                            encodedcontroller = _lev_ctrl_modwheel;
1896                            break;
1897                        case 2:
1898                            encodedcontroller = _lev_ctrl_breath;
1899                            break;
1900                        case 4:
1901                            encodedcontroller = _lev_ctrl_foot;
1902                            break;
1903                        case 12:
1904                            encodedcontroller = _lev_ctrl_effect1;
1905                            break;
1906                        case 13:
1907                            encodedcontroller = _lev_ctrl_effect2;
1908                            break;
1909                        case 16:
1910                            encodedcontroller = _lev_ctrl_genpurpose1;
1911                            break;
1912                        case 17:
1913                            encodedcontroller = _lev_ctrl_genpurpose2;
1914                            break;
1915                        case 18:
1916                            encodedcontroller = _lev_ctrl_genpurpose3;
1917                            break;
1918                        case 19:
1919                            encodedcontroller = _lev_ctrl_genpurpose4;
1920                            break;
1921                        case 5:
1922                            encodedcontroller = _lev_ctrl_portamentotime;
1923                            break;
1924                        case 64:
1925                            encodedcontroller = _lev_ctrl_sustainpedal;
1926                            break;
1927                        case 65:
1928                            encodedcontroller = _lev_ctrl_portamento;
1929                            break;
1930                        case 66:
1931                            encodedcontroller = _lev_ctrl_sostenutopedal;
1932                            break;
1933                        case 67:
1934                            encodedcontroller = _lev_ctrl_softpedal;
1935                            break;
1936                        case 80:
1937                            encodedcontroller = _lev_ctrl_genpurpose5;
1938                            break;
1939                        case 81:
1940                            encodedcontroller = _lev_ctrl_genpurpose6;
1941                            break;
1942                        case 82:
1943                            encodedcontroller = _lev_ctrl_genpurpose7;
1944                            break;
1945                        case 83:
1946                            encodedcontroller = _lev_ctrl_genpurpose8;
1947                            break;
1948                        case 91:
1949                            encodedcontroller = _lev_ctrl_effect1depth;
1950                            break;
1951                        case 92:
1952                            encodedcontroller = _lev_ctrl_effect2depth;
1953                            break;
1954                        case 93:
1955                            encodedcontroller = _lev_ctrl_effect3depth;
1956                            break;
1957                        case 94:
1958                            encodedcontroller = _lev_ctrl_effect4depth;
1959                            break;
1960                        case 95:
1961                            encodedcontroller = _lev_ctrl_effect5depth;
1962                            break;
1963                        default:
1964                            throw gig::Exception("leverage controller number is not supported by the gig format");
1965                    }
1966                default:
1967                    throw gig::Exception("Unknown leverage controller type.");
1968            }
1969            return encodedcontroller;
1970        }
1971    
1972      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1973          Instances--;          Instances--;
1974          if (!Instances) {          if (!Instances) {
# Line 996  namespace gig { Line 1982  namespace gig {
1982              delete pVelocityTables;              delete pVelocityTables;
1983              pVelocityTables = NULL;              pVelocityTables = NULL;
1984          }          }
1985            if (VelocityTable) delete[] VelocityTable;
1986      }      }
1987    
1988      /**      /**
# Line 1013  namespace gig { Line 2000  namespace gig {
2000          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
2001      }      }
2002    
2003        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2004            return pVelocityReleaseTable[MIDIKeyVelocity];
2005        }
2006    
2007        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2008            return pVelocityCutoffTable[MIDIKeyVelocity];
2009        }
2010    
2011      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) {
2012    
2013          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1046  namespace gig { Line 2041  namespace gig {
2041          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2042                               127, 127 };                               127, 127 };
2043    
2044            // this is only used by the VCF velocity curve
2045            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2046                                 91, 127, 127, 127 };
2047    
2048          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2049                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2050                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2051    
2052          double* const table = new double[128];          double* const table = new double[128];
2053    
# Line 1081  namespace gig { Line 2080  namespace gig {
2080  // *  // *
2081    
2082      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2083            pInfo->UseFixedLengthStrings = true;
2084    
2085          // Initialization          // Initialization
2086          Dimensions = 0;          Dimensions = 0;
2087          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 1100  namespace gig { Line 2101  namespace gig {
2101              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2102                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2103                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2104                    _3lnk->ReadUint8(); // probably the position of the dimension
2105                    _3lnk->ReadUint8(); // unknown
2106                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2107                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2108                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2109                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2110                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2111                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2112                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2113                  }                  }
2114                  else { // active dimension                  else { // active dimension
2115                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2116                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2117                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2118                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2119                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2120                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
2121                                                                                                    : split_type_normal;                                                             dimension == dimension_keyboard ||
2122                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point                                                             dimension == dimension_roundrobin ||
2123                                                               dimension == dimension_random ||
2124                                                               dimension == dimension_smartmidi ||
2125                                                               dimension == dimension_roundrobinkeyboard) ? split_type_bit
2126                                                                                                          : split_type_normal;
2127                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2128                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2129                                                                                     : 0;                                                                                     : 0;
2130                      Dimensions++;                      Dimensions++;
2131    
2132                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2133                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2134                  }                  }
2135                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2136              }              }
2137                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2138    
2139              // check velocity dimension (if there is one) for custom defined zone ranges              // if there's a velocity dimension and custom velocity zone splits are used,
2140              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2141                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
                 if (pDimDef->dimension == dimension_velocity) {  
                     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {  
                         // no custom defined ranges  
                         pDimDef->split_type = split_type_normal;  
                         pDimDef->ranges     = NULL;  
                     }  
                     else { // custom defined ranges  
                         pDimDef->split_type = split_type_customvelocity;  
                         pDimDef->ranges     = new range_t[pDimDef->zones];  
                         uint8_t bits[8] = { 0 };  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);  
   
                             pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;  
                             pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;  
                             previousUpperLimit = pDimDef->ranges[velocityZone].high;  
                             // fill velocity table  
                             for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {  
                                 VelocityTable[i] = velocityZone;  
                             }  
                         }  
                     }  
                 }  
             }  
2142    
2143              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
             File* file = (File*) GetParent()->GetParent();  
2144              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2145                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2146              else              else
# Line 1168  namespace gig { Line 2149  namespace gig {
2149              // load sample references              // load sample references
2150              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2151                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2152                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2153              }              }
2154                GetSample(); // load global region sample reference
2155            }
2156    
2157            // make sure there is at least one dimension region
2158            if (!DimensionRegions) {
2159                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2160                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2161                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2162                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2163                DimensionRegions = 1;
2164            }
2165        }
2166    
2167        /**
2168         * Apply Region settings and all its DimensionRegions to the respective
2169         * RIFF chunks. You have to call File::Save() to make changes persistent.
2170         *
2171         * Usually there is absolutely no need to call this method explicitly.
2172         * It will be called automatically when File::Save() was called.
2173         *
2174         * @throws gig::Exception if samples cannot be dereferenced
2175         */
2176        void Region::UpdateChunks() {
2177            // first update base class's chunks
2178            DLS::Region::UpdateChunks();
2179    
2180            // update dimension region's chunks
2181            for (int i = 0; i < DimensionRegions; i++) {
2182                pDimensionRegions[i]->UpdateChunks();
2183            }
2184    
2185            File* pFile = (File*) GetParent()->GetParent();
2186            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2187            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2188    
2189            // make sure '3lnk' chunk exists
2190            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2191            if (!_3lnk) {
2192                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2193                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2194            }
2195    
2196            // update dimension definitions in '3lnk' chunk
2197            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2198            memcpy(&pData[0], &DimensionRegions, 4);
2199            for (int i = 0; i < iMaxDimensions; i++) {
2200                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2201                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2202                // next 2 bytes unknown
2203                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2204                // next 3 bytes unknown
2205            }
2206    
2207            // update wave pool table in '3lnk' chunk
2208            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2209            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2210                int iWaveIndex = -1;
2211                if (i < DimensionRegions) {
2212                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2213                    File::SampleList::iterator iter = pFile->pSamples->begin();
2214                    File::SampleList::iterator end  = pFile->pSamples->end();
2215                    for (int index = 0; iter != end; ++iter, ++index) {
2216                        if (*iter == pDimensionRegions[i]->pSample) {
2217                            iWaveIndex = index;
2218                            break;
2219                        }
2220                    }
2221                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2222                }
2223                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2224          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2225      }      }
2226    
2227      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1190  namespace gig { Line 2240  namespace gig {
2240          }          }
2241      }      }
2242    
2243      Region::~Region() {      void Region::UpdateVelocityTable() {
2244          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2245              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2246            for (int i = 0 ; i < Dimensions ; i++) {
2247                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2248                    veldim = i;
2249                    break;
2250                }
2251          }          }
2252            if (veldim == -1) return;
2253    
2254            int step = 1;
2255            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2256            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2257            int end = step * pDimensionDefinitions[veldim].zones;
2258    
2259            // loop through all dimension regions for all dimensions except the velocity dimension
2260            int dim[8] = { 0 };
2261            for (int i = 0 ; i < DimensionRegions ; i++) {
2262    
2263                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2264                    pDimensionRegions[i]->VelocityUpperLimit) {
2265                    // create the velocity table
2266                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2267                    if (!table) {
2268                        table = new uint8_t[128];
2269                        pDimensionRegions[i]->VelocityTable = table;
2270                    }
2271                    int tableidx = 0;
2272                    int velocityZone = 0;
2273                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2274                        for (int k = i ; k < end ; k += step) {
2275                            DimensionRegion *d = pDimensionRegions[k];
2276                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2277                            velocityZone++;
2278                        }
2279                    } else { // gig2
2280                        for (int k = i ; k < end ; k += step) {
2281                            DimensionRegion *d = pDimensionRegions[k];
2282                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2283                            velocityZone++;
2284                        }
2285                    }
2286                } else {
2287                    if (pDimensionRegions[i]->VelocityTable) {
2288                        delete[] pDimensionRegions[i]->VelocityTable;
2289                        pDimensionRegions[i]->VelocityTable = 0;
2290                    }
2291                }
2292    
2293                int j;
2294                int shift = 0;
2295                for (j = 0 ; j < Dimensions ; j++) {
2296                    if (j == veldim) i += skipveldim; // skip velocity dimension
2297                    else {
2298                        dim[j]++;
2299                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2300                        else {
2301                            // skip unused dimension regions
2302                            dim[j] = 0;
2303                            i += ((1 << pDimensionDefinitions[j].bits) -
2304                                  pDimensionDefinitions[j].zones) << shift;
2305                        }
2306                    }
2307                    shift += pDimensionDefinitions[j].bits;
2308                }
2309                if (j == Dimensions) break;
2310            }
2311        }
2312    
2313        /** @brief Einstein would have dreamed of it - create a new dimension.
2314         *
2315         * Creates a new dimension with the dimension definition given by
2316         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2317         * There is a hard limit of dimensions and total amount of "bits" all
2318         * dimensions can have. This limit is dependant to what gig file format
2319         * version this file refers to. The gig v2 (and lower) format has a
2320         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2321         * format has a limit of 8.
2322         *
2323         * @param pDimDef - defintion of the new dimension
2324         * @throws gig::Exception if dimension of the same type exists already
2325         * @throws gig::Exception if amount of dimensions or total amount of
2326         *                        dimension bits limit is violated
2327         */
2328        void Region::AddDimension(dimension_def_t* pDimDef) {
2329            // check if max. amount of dimensions reached
2330            File* file = (File*) GetParent()->GetParent();
2331            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2332            if (Dimensions >= iMaxDimensions)
2333                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2334            // check if max. amount of dimension bits reached
2335            int iCurrentBits = 0;
2336            for (int i = 0; i < Dimensions; i++)
2337                iCurrentBits += pDimensionDefinitions[i].bits;
2338            if (iCurrentBits >= iMaxDimensions)
2339                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2340            const int iNewBits = iCurrentBits + pDimDef->bits;
2341            if (iNewBits > iMaxDimensions)
2342                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2343            // check if there's already a dimensions of the same type
2344            for (int i = 0; i < Dimensions; i++)
2345                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2346                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2347    
2348            // assign definition of new dimension
2349            pDimensionDefinitions[Dimensions] = *pDimDef;
2350    
2351            // create new dimension region(s) for this new dimension
2352            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2353                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2354                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2355                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2356                DimensionRegions++;
2357            }
2358    
2359            Dimensions++;
2360    
2361            // if this is a layer dimension, update 'Layers' attribute
2362            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2363    
2364            UpdateVelocityTable();
2365        }
2366    
2367        /** @brief Delete an existing dimension.
2368         *
2369         * Deletes the dimension given by \a pDimDef and deletes all respective
2370         * dimension regions, that is all dimension regions where the dimension's
2371         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2372         * for example this would delete all dimension regions for the case(s)
2373         * where the sustain pedal is pressed down.
2374         *
2375         * @param pDimDef - dimension to delete
2376         * @throws gig::Exception if given dimension cannot be found
2377         */
2378        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2379            // get dimension's index
2380            int iDimensionNr = -1;
2381            for (int i = 0; i < Dimensions; i++) {
2382                if (&pDimensionDefinitions[i] == pDimDef) {
2383                    iDimensionNr = i;
2384                    break;
2385                }
2386            }
2387            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2388    
2389            // get amount of bits below the dimension to delete
2390            int iLowerBits = 0;
2391            for (int i = 0; i < iDimensionNr; i++)
2392                iLowerBits += pDimensionDefinitions[i].bits;
2393    
2394            // get amount ot bits above the dimension to delete
2395            int iUpperBits = 0;
2396            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2397                iUpperBits += pDimensionDefinitions[i].bits;
2398    
2399            // delete dimension regions which belong to the given dimension
2400            // (that is where the dimension's bit > 0)
2401            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2402                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2403                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2404                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2405                                        iObsoleteBit << iLowerBits |
2406                                        iLowerBit;
2407                        delete pDimensionRegions[iToDelete];
2408                        pDimensionRegions[iToDelete] = NULL;
2409                        DimensionRegions--;
2410                    }
2411                }
2412            }
2413    
2414            // defrag pDimensionRegions array
2415            // (that is remove the NULL spaces within the pDimensionRegions array)
2416            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2417                if (!pDimensionRegions[iTo]) {
2418                    if (iFrom <= iTo) iFrom = iTo + 1;
2419                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2420                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2421                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2422                        pDimensionRegions[iFrom] = NULL;
2423                    }
2424                }
2425            }
2426    
2427            // 'remove' dimension definition
2428            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2429                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2430            }
2431            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2432            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2433            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2434    
2435            Dimensions--;
2436    
2437            // if this was a layer dimension, update 'Layers' attribute
2438            if (pDimDef->dimension == dimension_layer) Layers = 1;
2439        }
2440    
2441        Region::~Region() {
2442          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2443              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2444          }          }
# Line 1218  namespace gig { Line 2463  namespace gig {
2463       * @see             Dimensions       * @see             Dimensions
2464       */       */
2465      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2466          uint8_t bits[8] = { 0 };          uint8_t bits;
2467            int veldim = -1;
2468            int velbitpos;
2469            int bitpos = 0;
2470            int dimregidx = 0;
2471          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2472              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2473              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2474                  case split_type_normal:                  veldim = i;
2475                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2476                      break;              } else {
2477                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2478                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2479                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2480                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2481                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2482                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2483                      break;                              }
2484                            } else {
2485                                // gig2: evenly sized zones
2486                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2487                            }
2488                            break;
2489                        case split_type_bit: // the value is already the sought dimension bit number
2490                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2491                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2492                            break;
2493                    }
2494                    dimregidx |= bits << bitpos;
2495              }              }
2496                bitpos += pDimensionDefinitions[i].bits;
2497            }
2498            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2499            if (veldim != -1) {
2500                // (dimreg is now the dimension region for the lowest velocity)
2501                if (dimreg->VelocityTable) // custom defined zone ranges
2502                    bits = dimreg->VelocityTable[DimValues[veldim]];
2503                else // normal split type
2504                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2505    
2506                dimregidx |= bits << velbitpos;
2507                dimreg = pDimensionRegions[dimregidx];
2508          }          }
2509          return GetDimensionRegionByBit(bits);          return dimreg;
2510      }      }
2511    
2512      /**      /**
# Line 1271  namespace gig { Line 2543  namespace gig {
2543          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2544      }      }
2545    
2546      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2547          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2548          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2549            if (!file->pWavePoolTable) return NULL;
2550          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2551          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2552            Sample* sample = file->GetFirstSample(pProgress);
2553          while (sample) {          while (sample) {
2554              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2555                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2556              sample = file->GetNextSample();              sample = file->GetNextSample();
2557          }          }
2558          return NULL;          return NULL;
# Line 1288  namespace gig { Line 2563  namespace gig {
2563  // *************** Instrument ***************  // *************** Instrument ***************
2564  // *  // *
2565    
2566      Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2567            pInfo->UseFixedLengthStrings = true;
2568    
2569          // Initialization          // Initialization
2570          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2571    
2572          // Loading          // Loading
2573          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1307  namespace gig { Line 2583  namespace gig {
2583                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2584                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2585              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2586          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2587    
2588            if (!pRegions) pRegions = new RegionList;
2589          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2590          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2591          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2592          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2593          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2594          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2595          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2596              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2597                  pRegions[iRegion] = new Region(this, rgn);                  rgn = lrgn->GetNextSubList();
                 iRegion++;  
             }  
             rgn = lrgn->GetNextSubList();  
         }  
   
         // Creating Region Key Table for fast lookup  
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
2598              }              }
2599                // Creating Region Key Table for fast lookup
2600                UpdateRegionKeyTable();
2601          }          }
2602    
2603            __notify_progress(pProgress, 1.0f); // notify done
2604      }      }
2605    
2606      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2607          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2608              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2609                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2610                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2611                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2612                    RegionKeyTable[iKey] = pRegion;
2613              }              }
2614          }          }
2615          if (pRegions) delete[] pRegions;      }
2616    
2617        Instrument::~Instrument() {
2618        }
2619    
2620        /**
2621         * Apply Instrument with all its Regions to the respective RIFF chunks.
2622         * You have to call File::Save() to make changes persistent.
2623         *
2624         * Usually there is absolutely no need to call this method explicitly.
2625         * It will be called automatically when File::Save() was called.
2626         *
2627         * @throws gig::Exception if samples cannot be dereferenced
2628         */
2629        void Instrument::UpdateChunks() {
2630            // first update base classes' chunks
2631            DLS::Instrument::UpdateChunks();
2632    
2633            // update Regions' chunks
2634            {
2635                RegionList::iterator iter = pRegions->begin();
2636                RegionList::iterator end  = pRegions->end();
2637                for (; iter != end; ++iter)
2638                    (*iter)->UpdateChunks();
2639            }
2640    
2641            // make sure 'lart' RIFF list chunk exists
2642            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2643            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2644            // make sure '3ewg' RIFF chunk exists
2645            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2646            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2647            // update '3ewg' RIFF chunk
2648            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2649            memcpy(&pData[0], &EffectSend, 2);
2650            memcpy(&pData[2], &Attenuation, 4);
2651            memcpy(&pData[6], &FineTune, 2);
2652            memcpy(&pData[8], &PitchbendRange, 2);
2653            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2654                                        DimensionKeyRange.low << 1;
2655            memcpy(&pData[10], &dimkeystart, 1);
2656            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2657      }      }
2658    
2659      /**      /**
# Line 1350  namespace gig { Line 2664  namespace gig {
2664       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2665       */       */
2666      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2667          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2668          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2669    
2670          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2671              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2672                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1367  namespace gig { Line 2682  namespace gig {
2682       * @see      GetNextRegion()       * @see      GetNextRegion()
2683       */       */
2684      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2685          if (!Regions) return NULL;          if (!pRegions) return NULL;
2686          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2687          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2688      }      }
2689    
2690      /**      /**
# Line 1381  namespace gig { Line 2696  namespace gig {
2696       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2697       */       */
2698      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2699          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (!pRegions) return NULL;
2700          return pRegions[RegionIndex++];          RegionsIterator++;
2701            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2702        }
2703    
2704        Region* Instrument::AddRegion() {
2705            // create new Region object (and its RIFF chunks)
2706            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2707            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2708            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2709            Region* pNewRegion = new Region(this, rgn);
2710            pRegions->push_back(pNewRegion);
2711            Regions = pRegions->size();
2712            // update Region key table for fast lookup
2713            UpdateRegionKeyTable();
2714            // done
2715            return pNewRegion;
2716        }
2717    
2718        void Instrument::DeleteRegion(Region* pRegion) {
2719            if (!pRegions) return;
2720            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2721            // update Region key table for fast lookup
2722            UpdateRegionKeyTable();
2723        }
2724    
2725    
2726    
2727    // *************** Group ***************
2728    // *
2729    
2730        /** @brief Constructor.
2731         *
2732         * @param file   - pointer to the gig::File object
2733         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
2734         *                 NULL if this is a new Group
2735         */
2736        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
2737            pFile      = file;
2738            pNameChunk = ck3gnm;
2739            ::LoadString(pNameChunk, Name);
2740        }
2741    
2742        Group::~Group() {
2743        }
2744    
2745        /** @brief Update chunks with current group settings.
2746         *
2747         * Apply current Group field values to the respective. You have to call
2748         * File::Save() to make changes persistent.
2749         */
2750        void Group::UpdateChunks() {
2751            // make sure <3gri> and <3gnl> list chunks exist
2752            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
2753            if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
2754            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2755            if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);
2756            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2757            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2758        }
2759    
2760        /**
2761         * Returns the first Sample of this Group. You have to call this method
2762         * once before you use GetNextSample().
2763         *
2764         * <b>Notice:</b> this method might block for a long time, in case the
2765         * samples of this .gig file were not scanned yet
2766         *
2767         * @returns  pointer address to first Sample or NULL if there is none
2768         *           applied to this Group
2769         * @see      GetNextSample()
2770         */
2771        Sample* Group::GetFirstSample() {
2772            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2773            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
2774                if (pSample->GetGroup() == this) return pSample;
2775            }
2776            return NULL;
2777        }
2778    
2779        /**
2780         * Returns the next Sample of the Group. You have to call
2781         * GetFirstSample() once before you can use this method. By calling this
2782         * method multiple times it iterates through the Samples assigned to
2783         * this Group.
2784         *
2785         * @returns  pointer address to the next Sample of this Group or NULL if
2786         *           end reached
2787         * @see      GetFirstSample()
2788         */
2789        Sample* Group::GetNextSample() {
2790            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2791            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
2792                if (pSample->GetGroup() == this) return pSample;
2793            }
2794            return NULL;
2795        }
2796    
2797        /**
2798         * Move Sample given by \a pSample from another Group to this Group.
2799         */
2800        void Group::AddSample(Sample* pSample) {
2801            pSample->pGroup = this;
2802        }
2803    
2804        /**
2805         * Move all members of this group to another group (preferably the 1st
2806         * one except this). This method is called explicitly by
2807         * File::DeleteGroup() thus when a Group was deleted. This code was
2808         * intentionally not placed in the destructor!
2809         */
2810        void Group::MoveAll() {
2811            // get "that" other group first
2812            Group* pOtherGroup = NULL;
2813            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
2814                if (pOtherGroup != this) break;
2815            }
2816            if (!pOtherGroup) throw Exception(
2817                "Could not move samples to another group, since there is no "
2818                "other Group. This is a bug, report it!"
2819            );
2820            // now move all samples of this group to the other group
2821            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
2822                pOtherGroup->AddSample(pSample);
2823            }
2824      }      }
2825    
2826    
# Line 1390  namespace gig { Line 2828  namespace gig {
2828  // *************** File ***************  // *************** File ***************
2829  // *  // *
2830    
2831        File::File() : DLS::File() {
2832            pGroups = NULL;
2833            pInfo->UseFixedLengthStrings = true;
2834        }
2835    
2836      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2837          pSamples     = NULL;          pGroups = NULL;
2838          pInstruments = NULL;          pInfo->UseFixedLengthStrings = true;
2839      }      }
2840    
2841      File::~File() {      File::~File() {
2842          // free samples          if (pGroups) {
2843          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
2844              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
2845              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
2846                  delete (*SamplesIterator);                  delete *iter;
2847                  SamplesIterator++;                  ++iter;
             }  
             pSamples->clear();  
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
2848              }              }
2849              pInstruments->clear();              delete pGroups;
2850          }          }
2851      }      }
2852    
2853      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
2854          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
2855          if (!pSamples) return NULL;          if (!pSamples) return NULL;
2856          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
2857          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1430  namespace gig { Line 2863  namespace gig {
2863          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2864      }      }
2865    
2866        /** @brief Add a new sample.
2867         *
2868         * This will create a new Sample object for the gig file. You have to
2869         * call Save() to make this persistent to the file.
2870         *
2871         * @returns pointer to new Sample object
2872         */
2873        Sample* File::AddSample() {
2874           if (!pSamples) LoadSamples();
2875           __ensureMandatoryChunksExist();
2876           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2877           // create new Sample object and its respective 'wave' list chunk
2878           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2879           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2880           pSamples->push_back(pSample);
2881           return pSample;
2882        }
2883    
2884        /** @brief Delete a sample.
2885         *
2886         * This will delete the given Sample object from the gig file. You have
2887         * to call Save() to make this persistent to the file.
2888         *
2889         * @param pSample - sample to delete
2890         * @throws gig::Exception if given sample could not be found
2891         */
2892        void File::DeleteSample(Sample* pSample) {
2893            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2894            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2895            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2896            pSamples->erase(iter);
2897            delete pSample;
2898        }
2899    
2900      void File::LoadSamples() {      void File::LoadSamples() {
2901          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          LoadSamples(NULL);
2902          if (wvpl) {      }
2903              unsigned long wvplFileOffset = wvpl->GetFilePos();  
2904              RIFF::List* wave = wvpl->GetFirstSubList();      void File::LoadSamples(progress_t* pProgress) {
2905              while (wave) {          // Groups must be loaded before samples, because samples will try
2906                  if (wave->GetListType() == LIST_TYPE_WAVE) {          // to resolve the group they belong to
2907                      if (!pSamples) pSamples = new SampleList;          LoadGroups();
2908                      unsigned long waveFileOffset = wave->GetFilePos();  
2909                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          if (!pSamples) pSamples = new SampleList;
2910    
2911            RIFF::File* file = pRIFF;
2912    
2913            // just for progress calculation
2914            int iSampleIndex  = 0;
2915            int iTotalSamples = WavePoolCount;
2916    
2917            // check if samples should be loaded from extension files
2918            int lastFileNo = 0;
2919            for (int i = 0 ; i < WavePoolCount ; i++) {
2920                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2921            }
2922            String name(pRIFF->GetFileName());
2923            int nameLen = name.length();
2924            char suffix[6];
2925            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2926    
2927            for (int fileNo = 0 ; ; ) {
2928                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2929                if (wvpl) {
2930                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2931                    RIFF::List* wave = wvpl->GetFirstSubList();
2932                    while (wave) {
2933                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2934                            // notify current progress
2935                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2936                            __notify_progress(pProgress, subprogress);
2937    
2938                            unsigned long waveFileOffset = wave->GetFilePos();
2939                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2940    
2941                            iSampleIndex++;
2942                        }
2943                        wave = wvpl->GetNextSubList();
2944                  }                  }
2945                  wave = wvpl->GetNextSubList();  
2946              }                  if (fileNo == lastFileNo) break;
2947    
2948                    // open extension file (*.gx01, *.gx02, ...)
2949                    fileNo++;
2950                    sprintf(suffix, ".gx%02d", fileNo);
2951                    name.replace(nameLen, 5, suffix);
2952                    file = new RIFF::File(name);
2953                    ExtensionFiles.push_back(file);
2954                } else break;
2955          }          }
2956          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2957            __notify_progress(pProgress, 1.0); // notify done
2958      }      }
2959    
2960      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2961          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2962          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2963          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2964          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2965      }      }
2966    
2967      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2968          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2969          InstrumentsIterator++;          InstrumentsIterator++;
2970          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2971      }      }
2972    
2973      /**      /**
2974       * Returns the instrument with the given index.       * Returns the instrument with the given index.
2975       *       *
2976         * @param index     - number of the sought instrument (0..n)
2977         * @param pProgress - optional: callback function for progress notification
2978       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
2979       */       */
2980      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2981          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
2982                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2983    
2984                // sample loading subtask
2985                progress_t subprogress;
2986                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2987                __notify_progress(&subprogress, 0.0f);
2988                GetFirstSample(&subprogress); // now force all samples to be loaded
2989                __notify_progress(&subprogress, 1.0f);
2990    
2991                // instrument loading subtask
2992                if (pProgress && pProgress->callback) {
2993                    subprogress.__range_min = subprogress.__range_max;
2994                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2995                }
2996                __notify_progress(&subprogress, 0.0f);
2997                LoadInstruments(&subprogress);
2998                __notify_progress(&subprogress, 1.0f);
2999            }
3000          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3001          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3002          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
3003              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
3004              InstrumentsIterator++;              InstrumentsIterator++;
3005          }          }
3006          return NULL;          return NULL;
3007      }      }
3008    
3009        /** @brief Add a new instrument definition.
3010         *
3011         * This will create a new Instrument object for the gig file. You have
3012         * to call Save() to make this persistent to the file.
3013         *
3014         * @returns pointer to new Instrument object
3015         */
3016        Instrument* File::AddInstrument() {
3017           if (!pInstruments) LoadInstruments();
3018           __ensureMandatoryChunksExist();
3019           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3020           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3021           Instrument* pInstrument = new Instrument(this, lstInstr);
3022           pInstruments->push_back(pInstrument);
3023           return pInstrument;
3024        }
3025    
3026        /** @brief Delete an instrument.
3027         *
3028         * This will delete the given Instrument object from the gig file. You
3029         * have to call Save() to make this persistent to the file.
3030         *
3031         * @param pInstrument - instrument to delete
3032         * @throws gig::Excption if given instrument could not be found
3033         */
3034        void File::DeleteInstrument(Instrument* pInstrument) {
3035            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
3036            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3037            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
3038            pInstruments->erase(iter);
3039            delete pInstrument;
3040        }
3041    
3042      void File::LoadInstruments() {      void File::LoadInstruments() {
3043            LoadInstruments(NULL);
3044        }
3045    
3046        void File::LoadInstruments(progress_t* pProgress) {
3047            if (!pInstruments) pInstruments = new InstrumentList;
3048          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3049          if (lstInstruments) {          if (lstInstruments) {
3050                int iInstrumentIndex = 0;
3051              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
3052              while (lstInstr) {              while (lstInstr) {
3053                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
3054                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
3055                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
3056                        __notify_progress(pProgress, localProgress);
3057    
3058                        // divide local progress into subprogress for loading current Instrument
3059                        progress_t subprogress;
3060                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3061    
3062                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3063    
3064                        iInstrumentIndex++;
3065                  }                  }
3066                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
3067              }              }
3068                __notify_progress(pProgress, 1.0); // notify done
3069            }
3070        }
3071    
3072        Group* File::GetFirstGroup() {
3073            if (!pGroups) LoadGroups();
3074            // there must always be at least one group
3075            GroupsIterator = pGroups->begin();
3076            return *GroupsIterator;
3077        }
3078    
3079        Group* File::GetNextGroup() {
3080            if (!pGroups) return NULL;
3081            ++GroupsIterator;
3082            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3083        }
3084    
3085        /**
3086         * Returns the group with the given index.
3087         *
3088         * @param index - number of the sought group (0..n)
3089         * @returns sought group or NULL if there's no such group
3090         */
3091        Group* File::GetGroup(uint index) {
3092            if (!pGroups) LoadGroups();
3093            GroupsIterator = pGroups->begin();
3094            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3095                if (i == index) return *GroupsIterator;
3096                ++GroupsIterator;
3097            }
3098            return NULL;
3099        }
3100    
3101        Group* File::AddGroup() {
3102            if (!pGroups) LoadGroups();
3103            // there must always be at least one group
3104            __ensureMandatoryChunksExist();
3105            Group* pGroup = new Group(this, NULL);
3106            pGroups->push_back(pGroup);
3107            return pGroup;
3108        }
3109    
3110        void File::DeleteGroup(Group* pGroup) {
3111            if (!pGroups) LoadGroups();
3112            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3113            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3114            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3115            // move all members of this group to another group
3116            pGroup->MoveAll();
3117            pGroups->erase(iter);
3118            delete pGroup;
3119        }
3120    
3121        void File::LoadGroups() {
3122            if (!pGroups) pGroups = new std::list<Group*>;
3123            // try to read defined groups from file
3124            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3125            if (lst3gri) {
3126                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3127                if (lst3gnl) {
3128                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3129                    while (ck) {
3130                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3131                            pGroups->push_back(new Group(this, ck));
3132                        }
3133                        ck = lst3gnl->GetNextSubChunk();
3134                    }
3135                }
3136            }
3137            // if there were no group(s), create at least the mandatory default group
3138            if (!pGroups->size()) {
3139                Group* pGroup = new Group(this, NULL);
3140                pGroup->Name = "Default Group";
3141                pGroups->push_back(pGroup);
3142          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
3143      }      }
3144    
3145    
# Line 1503  namespace gig { Line 3154  namespace gig {
3154          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
3155      }      }
3156    
3157    
3158    // *************** functions ***************
3159    // *
3160    
3161        /**
3162         * Returns the name of this C++ library. This is usually "libgig" of
3163         * course. This call is equivalent to RIFF::libraryName() and
3164         * DLS::libraryName().
3165         */
3166        String libraryName() {
3167            return PACKAGE;
3168        }
3169    
3170        /**
3171         * Returns version of this C++ library. This call is equivalent to
3172         * RIFF::libraryVersion() and DLS::libraryVersion().
3173         */
3174        String libraryVersion() {
3175            return VERSION;
3176        }
3177    
3178  } // namespace gig  } // namespace gig

Legend:
Removed from v.352  
changed lines
  Added in v.1076

  ViewVC Help
Powered by ViewVC