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

Legend:
Removed from v.345  
changed lines
  Added in v.1179

  ViewVC Help
Powered by ViewVC