/[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 241 by schoenebeck, Wed Sep 15 13:49:21 2004 UTC revision 902 by persson, Sat Jul 22 14:22:01 2006 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file loader library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Christian Schoenebeck                     *   *   Copyright (C) 2003-2005 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          Instances++;          Instances++;
283            FileNo = fileNo;
284    
285          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
286          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
287          SampleGroup = _3gix->ReadInt16();              SampleGroup = pCk3gix->ReadInt16();
288            } else { // '3gix' chunk missing
289          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              // use default value(s)
290          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              SampleGroup = 0;
291          Manufacturer      = smpl->ReadInt32();          }
292          Product           = smpl->ReadInt32();  
293          SamplePeriod      = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
294          MIDIUnityNote     = smpl->ReadInt32();          if (pCkSmpl) {
295          FineTune          = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
296          smpl->Read(&SMPTEFormat, 1, 4);              Product       = pCkSmpl->ReadInt32();
297          SMPTEOffset       = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
298          Loops             = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
299          uint32_t manufByt = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
300          LoopID            = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
301          smpl->Read(&LoopType, 1, 4);              SMPTEOffset   = pCkSmpl->ReadInt32();
302          LoopStart         = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
303          LoopEnd           = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
304          LoopFraction      = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
305          LoopPlayCount     = smpl->ReadInt32();              pCkSmpl->Read(&LoopType, 1, 4);
306                LoopStart     = pCkSmpl->ReadInt32();
307                LoopEnd       = pCkSmpl->ReadInt32();
308                LoopFraction  = pCkSmpl->ReadInt32();
309                LoopPlayCount = pCkSmpl->ReadInt32();
310            } else { // 'smpl' chunk missing
311                // use default values
312                Manufacturer  = 0;
313                Product       = 0;
314                SamplePeriod  = 1 / SamplesPerSecond;
315                MIDIUnityNote = 64;
316                FineTune      = 0;
317                SMPTEOffset   = 0;
318                Loops         = 0;
319                LoopID        = 0;
320                LoopStart     = 0;
321                LoopEnd       = 0;
322                LoopFraction  = 0;
323                LoopPlayCount = 0;
324            }
325    
326          FrameTable                 = NULL;          FrameTable                 = NULL;
327          SamplePos                  = 0;          SamplePos                  = 0;
# Line 63  namespace gig { Line 329  namespace gig {
329          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
330          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
331    
332          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
333    
334            RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
335            Compressed        = ewav;
336            Dithered          = false;
337            TruncatedBits     = 0;
338          if (Compressed) {          if (Compressed) {
339              ScanCompressedSample();              uint32_t version = ewav->ReadInt32();
340              if (!pDecompressionBuffer) {              if (version == 3 && BitDepth == 24) {
341                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];                  Dithered = ewav->ReadInt32();
342                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;                  ewav->SetPos(Channels == 2 ? 84 : 64);
343                    TruncatedBits = ewav->ReadInt32();
344              }              }
345                ScanCompressedSample();
346          }          }
         FrameOffset = 0; // just for streaming compressed samples  
347    
348          LoopSize = LoopEnd - LoopStart;          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
349            if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
350                InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
351                InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
352            }
353            FrameOffset = 0; // just for streaming compressed samples
354    
355            LoopSize = LoopEnd - LoopStart + 1;
356        }
357    
358        /**
359         * Apply sample and its settings to the respective RIFF chunks. You have
360         * to call File::Save() to make changes persistent.
361         *
362         * Usually there is absolutely no need to call this method explicitly.
363         * It will be called automatically when File::Save() was called.
364         *
365         * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
366         *                        was provided yet
367         * @throws gig::Exception if there is any invalid sample setting
368         */
369        void Sample::UpdateChunks() {
370            // first update base class's chunks
371            DLS::Sample::UpdateChunks();
372    
373            // make sure 'smpl' chunk exists
374            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
375            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
376            // update 'smpl' chunk
377            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
378            SamplePeriod = 1 / SamplesPerSecond;
379            memcpy(&pData[0], &Manufacturer, 4);
380            memcpy(&pData[4], &Product, 4);
381            memcpy(&pData[8], &SamplePeriod, 4);
382            memcpy(&pData[12], &MIDIUnityNote, 4);
383            memcpy(&pData[16], &FineTune, 4);
384            memcpy(&pData[20], &SMPTEFormat, 4);
385            memcpy(&pData[24], &SMPTEOffset, 4);
386            memcpy(&pData[28], &Loops, 4);
387    
388            // we skip 'manufByt' for now (4 bytes)
389    
390            memcpy(&pData[36], &LoopID, 4);
391            memcpy(&pData[40], &LoopType, 4);
392            memcpy(&pData[44], &LoopStart, 4);
393            memcpy(&pData[48], &LoopEnd, 4);
394            memcpy(&pData[52], &LoopFraction, 4);
395            memcpy(&pData[56], &LoopPlayCount, 4);
396    
397            // make sure '3gix' chunk exists
398            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
399            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
400            // update '3gix' chunk
401            pData = (uint8_t*) pCk3gix->LoadChunkData();
402            memcpy(&pData[0], &SampleGroup, 2);
403      }      }
404    
405      /// 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 82  namespace gig { Line 408  namespace gig {
408          this->SamplesTotal = 0;          this->SamplesTotal = 0;
409          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
410    
411            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
412            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
413    
414          // Scanning          // Scanning
415          pCkData->SetPos(0);          pCkData->SetPos(0);
416          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
417              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
418              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
419              this->SamplesTotal += 2048;                  // stored, to save some memory
420              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
421                  case 1:   // left channel compressed  
422                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
423                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
424                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
425                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
426    
427                    if (pCkData->RemainingBytes() <= frameSize) {
428                        SamplesInLastFrame =
429                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
430                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
431                        SamplesTotal += SamplesInLastFrame;
432                      break;                      break;
433                  case 257: // both channels compressed                  }
434                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
435                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
436                }
437            }
438            else { // Mono
439                for (int i = 0 ; ; i++) {
440                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
441    
442                    const int mode = pCkData->ReadUint8();
443                    if (mode > 5) throw gig::Exception("Unknown compression mode");
444                    const unsigned long frameSize = bytesPerFrame[mode];
445    
446                    if (pCkData->RemainingBytes() <= frameSize) {
447                        SamplesInLastFrame =
448                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
449                        SamplesTotal += SamplesInLastFrame;
450                      break;                      break;
451                  default: // both channels uncompressed                  }
452                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
453                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
454              }              }
455          }          }
456          pCkData->SetPos(0);          pCkData->SetPos(0);
457    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
458          // 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)
459          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
460          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 141  namespace gig { Line 490  namespace gig {
490       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
491       * 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
492       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
493       *       * @code
494       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
495       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
496         * @endcode
497       *       *
498       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
499       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 189  namespace gig { Line 539  namespace gig {
539       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
540       * 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
541       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
542       *       * @code
543       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
544       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
545       *       * @endcode
546       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
547       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
548       * 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 252  namespace gig { Line 602  namespace gig {
602          RAMCache.Size   = 0;          RAMCache.Size   = 0;
603      }      }
604    
605        /** @brief Resize sample.
606         *
607         * Resizes the sample's wave form data, that is the actual size of
608         * sample wave data possible to be written for this sample. This call
609         * will return immediately and just schedule the resize operation. You
610         * should call File::Save() to actually perform the resize operation(s)
611         * "physically" to the file. As this can take a while on large files, it
612         * is recommended to call Resize() first on all samples which have to be
613         * resized and finally to call File::Save() to perform all those resize
614         * operations in one rush.
615         *
616         * The actual size (in bytes) is dependant to the current FrameSize
617         * value. You may want to set FrameSize before calling Resize().
618         *
619         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
620         * enlarged samples before calling File::Save() as this might exceed the
621         * current sample's boundary!
622         *
623         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
624         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
625         * other formats will fail!
626         *
627         * @param iNewSize - new sample wave data size in sample points (must be
628         *                   greater than zero)
629         * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
630         *                         or if \a iNewSize is less than 1
631         * @throws gig::Exception if existing sample is compressed
632         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
633         *      DLS::Sample::FormatTag, File::Save()
634         */
635        void Sample::Resize(int iNewSize) {
636            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
637            DLS::Sample::Resize(iNewSize);
638        }
639    
640      /**      /**
641       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
642       * 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 323  namespace gig { Line 708  namespace gig {
708       * 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.
709       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
710       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
711       *       * @code
712       * <i>       * gig::playback_state_t playbackstate;
713       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
714       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
715       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
716       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
717       * 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
718       * 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.
719       * The method already handles such cases by itself.       * The method already handles such cases by itself.
720       *       *
721         * <b>Caution:</b> If you are using more than one streaming thread, you
722         * have to use an external decompression buffer for <b>EACH</b>
723         * streaming thread to avoid race conditions and crashes!
724         *
725       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
726       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
727       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
728       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
729         * @param pDimRgn          dimension region with looping information
730         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
731       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
732         * @see                    CreateDecompressionBuffer()
733       */       */
734      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,
735                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
736          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
737          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
738    
739          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
740    
741          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
742    
743              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
744                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
745    
746                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
747                      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  
748    
749                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
750                              // determine the end position within the loop first,                          do {
751                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
752                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
753                              // backward playback  
754                                if (!pPlaybackState->reverse) { // forward playback
755                              unsigned long swapareastart       = totalreadsamples;                                  do {
756                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
757                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
758                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
759                                        totalreadsamples += readsamples;
760                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
761                                            pPlaybackState->reverse = true;
762                              // read samples for backward playback                                          break;
763                              do {                                      }
764                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  } while (samplestoread && readsamples);
765                                  samplestoreadinloop -= readsamples;                              }
766                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
767    
768                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
769                                    // determine the end position within the loop first,
770                                    // read forward from that 'end' and finally after
771                                    // reading, swap all sample frames so it reflects
772                                    // backward playback
773    
774                                    unsigned long swapareastart       = totalreadsamples;
775                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
776                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
777                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
778    
779                                    SetPos(reverseplaybackend);
780    
781                                    // read samples for backward playback
782                                    do {
783                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
784                                        samplestoreadinloop -= readsamples;
785                                        samplestoread       -= readsamples;
786                                        totalreadsamples    += readsamples;
787                                    } while (samplestoreadinloop && readsamples);
788    
789                                    SetPos(reverseplaybackend); // pretend we really read backwards
790    
791                                    if (reverseplaybackend == loop.LoopStart) {
792                                        pPlaybackState->loop_cycles_left--;
793                                        pPlaybackState->reverse = false;
794                                    }
795    
796                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
797                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
798                              }                              }
799                            } while (samplestoread && readsamples);
800                            break;
801                        }
802    
803                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
804                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
805                          }                          if (!pPlaybackState->reverse) do {
806                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
807                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
808                  }                              samplestoread    -= readsamples;
809                                totalreadsamples += readsamples;
810                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
811                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
812                      if (!pPlaybackState->reverse) do {                                  break;
813                          samplestoloopend  = this->LoopEnd - GetPos();                              }
814                          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);  
815    
816                      if (!samplestoread) break;                          if (!samplestoread) break;
817    
818                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
819                      // determine the end position within the loop first,                          // determine the end position within the loop first,
820                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
821                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
822                      // backward playback                          // backward playback
823    
824                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
825                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
826                      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)
827                                                                                : samplestoread;                                                                                    : samplestoread;
828                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
829    
830                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
831    
832                      // read samples for backward playback                          // read samples for backward playback
833                      do {                          do {
834                          // 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
835                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
836                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
837                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
838                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
839                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
840                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
841                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
842                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
843                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
844                          }                              }
845                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
846    
847                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
848    
849                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
850                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
851                      break;                          break;
852                  }                      }
853    
854                  default: case loop_type_normal: {                      default: case loop_type_normal: {
855                      do {                          do {
856                          // 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
857                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
858                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
859                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
860                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
861                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
862                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
863                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
864                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
865                          }                              }
866                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
867                      break;                          break;
868                        }
869                  }                  }
870              }              }
871          }          }
872    
873          // read on without looping          // read on without looping
874          if (samplestoread) do {          if (samplestoread) do {
875              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
876              samplestoread    -= readsamples;              samplestoread    -= readsamples;
877              totalreadsamples += readsamples;              totalreadsamples += readsamples;
878          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 495  namespace gig { Line 891  namespace gig {
891       * 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,
892       * thus for disk streaming.       * thus for disk streaming.
893       *       *
894         * <b>Caution:</b> If you are using more than one streaming thread, you
895         * have to use an external decompression buffer for <b>EACH</b>
896         * streaming thread to avoid race conditions and crashes!
897         *
898         * For 16 bit samples, the data in the buffer will be int16_t
899         * (using native endianness). For 24 bit, the buffer will
900         * contain three bytes per sample, little-endian.
901         *
902       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
903       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
904         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
905       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
906       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
907       */       */
908      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
909          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
910          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?          if (!Compressed) {
911          else { //FIXME: no support for mono compressed samples yet, are there any?              if (BitDepth == 24) {
912                    return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
913                }
914                else { // 16 bit
915                    // (pCkData->Read does endian correction)
916                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
917                                         : pCkData->Read(pBuffer, SampleCount, 2);
918                }
919            }
920            else {
921              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
922              //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
923              // 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  
924                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
925                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
926                            copysamples;                            copysamples, skipsamples,
927              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
928              this->FrameOffset = 0;              this->FrameOffset = 0;
929    
930              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
931                  // local buffer reallocation - hope this won't happen  
932                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
933                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
934                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
935                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
936                    remainingsamples = SampleCount;
937                    assumedsize      = GuessSize(SampleCount);
938              }              }
939    
940              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
941              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
942              int16_t* pDst = (int16_t*) pBuffer;              uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
943              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
944    
945              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
946                    unsigned long framesamples = SamplesPerFrame;
947                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
948                  if (remainingbytes < 8194) {  
949                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
950                          this->SamplePos = this->SamplesTotal;  
951                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
952                        mode_r = *pSrc++;
953                        framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
954                        rightChannelOffset = bytesPerFrameNoHdr[mode_l];
955                        nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
956                        if (remainingbytes < framebytes) { // last frame in sample
957                            framesamples = SamplesInLastFrame;
958                            if (mode_l == 4 && (framesamples & 1)) {
959                                rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
960                            }
961                            else {
962                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
963                            }
964                        }
965                    }
966                    else {
967                        framebytes = bytesPerFrame[mode_l] + 1;
968                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
969                        if (remainingbytes < framebytes) {
970                            framesamples = SamplesInLastFrame;
971                      }                      }
                     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;  
972                  }                  }
973    
974                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
975                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
976                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
977                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
978                            skipsamples = currentframeoffset;
979                        }
980                        else {
981                            copysamples = 0;
982                            skipsamples = framesamples;
983                        }
984                  }                  }
985                  else {                  else {
986                        // This frame has enough data for pBuffer, but not
987                        // all of the frame is needed. Set file position
988                        // to start of this frame for next call to Read.
989                      copysamples = remainingsamples;                      copysamples = remainingsamples;
990                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
991                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
992                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
993                      }                  }
994                      else {                  remainingsamples -= copysamples;
995    
996                    if (remainingbytes > framebytes) {
997                        remainingbytes -= framebytes;
998                        if (remainingsamples == 0 &&
999                            currentframeoffset + copysamples == framesamples) {
1000                            // This frame has enough data for pBuffer, and
1001                            // all of the frame is needed. Set file
1002                            // position to start of next frame for next
1003                            // call to Read. FrameOffset is 0.
1004                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
1005                      }                      }
1006                  }                  }
1007                    else remainingbytes = 0;
1008    
1009                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
1010                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
1011                  switch (compressionmode) {                  if (copysamples == 0) {
1012                      case 1: // left channel compressed                      // skip this frame
1013                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
1014                          if (!remainingsamples && copysamples == 2048)                  }
1015                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
1016                        const unsigned char* const param_l = pSrc;
1017                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
1018                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
1019                          while (currentframeoffset) {  
1020                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
1021                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
1022                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
1023                              currentframeoffset--;  
1024                          }                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1025                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
1026                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1027                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
1028                              *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  
1029                          }                          }
1030                          while (copysamples) {                          else { // Mono
1031                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1032                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
1033                              right  -= dright;                              pDst24 += copysamples * 3;
                             *pDst = right; pDst++;  
                             copysamples--;  
1034                          }                          }
1035                          break;                      }
1036                      case 257: // both channels compressed                      else { // 16 bit
1037                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
1038                          if (!remainingsamples && copysamples == 2048)  
1039                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
1040                            if (Channels == 2) { // Stereo
1041                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
1042                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
1043                          right  = *(int16_t*)pSrc; pSrc+=2;  
1044                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
1045                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1046                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1047                              left   -= dleft;                                           skipsamples, copysamples);
1048                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
1049                          }                          }
1050                          while (copysamples) {                          else { // Mono
1051                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
1052                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1053                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
1054                          }                          }
1055                          break;                      }
1056                      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;  
1057                  }                  }
1058              }  
1059                    // reload from disk to local buffer if needed
1060                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1061                        assumedsize    = GuessSize(remainingsamples);
1062                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1063                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1064                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1065                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1066                    }
1067                } // while
1068    
1069              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
1070              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1071              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
1072          }          }
1073      }      }
1074    
1075        /** @brief Write sample wave data.
1076         *
1077         * Writes \a SampleCount number of sample points from the buffer pointed
1078         * by \a pBuffer and increments the position within the sample. Use this
1079         * method to directly write the sample data to disk, i.e. if you don't
1080         * want or cannot load the whole sample data into RAM.
1081         *
1082         * You have to Resize() the sample to the desired size and call
1083         * File::Save() <b>before</b> using Write().
1084         *
1085         * Note: there is currently no support for writing compressed samples.
1086         *
1087         * @param pBuffer     - source buffer
1088         * @param SampleCount - number of sample points to write
1089         * @throws DLS::Exception if current sample size is too small
1090         * @throws gig::Exception if sample is compressed
1091         * @see DLS::LoadSampleData()
1092         */
1093        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1094            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1095            return DLS::Sample::Write(pBuffer, SampleCount);
1096        }
1097    
1098        /**
1099         * Allocates a decompression buffer for streaming (compressed) samples
1100         * with Sample::Read(). If you are using more than one streaming thread
1101         * in your application you <b>HAVE</b> to create a decompression buffer
1102         * for <b>EACH</b> of your streaming threads and provide it with the
1103         * Sample::Read() call in order to avoid race conditions and crashes.
1104         *
1105         * You should free the memory occupied by the allocated buffer(s) once
1106         * you don't need one of your streaming threads anymore by calling
1107         * DestroyDecompressionBuffer().
1108         *
1109         * @param MaxReadSize - the maximum size (in sample points) you ever
1110         *                      expect to read with one Read() call
1111         * @returns allocated decompression buffer
1112         * @see DestroyDecompressionBuffer()
1113         */
1114        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1115            buffer_t result;
1116            const double worstCaseHeaderOverhead =
1117                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1118            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1119            result.pStart            = new int8_t[result.Size];
1120            result.NullExtensionSize = 0;
1121            return result;
1122        }
1123    
1124        /**
1125         * Free decompression buffer, previously created with
1126         * CreateDecompressionBuffer().
1127         *
1128         * @param DecompressionBuffer - previously allocated decompression
1129         *                              buffer to free
1130         */
1131        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1132            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1133                delete[] (int8_t*) DecompressionBuffer.pStart;
1134                DecompressionBuffer.pStart = NULL;
1135                DecompressionBuffer.Size   = 0;
1136                DecompressionBuffer.NullExtensionSize = 0;
1137            }
1138        }
1139    
1140      Sample::~Sample() {      Sample::~Sample() {
1141          Instances--;          Instances--;
1142          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
1143                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1144                InternalDecompressionBuffer.pStart = NULL;
1145                InternalDecompressionBuffer.Size   = 0;
1146            }
1147          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1148          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1149      }      }
# Line 676  namespace gig { Line 1159  namespace gig {
1159      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1160          Instances++;          Instances++;
1161    
1162            pSample = NULL;
1163    
1164          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1165          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1166    
1167          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1168          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1169          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1170          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1171          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1172          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1173          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1174          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1175          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1176          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1177          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1178          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1179          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1180          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1181          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1182          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1183          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1184          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1185          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1186          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1187          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1188          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1189          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1190          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1191          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1192          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1193          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1194          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1195          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1196          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1197          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1198          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1199          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1200          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1201          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1202          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1203          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1204          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1205          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1206          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1207          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1208          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1209          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1210          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1211          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1212          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1213          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1214          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1215          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1216          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1217          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1218          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1219              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1220              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1221          }                  VelocityResponseDepth = velocityresponse;
1222          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1223              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1224              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1225          }              } else if (velocityresponse < 15) {
1226          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1227              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1228              VelocityResponseDepth = velocityresponse - 10;              } else {
1229          }                  VelocityResponseCurve = curve_type_unknown;
1230          else {                  VelocityResponseDepth = 0;
1231              VelocityResponseCurve = curve_type_unknown;              }
1232              VelocityResponseDepth = 0;              uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1233          }              if (releasevelocityresponse < 5) {
1234          uint8_t releasevelocityresponse = _3ewa->ReadUint8();                  ReleaseVelocityResponseCurve = curve_type_nonlinear;
1235          if (releasevelocityresponse < 5) {                  ReleaseVelocityResponseDepth = releasevelocityresponse;
1236              ReleaseVelocityResponseCurve = curve_type_nonlinear;              } else if (releasevelocityresponse < 10) {
1237              ReleaseVelocityResponseDepth = releasevelocityresponse;                  ReleaseVelocityResponseCurve = curve_type_linear;
1238          }                  ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1239          else if (releasevelocityresponse < 10) {              } else if (releasevelocityresponse < 15) {
1240              ReleaseVelocityResponseCurve = curve_type_linear;                  ReleaseVelocityResponseCurve = curve_type_special;
1241              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1242          }              } else {
1243          else if (releasevelocityresponse < 15) {                  ReleaseVelocityResponseCurve = curve_type_unknown;
1244              ReleaseVelocityResponseCurve = curve_type_special;                  ReleaseVelocityResponseDepth = 0;
1245              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;              }
1246          }              VelocityResponseCurveScaling = _3ewa->ReadUint8();
1247          else {              AttenuationControllerThreshold = _3ewa->ReadInt8();
1248              ReleaseVelocityResponseCurve = curve_type_unknown;              _3ewa->ReadInt32(); // unknown
1249              ReleaseVelocityResponseDepth = 0;              SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1250                _3ewa->ReadInt16(); // unknown
1251                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1252                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1253                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1254                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1255                else                                       DimensionBypass = dim_bypass_ctrl_none;
1256                uint8_t pan = _3ewa->ReadUint8();
1257                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1258                SelfMask = _3ewa->ReadInt8() & 0x01;
1259                _3ewa->ReadInt8(); // unknown
1260                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1261                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1262                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1263                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1264                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1265                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1266                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1267                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1268                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1269                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1270                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1271                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1272                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1273                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1274                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1275                                                            : vcf_res_ctrl_none;
1276                uint16_t eg3depth = _3ewa->ReadUint16();
1277                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1278                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1279                _3ewa->ReadInt16(); // unknown
1280                ChannelOffset = _3ewa->ReadUint8() / 4;
1281                uint8_t regoptions = _3ewa->ReadUint8();
1282                MSDecode           = regoptions & 0x01; // bit 0
1283                SustainDefeat      = regoptions & 0x02; // bit 1
1284                _3ewa->ReadInt16(); // unknown
1285                VelocityUpperLimit = _3ewa->ReadInt8();
1286                _3ewa->ReadInt8(); // unknown
1287                _3ewa->ReadInt16(); // unknown
1288                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1289                _3ewa->ReadInt8(); // unknown
1290                _3ewa->ReadInt8(); // unknown
1291                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1292                uint8_t vcfcutoff = _3ewa->ReadUint8();
1293                VCFEnabled = vcfcutoff & 0x80; // bit 7
1294                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1295                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1296                uint8_t vcfvelscale = _3ewa->ReadUint8();
1297                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1298                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1299                _3ewa->ReadInt8(); // unknown
1300                uint8_t vcfresonance = _3ewa->ReadUint8();
1301                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1302                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1303                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1304                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1305                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1306                uint8_t vcfvelocity = _3ewa->ReadUint8();
1307                VCFVelocityDynamicRange = vcfvelocity % 5;
1308                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1309                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1310                if (VCFType == vcf_type_lowpass) {
1311                    if (lfo3ctrl & 0x40) // bit 6
1312                        VCFType = vcf_type_lowpassturbo;
1313                }
1314            } else { // '3ewa' chunk does not exist yet
1315                // use default values
1316                LFO3Frequency                   = 1.0;
1317                EG3Attack                       = 0.0;
1318                LFO1InternalDepth               = 0;
1319                LFO3InternalDepth               = 0;
1320                LFO1ControlDepth                = 0;
1321                LFO3ControlDepth                = 0;
1322                EG1Attack                       = 0.0;
1323                EG1Decay1                       = 0.0;
1324                EG1Sustain                      = 0;
1325                EG1Release                      = 0.0;
1326                EG1Controller.type              = eg1_ctrl_t::type_none;
1327                EG1Controller.controller_number = 0;
1328                EG1ControllerInvert             = false;
1329                EG1ControllerAttackInfluence    = 0;
1330                EG1ControllerDecayInfluence     = 0;
1331                EG1ControllerReleaseInfluence   = 0;
1332                EG2Controller.type              = eg2_ctrl_t::type_none;
1333                EG2Controller.controller_number = 0;
1334                EG2ControllerInvert             = false;
1335                EG2ControllerAttackInfluence    = 0;
1336                EG2ControllerDecayInfluence     = 0;
1337                EG2ControllerReleaseInfluence   = 0;
1338                LFO1Frequency                   = 1.0;
1339                EG2Attack                       = 0.0;
1340                EG2Decay1                       = 0.0;
1341                EG2Sustain                      = 0;
1342                EG2Release                      = 0.0;
1343                LFO2ControlDepth                = 0;
1344                LFO2Frequency                   = 1.0;
1345                LFO2InternalDepth               = 0;
1346                EG1Decay2                       = 0.0;
1347                EG1InfiniteSustain              = false;
1348                EG1PreAttack                    = 1000;
1349                EG2Decay2                       = 0.0;
1350                EG2InfiniteSustain              = false;
1351                EG2PreAttack                    = 1000;
1352                VelocityResponseCurve           = curve_type_nonlinear;
1353                VelocityResponseDepth           = 3;
1354                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1355                ReleaseVelocityResponseDepth    = 3;
1356                VelocityResponseCurveScaling    = 32;
1357                AttenuationControllerThreshold  = 0;
1358                SampleStartOffset               = 0;
1359                PitchTrack                      = true;
1360                DimensionBypass                 = dim_bypass_ctrl_none;
1361                Pan                             = 0;
1362                SelfMask                        = true;
1363                LFO3Controller                  = lfo3_ctrl_modwheel;
1364                LFO3Sync                        = false;
1365                InvertAttenuationController     = false;
1366                AttenuationController.type      = attenuation_ctrl_t::type_none;
1367                AttenuationController.controller_number = 0;
1368                LFO2Controller                  = lfo2_ctrl_internal;
1369                LFO2FlipPhase                   = false;
1370                LFO2Sync                        = false;
1371                LFO1Controller                  = lfo1_ctrl_internal;
1372                LFO1FlipPhase                   = false;
1373                LFO1Sync                        = false;
1374                VCFResonanceController          = vcf_res_ctrl_none;
1375                EG3Depth                        = 0;
1376                ChannelOffset                   = 0;
1377                MSDecode                        = false;
1378                SustainDefeat                   = false;
1379                VelocityUpperLimit              = 0;
1380                ReleaseTriggerDecay             = 0;
1381                EG1Hold                         = false;
1382                VCFEnabled                      = false;
1383                VCFCutoff                       = 0;
1384                VCFCutoffController             = vcf_cutoff_ctrl_none;
1385                VCFCutoffControllerInvert       = false;
1386                VCFVelocityScale                = 0;
1387                VCFResonance                    = 0;
1388                VCFResonanceDynamic             = false;
1389                VCFKeyboardTracking             = false;
1390                VCFKeyboardTrackingBreakpoint   = 0;
1391                VCFVelocityDynamicRange         = 0x04;
1392                VCFVelocityCurve                = curve_type_linear;
1393                VCFType                         = vcf_type_lowpass;
1394            }
1395    
1396            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1397                                                         VelocityResponseDepth,
1398                                                         VelocityResponseCurveScaling);
1399    
1400            curve_type_t curveType = ReleaseVelocityResponseCurve;
1401            uint8_t depth = ReleaseVelocityResponseDepth;
1402    
1403            // this models a strange behaviour or bug in GSt: two of the
1404            // velocity response curves for release time are not used even
1405            // if specified, instead another curve is chosen.
1406            if ((curveType == curve_type_nonlinear && depth == 0) ||
1407                (curveType == curve_type_special   && depth == 4)) {
1408                curveType = curve_type_nonlinear;
1409                depth = 3;
1410            }
1411            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1412    
1413            curveType = VCFVelocityCurve;
1414            depth = VCFVelocityDynamicRange;
1415    
1416            // even stranger GSt: two of the velocity response curves for
1417            // filter cutoff are not used, instead another special curve
1418            // is chosen. This curve is not used anywhere else.
1419            if ((curveType == curve_type_nonlinear && depth == 0) ||
1420                (curveType == curve_type_special   && depth == 4)) {
1421                curveType = curve_type_special;
1422                depth = 5;
1423          }          }
1424          VelocityResponseCurveScaling = _3ewa->ReadUint8();          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1425          AttenuationControllerThreshold = _3ewa->ReadInt8();                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
         _3ewa->ReadInt32(); // unknown  
         SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
         _3ewa->ReadInt16(); // unknown  
         uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();  
         PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
         if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;  
         else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
         else                                       DimensionBypass = dim_bypass_ctrl_none;  
         uint8_t pan = _3ewa->ReadUint8();  
         Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;  
         SelfMask = _3ewa->ReadInt8() & 0x01;  
         _3ewa->ReadInt8(); // unknown  
         uint8_t lfo3ctrl = _3ewa->ReadUint8();  
         LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits  
         LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
         InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
         AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
         uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
         LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
         LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
         LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
         bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
         uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
         LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
         LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
         LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
         VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
                                                     : vcf_res_ctrl_none;  
         uint16_t eg3depth = _3ewa->ReadUint16();  
         EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
                                       : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */  
         _3ewa->ReadInt16(); // unknown  
         ChannelOffset = _3ewa->ReadUint8() / 4;  
         uint8_t regoptions = _3ewa->ReadUint8();  
         MSDecode           = regoptions & 0x01; // bit 0  
         SustainDefeat      = regoptions & 0x02; // bit 1  
         _3ewa->ReadInt16(); // unknown  
         VelocityUpperLimit = _3ewa->ReadInt8();  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt16(); // unknown  
         ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
1426    
1427          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1428          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          VelocityTable = 0;
1429          if (pVelocityTables->count(tableKey)) { // if key exists      }
1430              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];  
1431        /**
1432         * Apply dimension region settings to the respective RIFF chunks. You
1433         * have to call File::Save() to make changes persistent.
1434         *
1435         * Usually there is absolutely no need to call this method explicitly.
1436         * It will be called automatically when File::Save() was called.
1437         */
1438        void DimensionRegion::UpdateChunks() {
1439            // first update base class's chunk
1440            DLS::Sampler::UpdateChunks();
1441    
1442            // make sure '3ewa' chunk exists
1443            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1444            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1445            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1446    
1447            // update '3ewa' chunk with DimensionRegion's current settings
1448    
1449            const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1450            memcpy(&pData[0], &unknown, 4);
1451    
1452            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1453            memcpy(&pData[4], &lfo3freq, 4);
1454    
1455            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1456            memcpy(&pData[4], &eg3attack, 4);
1457    
1458            // next 2 bytes unknown
1459    
1460            memcpy(&pData[10], &LFO1InternalDepth, 2);
1461    
1462            // next 2 bytes unknown
1463    
1464            memcpy(&pData[14], &LFO3InternalDepth, 2);
1465    
1466            // next 2 bytes unknown
1467    
1468            memcpy(&pData[18], &LFO1ControlDepth, 2);
1469    
1470            // next 2 bytes unknown
1471    
1472            memcpy(&pData[22], &LFO3ControlDepth, 2);
1473    
1474            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1475            memcpy(&pData[24], &eg1attack, 4);
1476    
1477            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1478            memcpy(&pData[28], &eg1decay1, 4);
1479    
1480            // next 2 bytes unknown
1481    
1482            memcpy(&pData[34], &EG1Sustain, 2);
1483    
1484            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1485            memcpy(&pData[36], &eg1release, 4);
1486    
1487            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1488            memcpy(&pData[40], &eg1ctl, 1);
1489    
1490            const uint8_t eg1ctrloptions =
1491                (EG1ControllerInvert) ? 0x01 : 0x00 |
1492                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1493                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1494                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1495            memcpy(&pData[41], &eg1ctrloptions, 1);
1496    
1497            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1498            memcpy(&pData[42], &eg2ctl, 1);
1499    
1500            const uint8_t eg2ctrloptions =
1501                (EG2ControllerInvert) ? 0x01 : 0x00 |
1502                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1503                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1504                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1505            memcpy(&pData[43], &eg2ctrloptions, 1);
1506    
1507            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1508            memcpy(&pData[44], &lfo1freq, 4);
1509    
1510            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1511            memcpy(&pData[48], &eg2attack, 4);
1512    
1513            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1514            memcpy(&pData[52], &eg2decay1, 4);
1515    
1516            // next 2 bytes unknown
1517    
1518            memcpy(&pData[58], &EG2Sustain, 2);
1519    
1520            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1521            memcpy(&pData[60], &eg2release, 4);
1522    
1523            // next 2 bytes unknown
1524    
1525            memcpy(&pData[66], &LFO2ControlDepth, 2);
1526    
1527            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1528            memcpy(&pData[68], &lfo2freq, 4);
1529    
1530            // next 2 bytes unknown
1531    
1532            memcpy(&pData[72], &LFO2InternalDepth, 2);
1533    
1534            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1535            memcpy(&pData[74], &eg1decay2, 4);
1536    
1537            // next 2 bytes unknown
1538    
1539            memcpy(&pData[80], &EG1PreAttack, 2);
1540    
1541            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1542            memcpy(&pData[82], &eg2decay2, 4);
1543    
1544            // next 2 bytes unknown
1545    
1546            memcpy(&pData[88], &EG2PreAttack, 2);
1547    
1548            {
1549                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1550                uint8_t velocityresponse = VelocityResponseDepth;
1551                switch (VelocityResponseCurve) {
1552                    case curve_type_nonlinear:
1553                        break;
1554                    case curve_type_linear:
1555                        velocityresponse += 5;
1556                        break;
1557                    case curve_type_special:
1558                        velocityresponse += 10;
1559                        break;
1560                    case curve_type_unknown:
1561                    default:
1562                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1563                }
1564                memcpy(&pData[90], &velocityresponse, 1);
1565          }          }
1566          else {  
1567              pVelocityAttenuationTable = new double[128];          {
1568              switch (VelocityResponseCurve) { // calculate the new table              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1569                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1570                switch (ReleaseVelocityResponseCurve) {
1571                  case curve_type_nonlinear:                  case curve_type_nonlinear:
1572                      for (int velocity = 0; velocity < 128; velocity++) {                      break;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_NONLINEAR(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));  
                         if      (pVelocityAttenuationTable[velocity] > 1.0)   pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;  
                      }  
                      break;  
1573                  case curve_type_linear:                  case curve_type_linear:
1574                      for (int velocity = 0; velocity < 128; velocity++) {                      releasevelocityresponse += 5;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_LINEAR(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));  
                         if      (pVelocityAttenuationTable[velocity] > 1.0)   pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
1575                      break;                      break;
1576                  case curve_type_special:                  case curve_type_special:
1577                      for (int velocity = 0; velocity < 128; velocity++) {                      releasevelocityresponse += 10;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_SPECIAL(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));  
                         if      (pVelocityAttenuationTable[velocity] > 1.0)   pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
1578                      break;                      break;
1579                  case curve_type_unknown:                  case curve_type_unknown:
1580                  default:                  default:
1581                      throw gig::Exception("Unknown transform curve type.");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1582              }              }
1583              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              memcpy(&pData[91], &releasevelocityresponse, 1);
1584          }          }
1585    
1586            memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1587    
1588            memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1589    
1590            // next 4 bytes unknown
1591    
1592            memcpy(&pData[98], &SampleStartOffset, 2);
1593    
1594            // next 2 bytes unknown
1595    
1596            {
1597                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1598                switch (DimensionBypass) {
1599                    case dim_bypass_ctrl_94:
1600                        pitchTrackDimensionBypass |= 0x10;
1601                        break;
1602                    case dim_bypass_ctrl_95:
1603                        pitchTrackDimensionBypass |= 0x20;
1604                        break;
1605                    case dim_bypass_ctrl_none:
1606                        //FIXME: should we set anything here?
1607                        break;
1608                    default:
1609                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1610                }
1611                memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1612            }
1613    
1614            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1615            memcpy(&pData[103], &pan, 1);
1616    
1617            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1618            memcpy(&pData[104], &selfmask, 1);
1619    
1620            // next byte unknown
1621    
1622            {
1623                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1624                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1625                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1626                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1627                memcpy(&pData[106], &lfo3ctrl, 1);
1628            }
1629    
1630            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1631            memcpy(&pData[107], &attenctl, 1);
1632    
1633            {
1634                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1635                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1636                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1637                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1638                memcpy(&pData[108], &lfo2ctrl, 1);
1639            }
1640    
1641            {
1642                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1643                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1644                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1645                if (VCFResonanceController != vcf_res_ctrl_none)
1646                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1647                memcpy(&pData[109], &lfo1ctrl, 1);
1648            }
1649    
1650            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1651                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1652            memcpy(&pData[110], &eg3depth, 1);
1653    
1654            // next 2 bytes unknown
1655    
1656            const uint8_t channeloffset = ChannelOffset * 4;
1657            memcpy(&pData[113], &channeloffset, 1);
1658    
1659            {
1660                uint8_t regoptions = 0;
1661                if (MSDecode)      regoptions |= 0x01; // bit 0
1662                if (SustainDefeat) regoptions |= 0x02; // bit 1
1663                memcpy(&pData[114], &regoptions, 1);
1664            }
1665    
1666            // next 2 bytes unknown
1667    
1668            memcpy(&pData[117], &VelocityUpperLimit, 1);
1669    
1670            // next 3 bytes unknown
1671    
1672            memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1673    
1674            // next 2 bytes unknown
1675    
1676            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1677            memcpy(&pData[124], &eg1hold, 1);
1678    
1679            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1680                                      (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */
1681            memcpy(&pData[125], &vcfcutoff, 1);
1682    
1683            memcpy(&pData[126], &VCFCutoffController, 1);
1684    
1685            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1686                                        (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1687            memcpy(&pData[127], &vcfvelscale, 1);
1688    
1689            // next byte unknown
1690    
1691            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1692                                         (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1693            memcpy(&pData[129], &vcfresonance, 1);
1694    
1695            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1696                                          (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1697            memcpy(&pData[130], &vcfbreakpoint, 1);
1698    
1699            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1700                                        VCFVelocityCurve * 5;
1701            memcpy(&pData[131], &vcfvelocity, 1);
1702    
1703            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1704            memcpy(&pData[132], &vcftype, 1);
1705        }
1706    
1707        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1708        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1709        {
1710            double* table;
1711            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1712            if (pVelocityTables->count(tableKey)) { // if key exists
1713                table = (*pVelocityTables)[tableKey];
1714            }
1715            else {
1716                table = CreateVelocityTable(curveType, depth, scaling);
1717                (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
1718            }
1719            return table;
1720      }      }
1721    
1722      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 988  namespace gig { Line 1837  namespace gig {
1837          return decodedcontroller;          return decodedcontroller;
1838      }      }
1839    
1840        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1841            _lev_ctrl_t encodedcontroller;
1842            switch (DecodedController.type) {
1843                // special controller
1844                case leverage_ctrl_t::type_none:
1845                    encodedcontroller = _lev_ctrl_none;
1846                    break;
1847                case leverage_ctrl_t::type_velocity:
1848                    encodedcontroller = _lev_ctrl_velocity;
1849                    break;
1850                case leverage_ctrl_t::type_channelaftertouch:
1851                    encodedcontroller = _lev_ctrl_channelaftertouch;
1852                    break;
1853    
1854                // ordinary MIDI control change controller
1855                case leverage_ctrl_t::type_controlchange:
1856                    switch (DecodedController.controller_number) {
1857                        case 1:
1858                            encodedcontroller = _lev_ctrl_modwheel;
1859                            break;
1860                        case 2:
1861                            encodedcontroller = _lev_ctrl_breath;
1862                            break;
1863                        case 4:
1864                            encodedcontroller = _lev_ctrl_foot;
1865                            break;
1866                        case 12:
1867                            encodedcontroller = _lev_ctrl_effect1;
1868                            break;
1869                        case 13:
1870                            encodedcontroller = _lev_ctrl_effect2;
1871                            break;
1872                        case 16:
1873                            encodedcontroller = _lev_ctrl_genpurpose1;
1874                            break;
1875                        case 17:
1876                            encodedcontroller = _lev_ctrl_genpurpose2;
1877                            break;
1878                        case 18:
1879                            encodedcontroller = _lev_ctrl_genpurpose3;
1880                            break;
1881                        case 19:
1882                            encodedcontroller = _lev_ctrl_genpurpose4;
1883                            break;
1884                        case 5:
1885                            encodedcontroller = _lev_ctrl_portamentotime;
1886                            break;
1887                        case 64:
1888                            encodedcontroller = _lev_ctrl_sustainpedal;
1889                            break;
1890                        case 65:
1891                            encodedcontroller = _lev_ctrl_portamento;
1892                            break;
1893                        case 66:
1894                            encodedcontroller = _lev_ctrl_sostenutopedal;
1895                            break;
1896                        case 67:
1897                            encodedcontroller = _lev_ctrl_softpedal;
1898                            break;
1899                        case 80:
1900                            encodedcontroller = _lev_ctrl_genpurpose5;
1901                            break;
1902                        case 81:
1903                            encodedcontroller = _lev_ctrl_genpurpose6;
1904                            break;
1905                        case 82:
1906                            encodedcontroller = _lev_ctrl_genpurpose7;
1907                            break;
1908                        case 83:
1909                            encodedcontroller = _lev_ctrl_genpurpose8;
1910                            break;
1911                        case 91:
1912                            encodedcontroller = _lev_ctrl_effect1depth;
1913                            break;
1914                        case 92:
1915                            encodedcontroller = _lev_ctrl_effect2depth;
1916                            break;
1917                        case 93:
1918                            encodedcontroller = _lev_ctrl_effect3depth;
1919                            break;
1920                        case 94:
1921                            encodedcontroller = _lev_ctrl_effect4depth;
1922                            break;
1923                        case 95:
1924                            encodedcontroller = _lev_ctrl_effect5depth;
1925                            break;
1926                        default:
1927                            throw gig::Exception("leverage controller number is not supported by the gig format");
1928                    }
1929                default:
1930                    throw gig::Exception("Unknown leverage controller type.");
1931            }
1932            return encodedcontroller;
1933        }
1934    
1935      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1936          Instances--;          Instances--;
1937          if (!Instances) {          if (!Instances) {
# Line 1001  namespace gig { Line 1945  namespace gig {
1945              delete pVelocityTables;              delete pVelocityTables;
1946              pVelocityTables = NULL;              pVelocityTables = NULL;
1947          }          }
1948            if (VelocityTable) delete[] VelocityTable;
1949      }      }
1950    
1951      /**      /**
# Line 1018  namespace gig { Line 1963  namespace gig {
1963          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1964      }      }
1965    
1966        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1967            return pVelocityReleaseTable[MIDIKeyVelocity];
1968        }
1969    
1970        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1971            return pVelocityCutoffTable[MIDIKeyVelocity];
1972        }
1973    
1974        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1975    
1976            // line-segment approximations of the 15 velocity curves
1977    
1978            // linear
1979            const int lin0[] = { 1, 1, 127, 127 };
1980            const int lin1[] = { 1, 21, 127, 127 };
1981            const int lin2[] = { 1, 45, 127, 127 };
1982            const int lin3[] = { 1, 74, 127, 127 };
1983            const int lin4[] = { 1, 127, 127, 127 };
1984    
1985            // non-linear
1986            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1987            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1988                                 127, 127 };
1989            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1990                                 127, 127 };
1991            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1992                                 127, 127 };
1993            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1994    
1995            // special
1996            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1997                                 113, 127, 127, 127 };
1998            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1999                                 118, 127, 127, 127 };
2000            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2001                                 85, 90, 91, 127, 127, 127 };
2002            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2003                                 117, 127, 127, 127 };
2004            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2005                                 127, 127 };
2006    
2007            // this is only used by the VCF velocity curve
2008            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2009                                 91, 127, 127, 127 };
2010    
2011            const int* const curves[] = { non0, non1, non2, non3, non4,
2012                                          lin0, lin1, lin2, lin3, lin4,
2013                                          spe0, spe1, spe2, spe3, spe4, spe5 };
2014    
2015            double* const table = new double[128];
2016    
2017            const int* curve = curves[curveType * 5 + depth];
2018            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2019    
2020            table[0] = 0;
2021            for (int x = 1 ; x < 128 ; x++) {
2022    
2023                if (x > curve[2]) curve += 2;
2024                double y = curve[1] + (x - curve[0]) *
2025                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2026                y = y / 127;
2027    
2028                // Scale up for s > 20, down for s < 20. When
2029                // down-scaling, the curve still ends at 1.0.
2030                if (s < 20 && y >= 0.5)
2031                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2032                else
2033                    y = y * (s / 20.0);
2034                if (y > 1) y = 1;
2035    
2036                table[x] = y;
2037            }
2038            return table;
2039        }
2040    
2041    
2042  // *************** Region ***************  // *************** Region ***************
# Line 1026  namespace gig { Line 2045  namespace gig {
2045      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) {
2046          // Initialization          // Initialization
2047          Dimensions = 0;          Dimensions = 0;
2048          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
2049              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
2050          }          }
2051            Layers = 1;
2052            File* file = (File*) GetParent()->GetParent();
2053            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2054    
2055          // Actual Loading          // Actual Loading
2056    
# Line 1037  namespace gig { Line 2059  namespace gig {
2059          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2060          if (_3lnk) {          if (_3lnk) {
2061              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
2062              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
2063                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2064                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2065                    _3lnk->ReadUint8(); // probably the position of the dimension
2066                    _3lnk->ReadUint8(); // unknown
2067                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2068                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2069                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2070                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2071                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2072                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2073                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2074                  }                  }
2075                  else { // active dimension                  else { // active dimension
2076                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2077                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2078                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2079                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2080                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2081                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
2082                                                                                                    : split_type_normal;                                                             dimension == dimension_keyboard ||
2083                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point                                                             dimension == dimension_roundrobin ||
2084                                                               dimension == dimension_random) ? split_type_bit
2085                                                                                              : split_type_normal;
2086                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2087                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2088                                                                                     : 0;                                                                                     : 0;
2089                      Dimensions++;                      Dimensions++;
                 }  
                 _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition  
             }  
2090    
2091              // check velocity dimension (if there is one) for custom defined zone ranges                      // if this is a layer dimension, remember the amount of layers
2092              for (uint i = 0; i < Dimensions; i++) {                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
                 dimension_def_t* pDimDef = pDimensionDefinitions + i;  
                 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];  
                         unsigned int bits[5] = {0,0,0,0,0};  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);  
   
                             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;  
                             }  
                         }  
                     }  
2093                  }                  }
2094                    _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2095              }              }
2096                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2097    
2098                // if there's a velocity dimension and custom velocity zone splits are used,
2099                // update the VelocityTables in the dimension regions
2100                UpdateVelocityTable();
2101    
2102                // jump to start of the wave pool indices (if not already there)
2103                if (file->pVersion && file->pVersion->major == 3)
2104                    _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2105                else
2106                    _3lnk->SetPos(44);
2107    
2108              // load sample references              // load sample references
             _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)  
2109              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2110                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2111                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2112                }
2113            }
2114    
2115            // make sure there is at least one dimension region
2116            if (!DimensionRegions) {
2117                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2118                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2119                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2120                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2121                DimensionRegions = 1;
2122            }
2123        }
2124    
2125        /**
2126         * Apply Region settings and all its DimensionRegions to the respective
2127         * RIFF chunks. You have to call File::Save() to make changes persistent.
2128         *
2129         * Usually there is absolutely no need to call this method explicitly.
2130         * It will be called automatically when File::Save() was called.
2131         *
2132         * @throws gig::Exception if samples cannot be dereferenced
2133         */
2134        void Region::UpdateChunks() {
2135            // first update base class's chunks
2136            DLS::Region::UpdateChunks();
2137    
2138            // update dimension region's chunks
2139            for (int i = 0; i < DimensionRegions; i++) {
2140                pDimensionRegions[i]->UpdateChunks();
2141            }
2142    
2143            File* pFile = (File*) GetParent()->GetParent();
2144            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2145            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2146    
2147            // make sure '3lnk' chunk exists
2148            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2149            if (!_3lnk) {
2150                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2151                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2152            }
2153    
2154            // update dimension definitions in '3lnk' chunk
2155            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2156            for (int i = 0; i < iMaxDimensions; i++) {
2157                pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;
2158                pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2159                // next 2 bytes unknown
2160                pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2161                // next 3 bytes unknown
2162            }
2163    
2164            // update wave pool table in '3lnk' chunk
2165            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2166            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2167                int iWaveIndex = -1;
2168                if (i < DimensionRegions) {
2169                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2170                    File::SampleList::iterator iter = pFile->pSamples->begin();
2171                    File::SampleList::iterator end  = pFile->pSamples->end();
2172                    for (int index = 0; iter != end; ++iter, ++index) {
2173                        if (*iter == pDimensionRegions[i]->pSample) {
2174                            iWaveIndex = index;
2175                            break;
2176                        }
2177                    }
2178                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2179              }              }
2180                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2181          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2182      }      }
2183    
2184      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1121  namespace gig { Line 2197  namespace gig {
2197          }          }
2198      }      }
2199    
2200      Region::~Region() {      void Region::UpdateVelocityTable() {
2201          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2202              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2203            for (int i = 0 ; i < Dimensions ; i++) {
2204                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2205                    veldim = i;
2206                    break;
2207                }
2208          }          }
2209          for (int i = 0; i < 32; i++) {          if (veldim == -1) return;
2210    
2211            int step = 1;
2212            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2213            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2214            int end = step * pDimensionDefinitions[veldim].zones;
2215    
2216            // loop through all dimension regions for all dimensions except the velocity dimension
2217            int dim[8] = { 0 };
2218            for (int i = 0 ; i < DimensionRegions ; i++) {
2219    
2220                if (pDimensionRegions[i]->VelocityUpperLimit) {
2221                    // create the velocity table
2222                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2223                    if (!table) {
2224                        table = new uint8_t[128];
2225                        pDimensionRegions[i]->VelocityTable = table;
2226                    }
2227                    int tableidx = 0;
2228                    int velocityZone = 0;
2229                    for (int k = i ; k < end ; k += step) {
2230                        DimensionRegion *d = pDimensionRegions[k];
2231                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2232                        velocityZone++;
2233                    }
2234                } else {
2235                    if (pDimensionRegions[i]->VelocityTable) {
2236                        delete[] pDimensionRegions[i]->VelocityTable;
2237                        pDimensionRegions[i]->VelocityTable = 0;
2238                    }
2239                }
2240    
2241                int j;
2242                int shift = 0;
2243                for (j = 0 ; j < Dimensions ; j++) {
2244                    if (j == veldim) i += skipveldim; // skip velocity dimension
2245                    else {
2246                        dim[j]++;
2247                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2248                        else {
2249                            // skip unused dimension regions
2250                            dim[j] = 0;
2251                            i += ((1 << pDimensionDefinitions[j].bits) -
2252                                  pDimensionDefinitions[j].zones) << shift;
2253                        }
2254                    }
2255                    shift += pDimensionDefinitions[j].bits;
2256                }
2257                if (j == Dimensions) break;
2258            }
2259        }
2260    
2261        /** @brief Einstein would have dreamed of it - create a new dimension.
2262         *
2263         * Creates a new dimension with the dimension definition given by
2264         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2265         * There is a hard limit of dimensions and total amount of "bits" all
2266         * dimensions can have. This limit is dependant to what gig file format
2267         * version this file refers to. The gig v2 (and lower) format has a
2268         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2269         * format has a limit of 8.
2270         *
2271         * @param pDimDef - defintion of the new dimension
2272         * @throws gig::Exception if dimension of the same type exists already
2273         * @throws gig::Exception if amount of dimensions or total amount of
2274         *                        dimension bits limit is violated
2275         */
2276        void Region::AddDimension(dimension_def_t* pDimDef) {
2277            // check if max. amount of dimensions reached
2278            File* file = (File*) GetParent()->GetParent();
2279            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2280            if (Dimensions >= iMaxDimensions)
2281                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2282            // check if max. amount of dimension bits reached
2283            int iCurrentBits = 0;
2284            for (int i = 0; i < Dimensions; i++)
2285                iCurrentBits += pDimensionDefinitions[i].bits;
2286            if (iCurrentBits >= iMaxDimensions)
2287                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2288            const int iNewBits = iCurrentBits + pDimDef->bits;
2289            if (iNewBits > iMaxDimensions)
2290                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2291            // check if there's already a dimensions of the same type
2292            for (int i = 0; i < Dimensions; i++)
2293                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2294                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2295    
2296            // assign definition of new dimension
2297            pDimensionDefinitions[Dimensions] = *pDimDef;
2298    
2299            // create new dimension region(s) for this new dimension
2300            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2301                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2302                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2303                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2304                DimensionRegions++;
2305            }
2306    
2307            Dimensions++;
2308    
2309            // if this is a layer dimension, update 'Layers' attribute
2310            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2311    
2312            UpdateVelocityTable();
2313        }
2314    
2315        /** @brief Delete an existing dimension.
2316         *
2317         * Deletes the dimension given by \a pDimDef and deletes all respective
2318         * dimension regions, that is all dimension regions where the dimension's
2319         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2320         * for example this would delete all dimension regions for the case(s)
2321         * where the sustain pedal is pressed down.
2322         *
2323         * @param pDimDef - dimension to delete
2324         * @throws gig::Exception if given dimension cannot be found
2325         */
2326        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2327            // get dimension's index
2328            int iDimensionNr = -1;
2329            for (int i = 0; i < Dimensions; i++) {
2330                if (&pDimensionDefinitions[i] == pDimDef) {
2331                    iDimensionNr = i;
2332                    break;
2333                }
2334            }
2335            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2336    
2337            // get amount of bits below the dimension to delete
2338            int iLowerBits = 0;
2339            for (int i = 0; i < iDimensionNr; i++)
2340                iLowerBits += pDimensionDefinitions[i].bits;
2341    
2342            // get amount ot bits above the dimension to delete
2343            int iUpperBits = 0;
2344            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2345                iUpperBits += pDimensionDefinitions[i].bits;
2346    
2347            // delete dimension regions which belong to the given dimension
2348            // (that is where the dimension's bit > 0)
2349            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2350                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2351                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2352                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2353                                        iObsoleteBit << iLowerBits |
2354                                        iLowerBit;
2355                        delete pDimensionRegions[iToDelete];
2356                        pDimensionRegions[iToDelete] = NULL;
2357                        DimensionRegions--;
2358                    }
2359                }
2360            }
2361    
2362            // defrag pDimensionRegions array
2363            // (that is remove the NULL spaces within the pDimensionRegions array)
2364            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2365                if (!pDimensionRegions[iTo]) {
2366                    if (iFrom <= iTo) iFrom = iTo + 1;
2367                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2368                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2369                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2370                        pDimensionRegions[iFrom] = NULL;
2371                    }
2372                }
2373            }
2374    
2375            // 'remove' dimension definition
2376            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2377                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2378            }
2379            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2380            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2381            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2382    
2383            Dimensions--;
2384    
2385            // if this was a layer dimension, update 'Layers' attribute
2386            if (pDimDef->dimension == dimension_layer) Layers = 1;
2387        }
2388    
2389        Region::~Region() {
2390            for (int i = 0; i < 256; i++) {
2391              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2392          }          }
2393      }      }
# Line 1143  namespace gig { Line 2405  namespace gig {
2405       * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,       * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
2406       * etc.).       * etc.).
2407       *       *
2408       * @param  Dim4Val  MIDI controller value (0-127) for dimension 4       * @param  DimValues  MIDI controller values (0-127) for dimension 0 to 7
      * @param  Dim3Val  MIDI controller value (0-127) for dimension 3  
      * @param  Dim2Val  MIDI controller value (0-127) for dimension 2  
      * @param  Dim1Val  MIDI controller value (0-127) for dimension 1  
      * @param  Dim0Val  MIDI controller value (0-127) for dimension 0  
2409       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
2410       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
2411       * @see             Dimensions       * @see             Dimensions
2412       */       */
2413      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2414          uint8_t bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits;
2415            int veldim = -1;
2416            int velbitpos;
2417            int bitpos = 0;
2418            int dimregidx = 0;
2419          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2420              switch (pDimensionDefinitions[i].split_type) {              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2421                  case split_type_normal:                  // the velocity dimension must be handled after the other dimensions
2422                      bits[i] /= pDimensionDefinitions[i].zone_size;                  veldim = i;
2423                      break;                  velbitpos = bitpos;
2424                  case split_type_customvelocity:              } else {
2425                      bits[i] = VelocityTable[bits[i]];                  switch (pDimensionDefinitions[i].split_type) {
2426                      break;                      case split_type_normal:
2427                  case split_type_bit: // the value is already the sought dimension bit number                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2428                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          break;
2429                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                      case split_type_bit: // the value is already the sought dimension bit number
2430                      break;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2431                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2432                            break;
2433                    }
2434                    dimregidx |= bits << bitpos;
2435              }              }
2436                bitpos += pDimensionDefinitions[i].bits;
2437          }          }
2438          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2439            if (veldim != -1) {
2440                // (dimreg is now the dimension region for the lowest velocity)
2441                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2442                    bits = dimreg->VelocityTable[DimValues[veldim]];
2443                else // normal split type
2444                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2445    
2446                dimregidx |= bits << velbitpos;
2447                dimreg = pDimensionRegions[dimregidx];
2448            }
2449            return dimreg;
2450      }      }
2451    
2452      /**      /**
# Line 1176  namespace gig { Line 2454  namespace gig {
2454       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
2455       * instead of calling this method directly!       * instead of calling this method directly!
2456       *       *
2457       * @param Dim4Bit  Bit number for dimension 4       * @param DimBits  Bit numbers for dimension 0 to 7
      * @param Dim3Bit  Bit number for dimension 3  
      * @param Dim2Bit  Bit number for dimension 2  
      * @param Dim1Bit  Bit number for dimension 1  
      * @param Dim0Bit  Bit number for dimension 0  
2458       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
2459       *                 bit numbers       *                 bit numbers
2460       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
2461       */       */
2462      DimensionRegion* Region::GetDimensionRegionByBit(uint8_t Dim4Bit, uint8_t Dim3Bit, uint8_t Dim2Bit, uint8_t Dim1Bit, uint8_t Dim0Bit) {      DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
2463          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
2464                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
2465                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
2466                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
2467                                                      << pDimensionDefinitions[2].bits | DimBits[2])
2468                                                      << pDimensionDefinitions[1].bits | DimBits[1])
2469                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
2470      }      }
2471    
2472      /**      /**
# Line 1206  namespace gig { Line 2483  namespace gig {
2483          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2484      }      }
2485    
2486      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2487            if ((int32_t)WavePoolTableIndex == -1) return NULL;
2488          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2489            if (!file->pWavePoolTable) return NULL;
2490          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2491          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2492            Sample* sample = file->GetFirstSample(pProgress);
2493          while (sample) {          while (sample) {
2494              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2495                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2496              sample = file->GetNextSample();              sample = file->GetNextSample();
2497          }          }
2498          return NULL;          return NULL;
# Line 1222  namespace gig { Line 2503  namespace gig {
2503  // *************** Instrument ***************  // *************** Instrument ***************
2504  // *  // *
2505    
2506      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) {
2507          // Initialization          // Initialization
2508          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2509    
2510          // Loading          // Loading
2511          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1241  namespace gig { Line 2521  namespace gig {
2521                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2522                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2523              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2524          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2525    
2526            if (!pRegions) pRegions = new RegionList;
2527          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2528          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2529          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2530          RIFF::List* rgn = lrgn->GetFirstSubList();              while (rgn) {
2531          unsigned int iRegion = 0;                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2532          while (rgn) {                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2533              if (rgn->GetListType() == LIST_TYPE_RGN) {                      pRegions->push_back(new Region(this, rgn));
2534                  pRegions[iRegion] = new Region(this, rgn);                  }
2535                  iRegion++;                  rgn = lrgn->GetNextSubList();
             }  
             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];  
2536              }              }
2537                // Creating Region Key Table for fast lookup
2538                UpdateRegionKeyTable();
2539          }          }
2540    
2541            __notify_progress(pProgress, 1.0f); // notify done
2542      }      }
2543    
2544      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2545          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2546              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2547                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2548                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2549                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2550                    RegionKeyTable[iKey] = pRegion;
2551              }              }
             delete[] pRegions;  
2552          }          }
2553      }      }
2554    
2555        Instrument::~Instrument() {
2556        }
2557    
2558        /**
2559         * Apply Instrument with all its Regions to the respective RIFF chunks.
2560         * You have to call File::Save() to make changes persistent.
2561         *
2562         * Usually there is absolutely no need to call this method explicitly.
2563         * It will be called automatically when File::Save() was called.
2564         *
2565         * @throws gig::Exception if samples cannot be dereferenced
2566         */
2567        void Instrument::UpdateChunks() {
2568            // first update base classes' chunks
2569            DLS::Instrument::UpdateChunks();
2570    
2571            // update Regions' chunks
2572            {
2573                RegionList::iterator iter = pRegions->begin();
2574                RegionList::iterator end  = pRegions->end();
2575                for (; iter != end; ++iter)
2576                    (*iter)->UpdateChunks();
2577            }
2578    
2579            // make sure 'lart' RIFF list chunk exists
2580            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2581            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2582            // make sure '3ewg' RIFF chunk exists
2583            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2584            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2585            // update '3ewg' RIFF chunk
2586            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2587            memcpy(&pData[0], &EffectSend, 2);
2588            memcpy(&pData[2], &Attenuation, 4);
2589            memcpy(&pData[6], &FineTune, 2);
2590            memcpy(&pData[8], &PitchbendRange, 2);
2591            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2592                                        DimensionKeyRange.low << 1;
2593            memcpy(&pData[10], &dimkeystart, 1);
2594            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2595        }
2596    
2597      /**      /**
2598       * Returns the appropriate Region for a triggered note.       * Returns the appropriate Region for a triggered note.
2599       *       *
# Line 1283  namespace gig { Line 2602  namespace gig {
2602       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2603       */       */
2604      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2605          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2606          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2607    
2608          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2609              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2610                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1300  namespace gig { Line 2620  namespace gig {
2620       * @see      GetNextRegion()       * @see      GetNextRegion()
2621       */       */
2622      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2623          if (!Regions) return NULL;          if (!pRegions) return NULL;
2624          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2625          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2626      }      }
2627    
2628      /**      /**
# Line 1314  namespace gig { Line 2634  namespace gig {
2634       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2635       */       */
2636      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2637          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (!pRegions) return NULL;
2638          return pRegions[RegionIndex++];          RegionsIterator++;
2639            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2640        }
2641    
2642        Region* Instrument::AddRegion() {
2643            // create new Region object (and its RIFF chunks)
2644            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2645            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2646            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2647            Region* pNewRegion = new Region(this, rgn);
2648            pRegions->push_back(pNewRegion);
2649            Regions = pRegions->size();
2650            // update Region key table for fast lookup
2651            UpdateRegionKeyTable();
2652            // done
2653            return pNewRegion;
2654        }
2655    
2656        void Instrument::DeleteRegion(Region* pRegion) {
2657            if (!pRegions) return;
2658            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2659            // update Region key table for fast lookup
2660            UpdateRegionKeyTable();
2661      }      }
2662    
2663    
# Line 1323  namespace gig { Line 2665  namespace gig {
2665  // *************** File ***************  // *************** File ***************
2666  // *  // *
2667    
2668        File::File() : DLS::File() {
2669        }
2670    
2671      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
         pSamples     = NULL;  
         pInstruments = NULL;  
2672      }      }
2673    
2674      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
2675          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
2676          if (!pSamples) return NULL;          if (!pSamples) return NULL;
2677          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
2678          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1341  namespace gig { Line 2684  namespace gig {
2684          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2685      }      }
2686    
2687        /** @brief Add a new sample.
2688         *
2689         * This will create a new Sample object for the gig file. You have to
2690         * call Save() to make this persistent to the file.
2691         *
2692         * @returns pointer to new Sample object
2693         */
2694        Sample* File::AddSample() {
2695           if (!pSamples) LoadSamples();
2696           __ensureMandatoryChunksExist();
2697           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2698           // create new Sample object and its respective 'wave' list chunk
2699           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2700           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2701           pSamples->push_back(pSample);
2702           return pSample;
2703        }
2704    
2705        /** @brief Delete a sample.
2706         *
2707         * This will delete the given Sample object from the gig file. You have
2708         * to call Save() to make this persistent to the file.
2709         *
2710         * @param pSample - sample to delete
2711         * @throws gig::Exception if given sample could not be found
2712         */
2713        void File::DeleteSample(Sample* pSample) {
2714            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2715            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2716            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2717            pSamples->erase(iter);
2718            delete pSample;
2719        }
2720    
2721      void File::LoadSamples() {      void File::LoadSamples() {
2722          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          LoadSamples(NULL);
2723          if (wvpl) {      }
2724              unsigned long wvplFileOffset = wvpl->GetFilePos();  
2725              RIFF::List* wave = wvpl->GetFirstSubList();      void File::LoadSamples(progress_t* pProgress) {
2726              while (wave) {          if (!pSamples) pSamples = new SampleList;
2727                  if (wave->GetListType() == LIST_TYPE_WAVE) {  
2728                      if (!pSamples) pSamples = new SampleList;          RIFF::File* file = pRIFF;
2729                      unsigned long waveFileOffset = wave->GetFilePos();  
2730                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          // just for progress calculation
2731            int iSampleIndex  = 0;
2732            int iTotalSamples = WavePoolCount;
2733    
2734            // check if samples should be loaded from extension files
2735            int lastFileNo = 0;
2736            for (int i = 0 ; i < WavePoolCount ; i++) {
2737                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2738            }
2739            String name(pRIFF->GetFileName());
2740            int nameLen = name.length();
2741            char suffix[6];
2742            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2743    
2744            for (int fileNo = 0 ; ; ) {
2745                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2746                if (wvpl) {
2747                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2748                    RIFF::List* wave = wvpl->GetFirstSubList();
2749                    while (wave) {
2750                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2751                            // notify current progress
2752                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2753                            __notify_progress(pProgress, subprogress);
2754    
2755                            unsigned long waveFileOffset = wave->GetFilePos();
2756                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2757    
2758                            iSampleIndex++;
2759                        }
2760                        wave = wvpl->GetNextSubList();
2761                  }                  }
2762                  wave = wvpl->GetNextSubList();  
2763              }                  if (fileNo == lastFileNo) break;
2764    
2765                    // open extension file (*.gx01, *.gx02, ...)
2766                    fileNo++;
2767                    sprintf(suffix, ".gx%02d", fileNo);
2768                    name.replace(nameLen, 5, suffix);
2769                    file = new RIFF::File(name);
2770                    ExtensionFiles.push_back(file);
2771                } else break;
2772          }          }
2773          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2774            __notify_progress(pProgress, 1.0); // notify done
2775      }      }
2776    
2777      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2778          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2779          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2780          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2781          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2782      }      }
2783    
2784      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2785          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2786          InstrumentsIterator++;          InstrumentsIterator++;
2787          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2788      }      }
2789    
2790      /**      /**
2791       * Returns the instrument with the given index.       * Returns the instrument with the given index.
2792       *       *
2793         * @param index     - number of the sought instrument (0..n)
2794         * @param pProgress - optional: callback function for progress notification
2795       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
2796       */       */
2797      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2798          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
2799                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2800    
2801                // sample loading subtask
2802                progress_t subprogress;
2803                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2804                __notify_progress(&subprogress, 0.0f);
2805                GetFirstSample(&subprogress); // now force all samples to be loaded
2806                __notify_progress(&subprogress, 1.0f);
2807    
2808                // instrument loading subtask
2809                if (pProgress && pProgress->callback) {
2810                    subprogress.__range_min = subprogress.__range_max;
2811                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2812                }
2813                __notify_progress(&subprogress, 0.0f);
2814                LoadInstruments(&subprogress);
2815                __notify_progress(&subprogress, 1.0f);
2816            }
2817          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2818          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2819          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2820              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2821              InstrumentsIterator++;              InstrumentsIterator++;
2822          }          }
2823          return NULL;          return NULL;
2824      }      }
2825    
2826        /** @brief Add a new instrument definition.
2827         *
2828         * This will create a new Instrument object for the gig file. You have
2829         * to call Save() to make this persistent to the file.
2830         *
2831         * @returns pointer to new Instrument object
2832         */
2833        Instrument* File::AddInstrument() {
2834           if (!pInstruments) LoadInstruments();
2835           __ensureMandatoryChunksExist();
2836           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2837           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2838           Instrument* pInstrument = new Instrument(this, lstInstr);
2839           pInstruments->push_back(pInstrument);
2840           return pInstrument;
2841        }
2842    
2843        /** @brief Delete an instrument.
2844         *
2845         * This will delete the given Instrument object from the gig file. You
2846         * have to call Save() to make this persistent to the file.
2847         *
2848         * @param pInstrument - instrument to delete
2849         * @throws gig::Excption if given instrument could not be found
2850         */
2851        void File::DeleteInstrument(Instrument* pInstrument) {
2852            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2853            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2854            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2855            pInstruments->erase(iter);
2856            delete pInstrument;
2857        }
2858    
2859      void File::LoadInstruments() {      void File::LoadInstruments() {
2860            LoadInstruments(NULL);
2861        }
2862    
2863        void File::LoadInstruments(progress_t* pProgress) {
2864            if (!pInstruments) pInstruments = new InstrumentList;
2865          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2866          if (lstInstruments) {          if (lstInstruments) {
2867                int iInstrumentIndex = 0;
2868              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2869              while (lstInstr) {              while (lstInstr) {
2870                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
2871                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
2872                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2873                        __notify_progress(pProgress, localProgress);
2874    
2875                        // divide local progress into subprogress for loading current Instrument
2876                        progress_t subprogress;
2877                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2878    
2879                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2880    
2881                        iInstrumentIndex++;
2882                  }                  }
2883                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
2884              }              }
2885                __notify_progress(pProgress, 1.0); // notify done
2886          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
2887      }      }
2888    
2889    
# Line 1414  namespace gig { Line 2898  namespace gig {
2898          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
2899      }      }
2900    
2901    
2902    // *************** functions ***************
2903    // *
2904    
2905        /**
2906         * Returns the name of this C++ library. This is usually "libgig" of
2907         * course. This call is equivalent to RIFF::libraryName() and
2908         * DLS::libraryName().
2909         */
2910        String libraryName() {
2911            return PACKAGE;
2912        }
2913    
2914        /**
2915         * Returns version of this C++ library. This call is equivalent to
2916         * RIFF::libraryVersion() and DLS::libraryVersion().
2917         */
2918        String libraryVersion() {
2919            return VERSION;
2920        }
2921    
2922  } // namespace gig  } // namespace gig

Legend:
Removed from v.241  
changed lines
  Added in v.902

  ViewVC Help
Powered by ViewVC