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

Legend:
Removed from v.2  
changed lines
  Added in v.918

  ViewVC Help
Powered by ViewVC