/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Diff of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2 by schoenebeck, Sat Oct 25 20:15:04 2003 UTC revision 1950 by persson, Wed Jul 29 08:57:46 2009 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 by Christian Schoenebeck                           *   *   Copyright (C) 2003-2009 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 <algorithm>
29    #include <math.h>
30    #include <iostream>
31    
32    /// Initial size of the sample buffer which is used for decompression of
33    /// compressed sample wave streams - this value should always be bigger than
34    /// the biggest sample piece expected to be read by the sampler engine,
35    /// otherwise the buffer size will be raised at runtime and thus the buffer
36    /// reallocated which is time consuming and unefficient.
37    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
38    
39    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
40    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
41    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
42    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
43    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
44    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
45    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
46    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
47    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
48    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
49    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
50    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
51    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
52    
53  namespace gig {  namespace gig {
54    
55    // *************** progress_t ***************
56    // *
57    
58        progress_t::progress_t() {
59            callback    = NULL;
60            custom      = NULL;
61            __range_min = 0.0f;
62            __range_max = 1.0f;
63        }
64    
65        // private helper function to convert progress of a subprocess into the global progress
66        static void __notify_progress(progress_t* pProgress, float subprogress) {
67            if (pProgress && pProgress->callback) {
68                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
69                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
70                pProgress->factor         = totalprogress;
71                pProgress->callback(pProgress); // now actually notify about the progress
72            }
73        }
74    
75        // private helper function to divide a progress into subprogresses
76        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
77            if (pParentProgress && pParentProgress->callback) {
78                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
79                pSubProgress->callback    = pParentProgress->callback;
80                pSubProgress->custom      = pParentProgress->custom;
81                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
82                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
83            }
84        }
85    
86    
87    // *************** Internal functions for sample decompression ***************
88    // *
89    
90    namespace {
91    
92        inline int get12lo(const unsigned char* pSrc)
93        {
94            const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
95            return x & 0x800 ? x - 0x1000 : x;
96        }
97    
98        inline int get12hi(const unsigned char* pSrc)
99        {
100            const int x = pSrc[1] >> 4 | pSrc[2] << 4;
101            return x & 0x800 ? x - 0x1000 : x;
102        }
103    
104        inline int16_t get16(const unsigned char* pSrc)
105        {
106            return int16_t(pSrc[0] | pSrc[1] << 8);
107        }
108    
109        inline int get24(const unsigned char* pSrc)
110        {
111            const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
112            return x & 0x800000 ? x - 0x1000000 : x;
113        }
114    
115        inline void store24(unsigned char* pDst, int x)
116        {
117            pDst[0] = x;
118            pDst[1] = x >> 8;
119            pDst[2] = x >> 16;
120        }
121    
122        void Decompress16(int compressionmode, const unsigned char* params,
123                          int srcStep, int dstStep,
124                          const unsigned char* pSrc, int16_t* pDst,
125                          unsigned long currentframeoffset,
126                          unsigned long copysamples)
127        {
128            switch (compressionmode) {
129                case 0: // 16 bit uncompressed
130                    pSrc += currentframeoffset * srcStep;
131                    while (copysamples) {
132                        *pDst = get16(pSrc);
133                        pDst += dstStep;
134                        pSrc += srcStep;
135                        copysamples--;
136                    }
137                    break;
138    
139                case 1: // 16 bit compressed to 8 bit
140                    int y  = get16(params);
141                    int dy = get16(params + 2);
142                    while (currentframeoffset) {
143                        dy -= int8_t(*pSrc);
144                        y  -= dy;
145                        pSrc += srcStep;
146                        currentframeoffset--;
147                    }
148                    while (copysamples) {
149                        dy -= int8_t(*pSrc);
150                        y  -= dy;
151                        *pDst = y;
152                        pDst += dstStep;
153                        pSrc += srcStep;
154                        copysamples--;
155                    }
156                    break;
157            }
158        }
159    
160        void Decompress24(int compressionmode, const unsigned char* params,
161                          int dstStep, const unsigned char* pSrc, uint8_t* pDst,
162                          unsigned long currentframeoffset,
163                          unsigned long copysamples, int truncatedBits)
164        {
165            int y, dy, ddy, dddy;
166    
167    #define GET_PARAMS(params)                      \
168            y    = get24(params);                   \
169            dy   = y - get24((params) + 3);         \
170            ddy  = get24((params) + 6);             \
171            dddy = get24((params) + 9)
172    
173    #define SKIP_ONE(x)                             \
174            dddy -= (x);                            \
175            ddy  -= dddy;                           \
176            dy   =  -dy - ddy;                      \
177            y    += dy
178    
179    #define COPY_ONE(x)                             \
180            SKIP_ONE(x);                            \
181            store24(pDst, y << truncatedBits);      \
182            pDst += dstStep
183    
184            switch (compressionmode) {
185                case 2: // 24 bit uncompressed
186                    pSrc += currentframeoffset * 3;
187                    while (copysamples) {
188                        store24(pDst, get24(pSrc) << truncatedBits);
189                        pDst += dstStep;
190                        pSrc += 3;
191                        copysamples--;
192                    }
193                    break;
194    
195                case 3: // 24 bit compressed to 16 bit
196                    GET_PARAMS(params);
197                    while (currentframeoffset) {
198                        SKIP_ONE(get16(pSrc));
199                        pSrc += 2;
200                        currentframeoffset--;
201                    }
202                    while (copysamples) {
203                        COPY_ONE(get16(pSrc));
204                        pSrc += 2;
205                        copysamples--;
206                    }
207                    break;
208    
209                case 4: // 24 bit compressed to 12 bit
210                    GET_PARAMS(params);
211                    while (currentframeoffset > 1) {
212                        SKIP_ONE(get12lo(pSrc));
213                        SKIP_ONE(get12hi(pSrc));
214                        pSrc += 3;
215                        currentframeoffset -= 2;
216                    }
217                    if (currentframeoffset) {
218                        SKIP_ONE(get12lo(pSrc));
219                        currentframeoffset--;
220                        if (copysamples) {
221                            COPY_ONE(get12hi(pSrc));
222                            pSrc += 3;
223                            copysamples--;
224                        }
225                    }
226                    while (copysamples > 1) {
227                        COPY_ONE(get12lo(pSrc));
228                        COPY_ONE(get12hi(pSrc));
229                        pSrc += 3;
230                        copysamples -= 2;
231                    }
232                    if (copysamples) {
233                        COPY_ONE(get12lo(pSrc));
234                    }
235                    break;
236    
237                case 5: // 24 bit compressed to 8 bit
238                    GET_PARAMS(params);
239                    while (currentframeoffset) {
240                        SKIP_ONE(int8_t(*pSrc++));
241                        currentframeoffset--;
242                    }
243                    while (copysamples) {
244                        COPY_ONE(int8_t(*pSrc++));
245                        copysamples--;
246                    }
247                    break;
248            }
249        }
250    
251        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
252        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
253        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
254        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
255    }
256    
257    
258    
259    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
260    // *
261    
262        static uint32_t* __initCRCTable() {
263            static uint32_t res[256];
264    
265            for (int i = 0 ; i < 256 ; i++) {
266                uint32_t c = i;
267                for (int j = 0 ; j < 8 ; j++) {
268                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269                }
270                res[i] = c;
271            }
272            return res;
273        }
274    
275        static const uint32_t* __CRCTable = __initCRCTable();
276    
277        /**
278         * Initialize a CRC variable.
279         *
280         * @param crc - variable to be initialized
281         */
282        inline static void __resetCRC(uint32_t& crc) {
283            crc = 0xffffffff;
284        }
285    
286        /**
287         * Used to calculate checksums of the sample data in a gig file. The
288         * checksums are stored in the 3crc chunk of the gig file and
289         * automatically updated when a sample is written with Sample::Write().
290         *
291         * One should call __resetCRC() to initialize the CRC variable to be
292         * used before calling this function the first time.
293         *
294         * After initializing the CRC variable one can call this function
295         * arbitrary times, i.e. to split the overall CRC calculation into
296         * steps.
297         *
298         * Once the whole data was processed by __calculateCRC(), one should
299         * call __encodeCRC() to get the final CRC result.
300         *
301         * @param buf     - pointer to data the CRC shall be calculated of
302         * @param bufSize - size of the data to be processed
303         * @param crc     - variable the CRC sum shall be stored to
304         */
305        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306            for (int i = 0 ; i < bufSize ; i++) {
307                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308            }
309        }
310    
311        /**
312         * Returns the final CRC result.
313         *
314         * @param crc - variable previously passed to __calculateCRC()
315         */
316        inline static uint32_t __encodeCRC(const uint32_t& crc) {
317            return crc ^ 0xffffffff;
318        }
319    
320    
321    
322    // *************** Other Internal functions  ***************
323    // *
324    
325        static split_type_t __resolveSplitType(dimension_t dimension) {
326            return (
327                dimension == dimension_layer ||
328                dimension == dimension_samplechannel ||
329                dimension == dimension_releasetrigger ||
330                dimension == dimension_keyboard ||
331                dimension == dimension_roundrobin ||
332                dimension == dimension_random ||
333                dimension == dimension_smartmidi ||
334                dimension == dimension_roundrobinkeyboard
335            ) ? split_type_bit : split_type_normal;
336        }
337    
338        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
339            return (dimension_definition.split_type == split_type_normal)
340            ? int(128.0 / dimension_definition.zones) : 0;
341        }
342    
343    
344    
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
348      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
349      void*         Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
350    
351      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
352         *
353         * Load an existing sample or create a new one. A 'wave' list chunk must
354         * be given to this constructor. In case the given 'wave' list chunk
355         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
356         * format and sample data will be loaded from there, otherwise default
357         * values will be used and those chunks will be created when
358         * File::Save() will be called later on.
359         *
360         * @param pFile          - pointer to gig::File where this sample is
361         *                         located (or will be located)
362         * @param waveList       - pointer to 'wave' list chunk which is (or
363         *                         will be) associated with this sample
364         * @param WavePoolOffset - offset of this sample data from wave pool
365         *                         ('wvpl') list chunk
366         * @param fileNo         - number of an extension file where this sample
367         *                         is located, 0 otherwise
368         */
369        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
370            static const DLS::Info::string_length_t fixedStringLengths[] = {
371                { CHUNK_ID_INAM, 64 },
372                { 0, 0 }
373            };
374            pInfo->SetFixedStringLengths(fixedStringLengths);
375          Instances++;          Instances++;
376            FileNo = fileNo;
377    
378          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          __resetCRC(crc);
379          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");  
380          SampleGroup = _3gix->ReadInt16();          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381            if (pCk3gix) {
382          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              uint16_t iSampleGroup = pCk3gix->ReadInt16();
383          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              pGroup = pFile->GetGroup(iSampleGroup);
384          Manufacturer      = smpl->ReadInt32();          } else { // '3gix' chunk missing
385          Product           = smpl->ReadInt32();              // by default assigned to that mandatory "Default Group"
386          SamplePeriod      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
387          MIDIUnityNote     = smpl->ReadInt32();          }
388          MIDIPitchFraction = smpl->ReadInt32();  
389          smpl->Read(&SMPTEFormat, 1, 4);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
390          SMPTEOffset       = smpl->ReadInt32();          if (pCkSmpl) {
391          Loops             = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
392          LoopID            = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
393          smpl->Read(&LoopType, 1, 4);              SamplePeriod  = pCkSmpl->ReadInt32();
394          LoopStart         = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
395          LoopEnd           = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
396          LoopFraction      = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
397          LoopPlayCount     = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
398                Loops         = pCkSmpl->ReadInt32();
399                pCkSmpl->ReadInt32(); // manufByt
400                LoopID        = pCkSmpl->ReadInt32();
401                pCkSmpl->Read(&LoopType, 1, 4);
402                LoopStart     = pCkSmpl->ReadInt32();
403                LoopEnd       = pCkSmpl->ReadInt32();
404                LoopFraction  = pCkSmpl->ReadInt32();
405                LoopPlayCount = pCkSmpl->ReadInt32();
406            } else { // 'smpl' chunk missing
407                // use default values
408                Manufacturer  = 0;
409                Product       = 0;
410                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
411                MIDIUnityNote = 60;
412                FineTune      = 0;
413                SMPTEFormat   = smpte_format_no_offset;
414                SMPTEOffset   = 0;
415                Loops         = 0;
416                LoopID        = 0;
417                LoopType      = loop_type_normal;
418                LoopStart     = 0;
419                LoopEnd       = 0;
420                LoopFraction  = 0;
421                LoopPlayCount = 0;
422            }
423    
424          FrameTable                 = NULL;          FrameTable                 = NULL;
425          SamplePos                  = 0;          SamplePos                  = 0;
# Line 62  namespace gig { Line 427  namespace gig {
427          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
428          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
429    
430          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
431    
432            RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
433            Compressed        = ewav;
434            Dithered          = false;
435            TruncatedBits     = 0;
436          if (Compressed) {          if (Compressed) {
437                uint32_t version = ewav->ReadInt32();
438                if (version == 3 && BitDepth == 24) {
439                    Dithered = ewav->ReadInt32();
440                    ewav->SetPos(Channels == 2 ? 84 : 64);
441                    TruncatedBits = ewav->ReadInt32();
442                }
443              ScanCompressedSample();              ScanCompressedSample();
444              if (!pDecompressionBuffer) {          }
445                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];  
446                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
447            if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
448                InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
449                InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
450            }
451            FrameOffset = 0; // just for streaming compressed samples
452    
453            LoopSize = LoopEnd - LoopStart + 1;
454        }
455    
456        /**
457         * Apply sample and its settings to the respective RIFF chunks. You have
458         * to call File::Save() to make changes persistent.
459         *
460         * Usually there is absolutely no need to call this method explicitly.
461         * It will be called automatically when File::Save() was called.
462         *
463         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
464         *                        was provided yet
465         * @throws gig::Exception if there is any invalid sample setting
466         */
467        void Sample::UpdateChunks() {
468            // first update base class's chunks
469            DLS::Sample::UpdateChunks();
470    
471            // make sure 'smpl' chunk exists
472            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
473            if (!pCkSmpl) {
474                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
475                memset(pCkSmpl->LoadChunkData(), 0, 60);
476            }
477            // update 'smpl' chunk
478            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
479            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
480            store32(&pData[0], Manufacturer);
481            store32(&pData[4], Product);
482            store32(&pData[8], SamplePeriod);
483            store32(&pData[12], MIDIUnityNote);
484            store32(&pData[16], FineTune);
485            store32(&pData[20], SMPTEFormat);
486            store32(&pData[24], SMPTEOffset);
487            store32(&pData[28], Loops);
488    
489            // we skip 'manufByt' for now (4 bytes)
490    
491            store32(&pData[36], LoopID);
492            store32(&pData[40], LoopType);
493            store32(&pData[44], LoopStart);
494            store32(&pData[48], LoopEnd);
495            store32(&pData[52], LoopFraction);
496            store32(&pData[56], LoopPlayCount);
497    
498            // make sure '3gix' chunk exists
499            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
500            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
501            // determine appropriate sample group index (to be stored in chunk)
502            uint16_t iSampleGroup = 0; // 0 refers to default sample group
503            File* pFile = static_cast<File*>(pParent);
504            if (pFile->pGroups) {
505                std::list<Group*>::iterator iter = pFile->pGroups->begin();
506                std::list<Group*>::iterator end  = pFile->pGroups->end();
507                for (int i = 0; iter != end; i++, iter++) {
508                    if (*iter == pGroup) {
509                        iSampleGroup = i;
510                        break; // found
511                    }
512              }              }
513          }          }
514          FrameOffset = 0; // just for streaming compressed samples          // update '3gix' chunk
515            pData = (uint8_t*) pCk3gix->LoadChunkData();
516            store16(&pData[0], iSampleGroup);
517      }      }
518    
519      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 79  namespace gig { Line 522  namespace gig {
522          this->SamplesTotal = 0;          this->SamplesTotal = 0;
523          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
524    
525            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
526            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
527    
528          // Scanning          // Scanning
529          pCkData->SetPos(0);          pCkData->SetPos(0);
530          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
531              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
532              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
533              this->SamplesTotal += 2048;                  // stored, to save some memory
534              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
535                  case 1:   // left channel compressed  
536                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
537                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
538                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
539                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
540    
541                    if (pCkData->RemainingBytes() <= frameSize) {
542                        SamplesInLastFrame =
543                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
544                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
545                        SamplesTotal += SamplesInLastFrame;
546                      break;                      break;
547                  case 257: // both channels compressed                  }
548                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
549                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
550                }
551            }
552            else { // Mono
553                for (int i = 0 ; ; i++) {
554                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
555    
556                    const int mode = pCkData->ReadUint8();
557                    if (mode > 5) throw gig::Exception("Unknown compression mode");
558                    const unsigned long frameSize = bytesPerFrame[mode];
559    
560                    if (pCkData->RemainingBytes() <= frameSize) {
561                        SamplesInLastFrame =
562                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
563                        SamplesTotal += SamplesInLastFrame;
564                      break;                      break;
565                  default: // both channels uncompressed                  }
566                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
567                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
568              }              }
569          }          }
570          pCkData->SetPos(0);          pCkData->SetPos(0);
571    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
572          // 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)
573          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
574          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 138  namespace gig { Line 604  namespace gig {
604       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
605       * 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
606       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
607       *       * @code
608       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
609       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
610         * @endcode
611       *       *
612       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
613       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 186  namespace gig { Line 653  namespace gig {
653       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
654       * 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
655       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
656       *       * @code
657       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
658       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
659       *       * @endcode
660       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
661       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
662       * 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 210  namespace gig { Line 677  namespace gig {
677          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
678          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
679          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
680            SetPos(0); // reset read position to begin of sample
681          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
682          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
683          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 247  namespace gig { Line 715  namespace gig {
715          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
716          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
717          RAMCache.Size   = 0;          RAMCache.Size   = 0;
718            RAMCache.NullExtensionSize = 0;
719        }
720    
721        /** @brief Resize sample.
722         *
723         * Resizes the sample's wave form data, that is the actual size of
724         * sample wave data possible to be written for this sample. This call
725         * will return immediately and just schedule the resize operation. You
726         * should call File::Save() to actually perform the resize operation(s)
727         * "physically" to the file. As this can take a while on large files, it
728         * is recommended to call Resize() first on all samples which have to be
729         * resized and finally to call File::Save() to perform all those resize
730         * operations in one rush.
731         *
732         * The actual size (in bytes) is dependant to the current FrameSize
733         * value. You may want to set FrameSize before calling Resize().
734         *
735         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
736         * enlarged samples before calling File::Save() as this might exceed the
737         * current sample's boundary!
738         *
739         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
740         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
741         * other formats will fail!
742         *
743         * @param iNewSize - new sample wave data size in sample points (must be
744         *                   greater than zero)
745         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
746         *                         or if \a iNewSize is less than 1
747         * @throws gig::Exception if existing sample is compressed
748         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
749         *      DLS::Sample::FormatTag, File::Save()
750         */
751        void Sample::Resize(int iNewSize) {
752            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
753            DLS::Sample::Resize(iNewSize);
754      }      }
755    
756      /**      /**
# Line 310  namespace gig { Line 814  namespace gig {
814      }      }
815    
816      /**      /**
817         * Reads \a SampleCount number of sample points from the position stored
818         * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
819         * the position within the sample respectively, this method honors the
820         * looping informations of the sample (if any). The sample wave stream
821         * will be decompressed on the fly if using a compressed sample. Use this
822         * method if you don't want to load the sample into RAM, thus for disk
823         * streaming. All this methods needs to know to proceed with streaming
824         * for the next time you call this method is stored in \a pPlaybackState.
825         * You have to allocate and initialize the playback_state_t structure by
826         * yourself before you use it to stream a sample:
827         * @code
828         * gig::playback_state_t playbackstate;
829         * playbackstate.position         = 0;
830         * playbackstate.reverse          = false;
831         * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
832         * @endcode
833         * You don't have to take care of things like if there is actually a loop
834         * defined or if the current read position is located within a loop area.
835         * The method already handles such cases by itself.
836         *
837         * <b>Caution:</b> If you are using more than one streaming thread, you
838         * have to use an external decompression buffer for <b>EACH</b>
839         * streaming thread to avoid race conditions and crashes!
840         *
841         * @param pBuffer          destination buffer
842         * @param SampleCount      number of sample points to read
843         * @param pPlaybackState   will be used to store and reload the playback
844         *                         state for the next ReadAndLoop() call
845         * @param pDimRgn          dimension region with looping information
846         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
847         * @returns                number of successfully read sample points
848         * @see                    CreateDecompressionBuffer()
849         */
850        unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
851                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
852            unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
853            uint8_t* pDst = (uint8_t*) pBuffer;
854    
855            SetPos(pPlaybackState->position); // recover position from the last time
856    
857            if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
858    
859                const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
860                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
861    
862                if (GetPos() <= loopEnd) {
863                    switch (loop.LoopType) {
864    
865                        case loop_type_bidirectional: { //TODO: not tested yet!
866                            do {
867                                // if not endless loop check if max. number of loop cycles have been passed
868                                if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
869    
870                                if (!pPlaybackState->reverse) { // forward playback
871                                    do {
872                                        samplestoloopend  = loopEnd - GetPos();
873                                        readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
874                                        samplestoread    -= readsamples;
875                                        totalreadsamples += readsamples;
876                                        if (readsamples == samplestoloopend) {
877                                            pPlaybackState->reverse = true;
878                                            break;
879                                        }
880                                    } while (samplestoread && readsamples);
881                                }
882                                else { // backward playback
883    
884                                    // as we can only read forward from disk, we have to
885                                    // determine the end position within the loop first,
886                                    // read forward from that 'end' and finally after
887                                    // reading, swap all sample frames so it reflects
888                                    // backward playback
889    
890                                    unsigned long swapareastart       = totalreadsamples;
891                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
892                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
893                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
894    
895                                    SetPos(reverseplaybackend);
896    
897                                    // read samples for backward playback
898                                    do {
899                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
900                                        samplestoreadinloop -= readsamples;
901                                        samplestoread       -= readsamples;
902                                        totalreadsamples    += readsamples;
903                                    } while (samplestoreadinloop && readsamples);
904    
905                                    SetPos(reverseplaybackend); // pretend we really read backwards
906    
907                                    if (reverseplaybackend == loop.LoopStart) {
908                                        pPlaybackState->loop_cycles_left--;
909                                        pPlaybackState->reverse = false;
910                                    }
911    
912                                    // reverse the sample frames for backward playback
913                                    if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
914                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
915                                }
916                            } while (samplestoread && readsamples);
917                            break;
918                        }
919    
920                        case loop_type_backward: { // TODO: not tested yet!
921                            // forward playback (not entered the loop yet)
922                            if (!pPlaybackState->reverse) do {
923                                samplestoloopend  = loopEnd - GetPos();
924                                readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
925                                samplestoread    -= readsamples;
926                                totalreadsamples += readsamples;
927                                if (readsamples == samplestoloopend) {
928                                    pPlaybackState->reverse = true;
929                                    break;
930                                }
931                            } while (samplestoread && readsamples);
932    
933                            if (!samplestoread) break;
934    
935                            // as we can only read forward from disk, we have to
936                            // determine the end position within the loop first,
937                            // read forward from that 'end' and finally after
938                            // reading, swap all sample frames so it reflects
939                            // backward playback
940    
941                            unsigned long swapareastart       = totalreadsamples;
942                            unsigned long loopoffset          = GetPos() - loop.LoopStart;
943                            unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
944                                                                                      : samplestoread;
945                            unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
946    
947                            SetPos(reverseplaybackend);
948    
949                            // read samples for backward playback
950                            do {
951                                // if not endless loop check if max. number of loop cycles have been passed
952                                if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
953                                samplestoloopend     = loopEnd - GetPos();
954                                readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
955                                samplestoreadinloop -= readsamples;
956                                samplestoread       -= readsamples;
957                                totalreadsamples    += readsamples;
958                                if (readsamples == samplestoloopend) {
959                                    pPlaybackState->loop_cycles_left--;
960                                    SetPos(loop.LoopStart);
961                                }
962                            } while (samplestoreadinloop && readsamples);
963    
964                            SetPos(reverseplaybackend); // pretend we really read backwards
965    
966                            // reverse the sample frames for backward playback
967                            SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
968                            break;
969                        }
970    
971                        default: case loop_type_normal: {
972                            do {
973                                // if not endless loop check if max. number of loop cycles have been passed
974                                if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
975                                samplestoloopend  = loopEnd - GetPos();
976                                readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
977                                samplestoread    -= readsamples;
978                                totalreadsamples += readsamples;
979                                if (readsamples == samplestoloopend) {
980                                    pPlaybackState->loop_cycles_left--;
981                                    SetPos(loop.LoopStart);
982                                }
983                            } while (samplestoread && readsamples);
984                            break;
985                        }
986                    }
987                }
988            }
989    
990            // read on without looping
991            if (samplestoread) do {
992                readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
993                samplestoread    -= readsamples;
994                totalreadsamples += readsamples;
995            } while (readsamples && samplestoread);
996    
997            // store current position
998            pPlaybackState->position = GetPos();
999    
1000            return totalreadsamples;
1001        }
1002    
1003        /**
1004       * Reads \a SampleCount number of sample points from the current       * Reads \a SampleCount number of sample points from the current
1005       * position into the buffer pointed by \a pBuffer and increments the       * position into the buffer pointed by \a pBuffer and increments the
1006       * position within the sample. The sample wave stream will be       * position within the sample. The sample wave stream will be
# Line 317  namespace gig { Line 1008  namespace gig {
1008       * 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,
1009       * thus for disk streaming.       * thus for disk streaming.
1010       *       *
1011         * <b>Caution:</b> If you are using more than one streaming thread, you
1012         * have to use an external decompression buffer for <b>EACH</b>
1013         * streaming thread to avoid race conditions and crashes!
1014         *
1015         * For 16 bit samples, the data in the buffer will be int16_t
1016         * (using native endianness). For 24 bit, the buffer will
1017         * contain three bytes per sample, little-endian.
1018         *
1019       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1020       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1021         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
1022       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1023       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
1024       */       */
1025      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1026          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize);          if (SampleCount == 0) return 0;
1027          else { //FIXME: no support for mono compressed samples yet, are there any?          if (!Compressed) {
1028              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              if (BitDepth == 24) {
1029              // best case needed buffer size (all frames compressed)                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1030              unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)              }
1031                                               (SampleCount >> 10) + // 10 bytes header per 2048 sample points              else { // 16 bit
1032                                               8194,                 // at least one worst case sample frame                  // (pCkData->Read does endian correction)
1033                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1034                                         : pCkData->Read(pBuffer, SampleCount, 2);
1035                }
1036            }
1037            else {
1038                if (this->SamplePos >= this->SamplesTotal) return 0;
1039                //TODO: efficiency: maybe we should test for an average compression rate
1040                unsigned long assumedsize      = GuessSize(SampleCount),
1041                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1042                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1043                            copysamples;                            copysamples, skipsamples,
1044              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
1045              this->FrameOffset = 0;              this->FrameOffset = 0;
1046    
1047              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1048                  // local buffer reallocation - hope this won't happen  
1049                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
1050                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
1051                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1052                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
1053                    remainingsamples = SampleCount;
1054                    assumedsize      = GuessSize(SampleCount);
1055              }              }
1056    
1057              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1058              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1059              int16_t* pDst = (int16_t*) pBuffer;              uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1060              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1061    
1062              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
1063                    unsigned long framesamples = SamplesPerFrame;
1064                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1065                  if (remainingbytes < 8194) {  
1066                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
1067                          this->SamplePos += (SampleCount - remainingsamples);  
1068                          //if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;                  if (Channels == 2) {
1069                          return (SampleCount - remainingsamples);                      mode_r = *pSrc++;
1070                        framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1071                        rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1072                        nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1073                        if (remainingbytes < framebytes) { // last frame in sample
1074                            framesamples = SamplesInLastFrame;
1075                            if (mode_l == 4 && (framesamples & 1)) {
1076                                rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1077                            }
1078                            else {
1079                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1080                            }
1081                        }
1082                    }
1083                    else {
1084                        framebytes = bytesPerFrame[mode_l] + 1;
1085                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1086                        if (remainingbytes < framebytes) {
1087                            framesamples = SamplesInLastFrame;
1088                      }                      }
                     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;  
1089                  }                  }
1090    
1091                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
1092                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
1093                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
1094                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
1095                            skipsamples = currentframeoffset;
1096                        }
1097                        else {
1098                            copysamples = 0;
1099                            skipsamples = framesamples;
1100                        }
1101                  }                  }
1102                  else {                  else {
1103                        // This frame has enough data for pBuffer, but not
1104                        // all of the frame is needed. Set file position
1105                        // to start of this frame for next call to Read.
1106                      copysamples = remainingsamples;                      copysamples = remainingsamples;
1107                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
1108                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1109                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
1110                      }                  }
1111                      else {                  remainingsamples -= copysamples;
1112    
1113                    if (remainingbytes > framebytes) {
1114                        remainingbytes -= framebytes;
1115                        if (remainingsamples == 0 &&
1116                            currentframeoffset + copysamples == framesamples) {
1117                            // This frame has enough data for pBuffer, and
1118                            // all of the frame is needed. Set file
1119                            // position to start of next frame for next
1120                            // call to Read. FrameOffset is 0.
1121                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
1122                      }                      }
1123                  }                  }
1124                    else remainingbytes = 0;
1125    
1126                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
1127                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
1128                  switch (compressionmode) {                  if (copysamples == 0) {
1129                      case 1: // left channel compressed                      // skip this frame
1130                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
1131                          if (!remainingsamples && copysamples == 2048)                  }
1132                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
1133                        const unsigned char* const param_l = pSrc;
1134                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
1135                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
1136                          while (currentframeoffset) {  
1137                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
1138                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
1139                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
1140                              currentframeoffset--;  
1141                          }                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1142                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
1143                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1144                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
1145                              *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  
1146                          }                          }
1147                          while (copysamples) {                          else { // Mono
1148                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1149                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
1150                              right  -= dright;                              pDst24 += copysamples * 3;
                             *pDst = right; pDst++;  
                             copysamples--;  
1151                          }                          }
1152                          break;                      }
1153                      case 257: // both channels compressed                      else { // 16 bit
1154                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
1155                          if (!remainingsamples && copysamples == 2048)  
1156                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
1157                            if (Channels == 2) { // Stereo
1158                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
1159                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
1160                          right  = *(int16_t*)pSrc; pSrc+=2;  
1161                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
1162                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1163                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1164                              left   -= dleft;                                           skipsamples, copysamples);
1165                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
1166                          }                          }
1167                          while (copysamples) {                          else { // Mono
1168                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
1169                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1170                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
1171                          }                          }
1172                          break;                      }
1173                      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;  
1174                  }                  }
1175              }  
1176                    // reload from disk to local buffer if needed
1177                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1178                        assumedsize    = GuessSize(remainingsamples);
1179                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1180                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1181                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1182                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1183                    }
1184                } // while
1185    
1186              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
1187              //if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1188              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
1189          }          }
1190      }      }
1191    
1192        /** @brief Write sample wave data.
1193         *
1194         * Writes \a SampleCount number of sample points from the buffer pointed
1195         * by \a pBuffer and increments the position within the sample. Use this
1196         * method to directly write the sample data to disk, i.e. if you don't
1197         * want or cannot load the whole sample data into RAM.
1198         *
1199         * You have to Resize() the sample to the desired size and call
1200         * File::Save() <b>before</b> using Write().
1201         *
1202         * Note: there is currently no support for writing compressed samples.
1203         *
1204         * For 16 bit samples, the data in the source buffer should be
1205         * int16_t (using native endianness). For 24 bit, the buffer
1206         * should contain three bytes per sample, little-endian.
1207         *
1208         * @param pBuffer     - source buffer
1209         * @param SampleCount - number of sample points to write
1210         * @throws DLS::Exception if current sample size is too small
1211         * @throws gig::Exception if sample is compressed
1212         * @see DLS::LoadSampleData()
1213         */
1214        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1215            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1216    
1217            // if this is the first write in this sample, reset the
1218            // checksum calculator
1219            if (pCkData->GetPos() == 0) {
1220                __resetCRC(crc);
1221            }
1222            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1223            unsigned long res;
1224            if (BitDepth == 24) {
1225                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1226            } else { // 16 bit
1227                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1228                                    : pCkData->Write(pBuffer, SampleCount, 2);
1229            }
1230            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1231    
1232            // if this is the last write, update the checksum chunk in the
1233            // file
1234            if (pCkData->GetPos() == pCkData->GetSize()) {
1235                File* pFile = static_cast<File*>(GetParent());
1236                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1237            }
1238            return res;
1239        }
1240    
1241        /**
1242         * Allocates a decompression buffer for streaming (compressed) samples
1243         * with Sample::Read(). If you are using more than one streaming thread
1244         * in your application you <b>HAVE</b> to create a decompression buffer
1245         * for <b>EACH</b> of your streaming threads and provide it with the
1246         * Sample::Read() call in order to avoid race conditions and crashes.
1247         *
1248         * You should free the memory occupied by the allocated buffer(s) once
1249         * you don't need one of your streaming threads anymore by calling
1250         * DestroyDecompressionBuffer().
1251         *
1252         * @param MaxReadSize - the maximum size (in sample points) you ever
1253         *                      expect to read with one Read() call
1254         * @returns allocated decompression buffer
1255         * @see DestroyDecompressionBuffer()
1256         */
1257        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1258            buffer_t result;
1259            const double worstCaseHeaderOverhead =
1260                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1261            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1262            result.pStart            = new int8_t[result.Size];
1263            result.NullExtensionSize = 0;
1264            return result;
1265        }
1266    
1267        /**
1268         * Free decompression buffer, previously created with
1269         * CreateDecompressionBuffer().
1270         *
1271         * @param DecompressionBuffer - previously allocated decompression
1272         *                              buffer to free
1273         */
1274        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1275            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1276                delete[] (int8_t*) DecompressionBuffer.pStart;
1277                DecompressionBuffer.pStart = NULL;
1278                DecompressionBuffer.Size   = 0;
1279                DecompressionBuffer.NullExtensionSize = 0;
1280            }
1281        }
1282    
1283        /**
1284         * Returns pointer to the Group this Sample belongs to. In the .gig
1285         * format a sample always belongs to one group. If it wasn't explicitly
1286         * assigned to a certain group, it will be automatically assigned to a
1287         * default group.
1288         *
1289         * @returns Sample's Group (never NULL)
1290         */
1291        Group* Sample::GetGroup() const {
1292            return pGroup;
1293        }
1294    
1295      Sample::~Sample() {      Sample::~Sample() {
1296          Instances--;          Instances--;
1297          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
1298                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1299                InternalDecompressionBuffer.pStart = NULL;
1300                InternalDecompressionBuffer.Size   = 0;
1301            }
1302          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1303          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1304      }      }
# Line 491  namespace gig { Line 1308  namespace gig {
1308  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1309  // *  // *
1310    
1311      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      uint                               DimensionRegion::Instances       = 0;
1312          memcpy(&Crossfade, &SamplerOptions, 4);      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1313    
1314        DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1315            Instances++;
1316    
1317            pSample = NULL;
1318            pRegion = pParent;
1319    
1320            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1321            else memset(&Crossfade, 0, 4);
1322    
1323            if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1324    
1325          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1326          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1327          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1328          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1329          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1330          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1331          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1332          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1333          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1334          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1335          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1336          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1337          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1338          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1339          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1340          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1341          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1342          EG1Controller       = static_cast<eg1_ctrl_t>(_3ewa->ReadUint8());              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1343          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1344          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1345          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1346          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1347          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1348          EG2Controller       = static_cast<eg2_ctrl_t>(_3ewa->ReadUint8());              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1349          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1350          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1351          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1352          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1353          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1354          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1355          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1356          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1357          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1358          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1359          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1360          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1361          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1362          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1363          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1364          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1365          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1366          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1367          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1368          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1369          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1370          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1371          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1372          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1373          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1374          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1375          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1376          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1377              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1378              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1379          }                  VelocityResponseDepth = velocityresponse;
1380          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1381              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1382              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1383          }              } else if (velocityresponse < 15) {
1384          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1385              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1386              VelocityResponseDepth = velocityresponse - 10;              } else {
1387                    VelocityResponseCurve = curve_type_unknown;
1388                    VelocityResponseDepth = 0;
1389                }
1390                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1391                if (releasevelocityresponse < 5) {
1392                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1393                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1394                } else if (releasevelocityresponse < 10) {
1395                    ReleaseVelocityResponseCurve = curve_type_linear;
1396                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1397                } else if (releasevelocityresponse < 15) {
1398                    ReleaseVelocityResponseCurve = curve_type_special;
1399                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1400                } else {
1401                    ReleaseVelocityResponseCurve = curve_type_unknown;
1402                    ReleaseVelocityResponseDepth = 0;
1403                }
1404                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1405                AttenuationControllerThreshold = _3ewa->ReadInt8();
1406                _3ewa->ReadInt32(); // unknown
1407                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1408                _3ewa->ReadInt16(); // unknown
1409                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1410                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1411                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1412                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1413                else                                       DimensionBypass = dim_bypass_ctrl_none;
1414                uint8_t pan = _3ewa->ReadUint8();
1415                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1416                SelfMask = _3ewa->ReadInt8() & 0x01;
1417                _3ewa->ReadInt8(); // unknown
1418                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1419                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1420                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1421                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1422                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1423                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1424                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1425                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1426                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1427                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1428                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1429                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1430                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1431                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1432                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1433                                                            : vcf_res_ctrl_none;
1434                uint16_t eg3depth = _3ewa->ReadUint16();
1435                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1436                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1437                _3ewa->ReadInt16(); // unknown
1438                ChannelOffset = _3ewa->ReadUint8() / 4;
1439                uint8_t regoptions = _3ewa->ReadUint8();
1440                MSDecode           = regoptions & 0x01; // bit 0
1441                SustainDefeat      = regoptions & 0x02; // bit 1
1442                _3ewa->ReadInt16(); // unknown
1443                VelocityUpperLimit = _3ewa->ReadInt8();
1444                _3ewa->ReadInt8(); // unknown
1445                _3ewa->ReadInt16(); // unknown
1446                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1447                _3ewa->ReadInt8(); // unknown
1448                _3ewa->ReadInt8(); // unknown
1449                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1450                uint8_t vcfcutoff = _3ewa->ReadUint8();
1451                VCFEnabled = vcfcutoff & 0x80; // bit 7
1452                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1453                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1454                uint8_t vcfvelscale = _3ewa->ReadUint8();
1455                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1456                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1457                _3ewa->ReadInt8(); // unknown
1458                uint8_t vcfresonance = _3ewa->ReadUint8();
1459                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1460                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1461                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1462                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1463                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1464                uint8_t vcfvelocity = _3ewa->ReadUint8();
1465                VCFVelocityDynamicRange = vcfvelocity % 5;
1466                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1467                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1468                if (VCFType == vcf_type_lowpass) {
1469                    if (lfo3ctrl & 0x40) // bit 6
1470                        VCFType = vcf_type_lowpassturbo;
1471                }
1472                if (_3ewa->RemainingBytes() >= 8) {
1473                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1474                } else {
1475                    memset(DimensionUpperLimits, 0, 8);
1476                }
1477            } else { // '3ewa' chunk does not exist yet
1478                // use default values
1479                LFO3Frequency                   = 1.0;
1480                EG3Attack                       = 0.0;
1481                LFO1InternalDepth               = 0;
1482                LFO3InternalDepth               = 0;
1483                LFO1ControlDepth                = 0;
1484                LFO3ControlDepth                = 0;
1485                EG1Attack                       = 0.0;
1486                EG1Decay1                       = 0.005;
1487                EG1Sustain                      = 1000;
1488                EG1Release                      = 0.3;
1489                EG1Controller.type              = eg1_ctrl_t::type_none;
1490                EG1Controller.controller_number = 0;
1491                EG1ControllerInvert             = false;
1492                EG1ControllerAttackInfluence    = 0;
1493                EG1ControllerDecayInfluence     = 0;
1494                EG1ControllerReleaseInfluence   = 0;
1495                EG2Controller.type              = eg2_ctrl_t::type_none;
1496                EG2Controller.controller_number = 0;
1497                EG2ControllerInvert             = false;
1498                EG2ControllerAttackInfluence    = 0;
1499                EG2ControllerDecayInfluence     = 0;
1500                EG2ControllerReleaseInfluence   = 0;
1501                LFO1Frequency                   = 1.0;
1502                EG2Attack                       = 0.0;
1503                EG2Decay1                       = 0.005;
1504                EG2Sustain                      = 1000;
1505                EG2Release                      = 0.3;
1506                LFO2ControlDepth                = 0;
1507                LFO2Frequency                   = 1.0;
1508                LFO2InternalDepth               = 0;
1509                EG1Decay2                       = 0.0;
1510                EG1InfiniteSustain              = true;
1511                EG1PreAttack                    = 0;
1512                EG2Decay2                       = 0.0;
1513                EG2InfiniteSustain              = true;
1514                EG2PreAttack                    = 0;
1515                VelocityResponseCurve           = curve_type_nonlinear;
1516                VelocityResponseDepth           = 3;
1517                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1518                ReleaseVelocityResponseDepth    = 3;
1519                VelocityResponseCurveScaling    = 32;
1520                AttenuationControllerThreshold  = 0;
1521                SampleStartOffset               = 0;
1522                PitchTrack                      = true;
1523                DimensionBypass                 = dim_bypass_ctrl_none;
1524                Pan                             = 0;
1525                SelfMask                        = true;
1526                LFO3Controller                  = lfo3_ctrl_modwheel;
1527                LFO3Sync                        = false;
1528                InvertAttenuationController     = false;
1529                AttenuationController.type      = attenuation_ctrl_t::type_none;
1530                AttenuationController.controller_number = 0;
1531                LFO2Controller                  = lfo2_ctrl_internal;
1532                LFO2FlipPhase                   = false;
1533                LFO2Sync                        = false;
1534                LFO1Controller                  = lfo1_ctrl_internal;
1535                LFO1FlipPhase                   = false;
1536                LFO1Sync                        = false;
1537                VCFResonanceController          = vcf_res_ctrl_none;
1538                EG3Depth                        = 0;
1539                ChannelOffset                   = 0;
1540                MSDecode                        = false;
1541                SustainDefeat                   = false;
1542                VelocityUpperLimit              = 0;
1543                ReleaseTriggerDecay             = 0;
1544                EG1Hold                         = false;
1545                VCFEnabled                      = false;
1546                VCFCutoff                       = 0;
1547                VCFCutoffController             = vcf_cutoff_ctrl_none;
1548                VCFCutoffControllerInvert       = false;
1549                VCFVelocityScale                = 0;
1550                VCFResonance                    = 0;
1551                VCFResonanceDynamic             = false;
1552                VCFKeyboardTracking             = false;
1553                VCFKeyboardTrackingBreakpoint   = 0;
1554                VCFVelocityDynamicRange         = 0x04;
1555                VCFVelocityCurve                = curve_type_linear;
1556                VCFType                         = vcf_type_lowpass;
1557                memset(DimensionUpperLimits, 127, 8);
1558            }
1559    
1560            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1561                                                         VelocityResponseDepth,
1562                                                         VelocityResponseCurveScaling);
1563    
1564            pVelocityReleaseTable = GetReleaseVelocityTable(
1565                                        ReleaseVelocityResponseCurve,
1566                                        ReleaseVelocityResponseDepth
1567                                    );
1568    
1569            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1570                                                          VCFVelocityDynamicRange,
1571                                                          VCFVelocityScale,
1572                                                          VCFCutoffController);
1573    
1574            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1575            VelocityTable = 0;
1576        }
1577    
1578        /*
1579         * Constructs a DimensionRegion by copying all parameters from
1580         * another DimensionRegion
1581         */
1582        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1583            Instances++;
1584            *this = src; // default memberwise shallow copy of all parameters
1585            pParentList = _3ewl; // restore the chunk pointer
1586    
1587            // deep copy of owned structures
1588            if (src.VelocityTable) {
1589                VelocityTable = new uint8_t[128];
1590                for (int k = 0 ; k < 128 ; k++)
1591                    VelocityTable[k] = src.VelocityTable[k];
1592            }
1593            if (src.pSampleLoops) {
1594                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1595                for (int k = 0 ; k < src.SampleLoops ; k++)
1596                    pSampleLoops[k] = src.pSampleLoops[k];
1597          }          }
1598          else {      }
1599              VelocityResponseCurve = curve_type_unknown;  
1600              VelocityResponseDepth = 0;      /**
1601         * Updates the respective member variable and updates @c SampleAttenuation
1602         * which depends on this value.
1603         */
1604        void DimensionRegion::SetGain(int32_t gain) {
1605            DLS::Sampler::SetGain(gain);
1606            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1607        }
1608    
1609        /**
1610         * Apply dimension region settings to the respective RIFF chunks. You
1611         * have to call File::Save() to make changes persistent.
1612         *
1613         * Usually there is absolutely no need to call this method explicitly.
1614         * It will be called automatically when File::Save() was called.
1615         */
1616        void DimensionRegion::UpdateChunks() {
1617            // first update base class's chunk
1618            DLS::Sampler::UpdateChunks();
1619    
1620            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1621            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1622            pData[12] = Crossfade.in_start;
1623            pData[13] = Crossfade.in_end;
1624            pData[14] = Crossfade.out_start;
1625            pData[15] = Crossfade.out_end;
1626    
1627            // make sure '3ewa' chunk exists
1628            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1629            if (!_3ewa) {
1630                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1631                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1632                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1633          }          }
1634          uint8_t releasevelocityresponse = _3ewa->ReadUint8();          pData = (uint8_t*) _3ewa->LoadChunkData();
1635          if (releasevelocityresponse < 5) {  
1636              ReleaseVelocityResponseCurve = curve_type_nonlinear;          // update '3ewa' chunk with DimensionRegion's current settings
1637              ReleaseVelocityResponseDepth = releasevelocityresponse;  
1638          }          const uint32_t chunksize = _3ewa->GetNewSize();
1639          else if (releasevelocityresponse < 10) {          store32(&pData[0], chunksize); // unknown, always chunk size?
1640              ReleaseVelocityResponseCurve = curve_type_linear;  
1641              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1642          }          store32(&pData[4], lfo3freq);
1643          else if (releasevelocityresponse < 15) {  
1644              ReleaseVelocityResponseCurve = curve_type_special;          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1645              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;          store32(&pData[8], eg3attack);
1646    
1647            // next 2 bytes unknown
1648    
1649            store16(&pData[14], LFO1InternalDepth);
1650    
1651            // next 2 bytes unknown
1652    
1653            store16(&pData[18], LFO3InternalDepth);
1654    
1655            // next 2 bytes unknown
1656    
1657            store16(&pData[22], LFO1ControlDepth);
1658    
1659            // next 2 bytes unknown
1660    
1661            store16(&pData[26], LFO3ControlDepth);
1662    
1663            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1664            store32(&pData[28], eg1attack);
1665    
1666            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1667            store32(&pData[32], eg1decay1);
1668    
1669            // next 2 bytes unknown
1670    
1671            store16(&pData[38], EG1Sustain);
1672    
1673            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1674            store32(&pData[40], eg1release);
1675    
1676            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1677            pData[44] = eg1ctl;
1678    
1679            const uint8_t eg1ctrloptions =
1680                (EG1ControllerInvert ? 0x01 : 0x00) |
1681                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1682                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1683                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1684            pData[45] = eg1ctrloptions;
1685    
1686            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1687            pData[46] = eg2ctl;
1688    
1689            const uint8_t eg2ctrloptions =
1690                (EG2ControllerInvert ? 0x01 : 0x00) |
1691                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1692                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1693                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1694            pData[47] = eg2ctrloptions;
1695    
1696            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1697            store32(&pData[48], lfo1freq);
1698    
1699            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1700            store32(&pData[52], eg2attack);
1701    
1702            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1703            store32(&pData[56], eg2decay1);
1704    
1705            // next 2 bytes unknown
1706    
1707            store16(&pData[62], EG2Sustain);
1708    
1709            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1710            store32(&pData[64], eg2release);
1711    
1712            // next 2 bytes unknown
1713    
1714            store16(&pData[70], LFO2ControlDepth);
1715    
1716            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1717            store32(&pData[72], lfo2freq);
1718    
1719            // next 2 bytes unknown
1720    
1721            store16(&pData[78], LFO2InternalDepth);
1722    
1723            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1724            store32(&pData[80], eg1decay2);
1725    
1726            // next 2 bytes unknown
1727    
1728            store16(&pData[86], EG1PreAttack);
1729    
1730            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1731            store32(&pData[88], eg2decay2);
1732    
1733            // next 2 bytes unknown
1734    
1735            store16(&pData[94], EG2PreAttack);
1736    
1737            {
1738                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1739                uint8_t velocityresponse = VelocityResponseDepth;
1740                switch (VelocityResponseCurve) {
1741                    case curve_type_nonlinear:
1742                        break;
1743                    case curve_type_linear:
1744                        velocityresponse += 5;
1745                        break;
1746                    case curve_type_special:
1747                        velocityresponse += 10;
1748                        break;
1749                    case curve_type_unknown:
1750                    default:
1751                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1752                }
1753                pData[96] = velocityresponse;
1754            }
1755    
1756            {
1757                if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1758                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1759                switch (ReleaseVelocityResponseCurve) {
1760                    case curve_type_nonlinear:
1761                        break;
1762                    case curve_type_linear:
1763                        releasevelocityresponse += 5;
1764                        break;
1765                    case curve_type_special:
1766                        releasevelocityresponse += 10;
1767                        break;
1768                    case curve_type_unknown:
1769                    default:
1770                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1771                }
1772                pData[97] = releasevelocityresponse;
1773            }
1774    
1775            pData[98] = VelocityResponseCurveScaling;
1776    
1777            pData[99] = AttenuationControllerThreshold;
1778    
1779            // next 4 bytes unknown
1780    
1781            store16(&pData[104], SampleStartOffset);
1782    
1783            // next 2 bytes unknown
1784    
1785            {
1786                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1787                switch (DimensionBypass) {
1788                    case dim_bypass_ctrl_94:
1789                        pitchTrackDimensionBypass |= 0x10;
1790                        break;
1791                    case dim_bypass_ctrl_95:
1792                        pitchTrackDimensionBypass |= 0x20;
1793                        break;
1794                    case dim_bypass_ctrl_none:
1795                        //FIXME: should we set anything here?
1796                        break;
1797                    default:
1798                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1799                }
1800                pData[108] = pitchTrackDimensionBypass;
1801            }
1802    
1803            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1804            pData[109] = pan;
1805    
1806            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1807            pData[110] = selfmask;
1808    
1809            // next byte unknown
1810    
1811            {
1812                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1813                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1814                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1815                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1816                pData[112] = lfo3ctrl;
1817            }
1818    
1819            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1820            pData[113] = attenctl;
1821    
1822            {
1823                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1824                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1825                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1826                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1827                pData[114] = lfo2ctrl;
1828            }
1829    
1830            {
1831                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1832                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1833                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1834                if (VCFResonanceController != vcf_res_ctrl_none)
1835                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1836                pData[115] = lfo1ctrl;
1837            }
1838    
1839            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1840                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1841            store16(&pData[116], eg3depth);
1842    
1843            // next 2 bytes unknown
1844    
1845            const uint8_t channeloffset = ChannelOffset * 4;
1846            pData[120] = channeloffset;
1847    
1848            {
1849                uint8_t regoptions = 0;
1850                if (MSDecode)      regoptions |= 0x01; // bit 0
1851                if (SustainDefeat) regoptions |= 0x02; // bit 1
1852                pData[121] = regoptions;
1853            }
1854    
1855            // next 2 bytes unknown
1856    
1857            pData[124] = VelocityUpperLimit;
1858    
1859            // next 3 bytes unknown
1860    
1861            pData[128] = ReleaseTriggerDecay;
1862    
1863            // next 2 bytes unknown
1864    
1865            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1866            pData[131] = eg1hold;
1867    
1868            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1869                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
1870            pData[132] = vcfcutoff;
1871    
1872            pData[133] = VCFCutoffController;
1873    
1874            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1875                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
1876            pData[134] = vcfvelscale;
1877    
1878            // next byte unknown
1879    
1880            const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1881                                         (VCFResonance & 0x7f); /* lower 7 bits */
1882            pData[136] = vcfresonance;
1883    
1884            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1885                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1886            pData[137] = vcfbreakpoint;
1887    
1888            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1889                                        VCFVelocityCurve * 5;
1890            pData[138] = vcfvelocity;
1891    
1892            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1893            pData[139] = vcftype;
1894    
1895            if (chunksize >= 148) {
1896                memcpy(&pData[140], DimensionUpperLimits, 8);
1897            }
1898        }
1899    
1900        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
1901            curve_type_t curveType = releaseVelocityResponseCurve;
1902            uint8_t depth = releaseVelocityResponseDepth;
1903            // this models a strange behaviour or bug in GSt: two of the
1904            // velocity response curves for release time are not used even
1905            // if specified, instead another curve is chosen.
1906            if ((curveType == curve_type_nonlinear && depth == 0) ||
1907                (curveType == curve_type_special   && depth == 4)) {
1908                curveType = curve_type_nonlinear;
1909                depth = 3;
1910            }
1911            return GetVelocityTable(curveType, depth, 0);
1912        }
1913    
1914        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
1915                                                        uint8_t vcfVelocityDynamicRange,
1916                                                        uint8_t vcfVelocityScale,
1917                                                        vcf_cutoff_ctrl_t vcfCutoffController)
1918        {
1919            curve_type_t curveType = vcfVelocityCurve;
1920            uint8_t depth = vcfVelocityDynamicRange;
1921            // even stranger GSt: two of the velocity response curves for
1922            // filter cutoff are not used, instead another special curve
1923            // is chosen. This curve is not used anywhere else.
1924            if ((curveType == curve_type_nonlinear && depth == 0) ||
1925                (curveType == curve_type_special   && depth == 4)) {
1926                curveType = curve_type_special;
1927                depth = 5;
1928            }
1929            return GetVelocityTable(curveType, depth,
1930                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
1931                                        ? vcfVelocityScale : 0);
1932        }
1933    
1934        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1935        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1936        {
1937            double* table;
1938            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1939            if (pVelocityTables->count(tableKey)) { // if key exists
1940                table = (*pVelocityTables)[tableKey];
1941          }          }
1942          else {          else {
1943              ReleaseVelocityResponseCurve = curve_type_unknown;              table = CreateVelocityTable(curveType, depth, scaling);
1944              ReleaseVelocityResponseDepth = 0;              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
1945            }
1946            return table;
1947        }
1948    
1949        Region* DimensionRegion::GetParent() const {
1950            return pRegion;
1951        }
1952    
1953        leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1954            leverage_ctrl_t decodedcontroller;
1955            switch (EncodedController) {
1956                // special controller
1957                case _lev_ctrl_none:
1958                    decodedcontroller.type = leverage_ctrl_t::type_none;
1959                    decodedcontroller.controller_number = 0;
1960                    break;
1961                case _lev_ctrl_velocity:
1962                    decodedcontroller.type = leverage_ctrl_t::type_velocity;
1963                    decodedcontroller.controller_number = 0;
1964                    break;
1965                case _lev_ctrl_channelaftertouch:
1966                    decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1967                    decodedcontroller.controller_number = 0;
1968                    break;
1969    
1970                // ordinary MIDI control change controller
1971                case _lev_ctrl_modwheel:
1972                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1973                    decodedcontroller.controller_number = 1;
1974                    break;
1975                case _lev_ctrl_breath:
1976                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1977                    decodedcontroller.controller_number = 2;
1978                    break;
1979                case _lev_ctrl_foot:
1980                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1981                    decodedcontroller.controller_number = 4;
1982                    break;
1983                case _lev_ctrl_effect1:
1984                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1985                    decodedcontroller.controller_number = 12;
1986                    break;
1987                case _lev_ctrl_effect2:
1988                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1989                    decodedcontroller.controller_number = 13;
1990                    break;
1991                case _lev_ctrl_genpurpose1:
1992                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1993                    decodedcontroller.controller_number = 16;
1994                    break;
1995                case _lev_ctrl_genpurpose2:
1996                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1997                    decodedcontroller.controller_number = 17;
1998                    break;
1999                case _lev_ctrl_genpurpose3:
2000                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2001                    decodedcontroller.controller_number = 18;
2002                    break;
2003                case _lev_ctrl_genpurpose4:
2004                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2005                    decodedcontroller.controller_number = 19;
2006                    break;
2007                case _lev_ctrl_portamentotime:
2008                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2009                    decodedcontroller.controller_number = 5;
2010                    break;
2011                case _lev_ctrl_sustainpedal:
2012                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2013                    decodedcontroller.controller_number = 64;
2014                    break;
2015                case _lev_ctrl_portamento:
2016                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2017                    decodedcontroller.controller_number = 65;
2018                    break;
2019                case _lev_ctrl_sostenutopedal:
2020                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2021                    decodedcontroller.controller_number = 66;
2022                    break;
2023                case _lev_ctrl_softpedal:
2024                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2025                    decodedcontroller.controller_number = 67;
2026                    break;
2027                case _lev_ctrl_genpurpose5:
2028                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2029                    decodedcontroller.controller_number = 80;
2030                    break;
2031                case _lev_ctrl_genpurpose6:
2032                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2033                    decodedcontroller.controller_number = 81;
2034                    break;
2035                case _lev_ctrl_genpurpose7:
2036                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2037                    decodedcontroller.controller_number = 82;
2038                    break;
2039                case _lev_ctrl_genpurpose8:
2040                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2041                    decodedcontroller.controller_number = 83;
2042                    break;
2043                case _lev_ctrl_effect1depth:
2044                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2045                    decodedcontroller.controller_number = 91;
2046                    break;
2047                case _lev_ctrl_effect2depth:
2048                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2049                    decodedcontroller.controller_number = 92;
2050                    break;
2051                case _lev_ctrl_effect3depth:
2052                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2053                    decodedcontroller.controller_number = 93;
2054                    break;
2055                case _lev_ctrl_effect4depth:
2056                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2057                    decodedcontroller.controller_number = 94;
2058                    break;
2059                case _lev_ctrl_effect5depth:
2060                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2061                    decodedcontroller.controller_number = 95;
2062                    break;
2063    
2064                // unknown controller type
2065                default:
2066                    throw gig::Exception("Unknown leverage controller type.");
2067            }
2068            return decodedcontroller;
2069        }
2070    
2071        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2072            _lev_ctrl_t encodedcontroller;
2073            switch (DecodedController.type) {
2074                // special controller
2075                case leverage_ctrl_t::type_none:
2076                    encodedcontroller = _lev_ctrl_none;
2077                    break;
2078                case leverage_ctrl_t::type_velocity:
2079                    encodedcontroller = _lev_ctrl_velocity;
2080                    break;
2081                case leverage_ctrl_t::type_channelaftertouch:
2082                    encodedcontroller = _lev_ctrl_channelaftertouch;
2083                    break;
2084    
2085                // ordinary MIDI control change controller
2086                case leverage_ctrl_t::type_controlchange:
2087                    switch (DecodedController.controller_number) {
2088                        case 1:
2089                            encodedcontroller = _lev_ctrl_modwheel;
2090                            break;
2091                        case 2:
2092                            encodedcontroller = _lev_ctrl_breath;
2093                            break;
2094                        case 4:
2095                            encodedcontroller = _lev_ctrl_foot;
2096                            break;
2097                        case 12:
2098                            encodedcontroller = _lev_ctrl_effect1;
2099                            break;
2100                        case 13:
2101                            encodedcontroller = _lev_ctrl_effect2;
2102                            break;
2103                        case 16:
2104                            encodedcontroller = _lev_ctrl_genpurpose1;
2105                            break;
2106                        case 17:
2107                            encodedcontroller = _lev_ctrl_genpurpose2;
2108                            break;
2109                        case 18:
2110                            encodedcontroller = _lev_ctrl_genpurpose3;
2111                            break;
2112                        case 19:
2113                            encodedcontroller = _lev_ctrl_genpurpose4;
2114                            break;
2115                        case 5:
2116                            encodedcontroller = _lev_ctrl_portamentotime;
2117                            break;
2118                        case 64:
2119                            encodedcontroller = _lev_ctrl_sustainpedal;
2120                            break;
2121                        case 65:
2122                            encodedcontroller = _lev_ctrl_portamento;
2123                            break;
2124                        case 66:
2125                            encodedcontroller = _lev_ctrl_sostenutopedal;
2126                            break;
2127                        case 67:
2128                            encodedcontroller = _lev_ctrl_softpedal;
2129                            break;
2130                        case 80:
2131                            encodedcontroller = _lev_ctrl_genpurpose5;
2132                            break;
2133                        case 81:
2134                            encodedcontroller = _lev_ctrl_genpurpose6;
2135                            break;
2136                        case 82:
2137                            encodedcontroller = _lev_ctrl_genpurpose7;
2138                            break;
2139                        case 83:
2140                            encodedcontroller = _lev_ctrl_genpurpose8;
2141                            break;
2142                        case 91:
2143                            encodedcontroller = _lev_ctrl_effect1depth;
2144                            break;
2145                        case 92:
2146                            encodedcontroller = _lev_ctrl_effect2depth;
2147                            break;
2148                        case 93:
2149                            encodedcontroller = _lev_ctrl_effect3depth;
2150                            break;
2151                        case 94:
2152                            encodedcontroller = _lev_ctrl_effect4depth;
2153                            break;
2154                        case 95:
2155                            encodedcontroller = _lev_ctrl_effect5depth;
2156                            break;
2157                        default:
2158                            throw gig::Exception("leverage controller number is not supported by the gig format");
2159                    }
2160                    break;
2161                default:
2162                    throw gig::Exception("Unknown leverage controller type.");
2163            }
2164            return encodedcontroller;
2165        }
2166    
2167        DimensionRegion::~DimensionRegion() {
2168            Instances--;
2169            if (!Instances) {
2170                // delete the velocity->volume tables
2171                VelocityTableMap::iterator iter;
2172                for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2173                    double* pTable = iter->second;
2174                    if (pTable) delete[] pTable;
2175                }
2176                pVelocityTables->clear();
2177                delete pVelocityTables;
2178                pVelocityTables = NULL;
2179          }          }
2180          VelocityResponseCurveScaling = _3ewa->ReadUint8();          if (VelocityTable) delete[] VelocityTable;
2181          AttenuationControlTreshold   = _3ewa->ReadInt8();      }
2182          _3ewa->ReadInt32(); // unknown  
2183          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();      /**
2184          _3ewa->ReadInt16(); // unknown       * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
2185          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();       * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
2186          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);       * and VelocityResponseCurveScaling) involved are taken into account to
2187          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;       * calculate the amplitude factor. Use this method when a key was
2188          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;       * triggered to get the volume with which the sample should be played
2189          else                                       DimensionBypass = dim_bypass_ctrl_none;       * back.
2190          uint8_t pan = _3ewa->ReadUint8();       *
2191          Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;       * @param MIDIKeyVelocity  MIDI velocity value of the triggered key (between 0 and 127)
2192          SelfMask = _3ewa->ReadInt8() & 0x01;       * @returns                amplitude factor (between 0.0 and 1.0)
2193          _3ewa->ReadInt8(); // unknown       */
2194          uint8_t lfo3ctrl = _3ewa->ReadUint8();      double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2195          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          return pVelocityAttenuationTable[MIDIKeyVelocity];
2196          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5      }
2197          InvertAttenuationControl = lfo3ctrl & 0x80; // bit 7  
2198          if (VCFType == vcf_type_lowpass) {      double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2199              if (lfo3ctrl & 0x40) // bit 6          return pVelocityReleaseTable[MIDIKeyVelocity];
2200                  VCFType = vcf_type_lowpassturbo;      }
2201          }  
2202          AttenuationControl = static_cast<attenuation_ctrl_t>(_3ewa->ReadUint8());      double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2203          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          return pVelocityCutoffTable[MIDIKeyVelocity];
2204          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits      }
2205          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
2206          LFO2Sync               = lfo2ctrl & 0x20; // bit 5      /**
2207          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6       * Updates the respective member variable and the lookup table / cache
2208          uint8_t lfo1ctrl       = _3ewa->ReadUint8();       * that depends on this value.
2209          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits       */
2210          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7      void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2211          LFO1Sync               = lfo1ctrl & 0x40; // bit 6          pVelocityAttenuationTable =
2212          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))              GetVelocityTable(
2213                                                      : vcf_res_ctrl_none;                  curve, VelocityResponseDepth, VelocityResponseCurveScaling
2214          uint16_t eg3depth = _3ewa->ReadUint16();              );
2215          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */          VelocityResponseCurve = curve;
2216                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */      }
2217          _3ewa->ReadInt16(); // unknown  
2218          ChannelOffset = _3ewa->ReadUint8() / 4;      /**
2219          uint8_t regoptions = _3ewa->ReadUint8();       * Updates the respective member variable and the lookup table / cache
2220          MSDecode           = regoptions & 0x01; // bit 0       * that depends on this value.
2221          SustainDefeat      = regoptions & 0x02; // bit 1       */
2222          _3ewa->ReadInt16(); // unknown      void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2223          VelocityUpperLimit = _3ewa->ReadInt8();          pVelocityAttenuationTable =
2224          _3ewa->ReadInt8(); // unknown              GetVelocityTable(
2225          _3ewa->ReadInt16(); // unknown                  VelocityResponseCurve, depth, VelocityResponseCurveScaling
2226          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay              );
2227          _3ewa->ReadInt8(); // unknown          VelocityResponseDepth = depth;
2228          _3ewa->ReadInt8(); // unknown      }
2229          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
2230          uint8_t vcfcutoff = _3ewa->ReadUint8();      /**
2231          VCFEnabled = vcfcutoff & 0x80; // bit 7       * Updates the respective member variable and the lookup table / cache
2232          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits       * that depends on this value.
2233          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());       */
2234          VCFVelocityScale = _3ewa->ReadUint8();      void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2235          _3ewa->ReadInt8(); // unknown          pVelocityAttenuationTable =
2236          uint8_t vcfresonance = _3ewa->ReadUint8();              GetVelocityTable(
2237          VCFResonance = vcfresonance & 0x7f; // lower 7 bits                  VelocityResponseCurve, VelocityResponseDepth, scaling
2238          VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7              );
2239          uint8_t vcfbreakpoint         = _3ewa->ReadUint8();          VelocityResponseCurveScaling = scaling;
2240          VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7      }
2241          VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
2242          uint8_t vcfvelocity = _3ewa->ReadUint8();      /**
2243          VCFVelocityDynamicRange = vcfvelocity % 5;       * Updates the respective member variable and the lookup table / cache
2244          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);       * that depends on this value.
2245          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());       */
2246        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2247            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2248            ReleaseVelocityResponseCurve = curve;
2249        }
2250    
2251        /**
2252         * Updates the respective member variable and the lookup table / cache
2253         * that depends on this value.
2254         */
2255        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2256            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2257            ReleaseVelocityResponseDepth = depth;
2258        }
2259    
2260        /**
2261         * Updates the respective member variable and the lookup table / cache
2262         * that depends on this value.
2263         */
2264        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2265            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2266            VCFCutoffController = controller;
2267        }
2268    
2269        /**
2270         * Updates the respective member variable and the lookup table / cache
2271         * that depends on this value.
2272         */
2273        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2274            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2275            VCFVelocityCurve = curve;
2276        }
2277    
2278        /**
2279         * Updates the respective member variable and the lookup table / cache
2280         * that depends on this value.
2281         */
2282        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2283            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2284            VCFVelocityDynamicRange = range;
2285      }      }
2286    
2287        /**
2288         * Updates the respective member variable and the lookup table / cache
2289         * that depends on this value.
2290         */
2291        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2292            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2293            VCFVelocityScale = scaling;
2294        }
2295    
2296        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2297    
2298            // line-segment approximations of the 15 velocity curves
2299    
2300            // linear
2301            const int lin0[] = { 1, 1, 127, 127 };
2302            const int lin1[] = { 1, 21, 127, 127 };
2303            const int lin2[] = { 1, 45, 127, 127 };
2304            const int lin3[] = { 1, 74, 127, 127 };
2305            const int lin4[] = { 1, 127, 127, 127 };
2306    
2307            // non-linear
2308            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2309            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2310                                 127, 127 };
2311            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2312                                 127, 127 };
2313            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2314                                 127, 127 };
2315            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2316    
2317            // special
2318            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2319                                 113, 127, 127, 127 };
2320            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2321                                 118, 127, 127, 127 };
2322            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2323                                 85, 90, 91, 127, 127, 127 };
2324            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2325                                 117, 127, 127, 127 };
2326            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2327                                 127, 127 };
2328    
2329            // this is only used by the VCF velocity curve
2330            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2331                                 91, 127, 127, 127 };
2332    
2333            const int* const curves[] = { non0, non1, non2, non3, non4,
2334                                          lin0, lin1, lin2, lin3, lin4,
2335                                          spe0, spe1, spe2, spe3, spe4, spe5 };
2336    
2337            double* const table = new double[128];
2338    
2339            const int* curve = curves[curveType * 5 + depth];
2340            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2341    
2342            table[0] = 0;
2343            for (int x = 1 ; x < 128 ; x++) {
2344    
2345                if (x > curve[2]) curve += 2;
2346                double y = curve[1] + (x - curve[0]) *
2347                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2348                y = y / 127;
2349    
2350                // Scale up for s > 20, down for s < 20. When
2351                // down-scaling, the curve still ends at 1.0.
2352                if (s < 20 && y >= 0.5)
2353                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2354                else
2355                    y = y * (s / 20.0);
2356                if (y > 1) y = 1;
2357    
2358                table[x] = y;
2359            }
2360            return table;
2361        }
2362    
2363    
2364  // *************** Region ***************  // *************** Region ***************
# Line 654  namespace gig { Line 2367  namespace gig {
2367      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) {
2368          // Initialization          // Initialization
2369          Dimensions = 0;          Dimensions = 0;
2370          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
2371              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
2372          }          }
2373            Layers = 1;
2374            File* file = (File*) GetParent()->GetParent();
2375            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2376    
2377          // Actual Loading          // Actual Loading
2378    
2379            if (!file->GetAutoLoad()) return;
2380    
2381          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2382    
2383          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2384          if (_3lnk) {          if (_3lnk) {
2385              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
2386              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
2387                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2388                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2389                    _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2390                    _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2391                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2392                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2393                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2394                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2395                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2396                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2397                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2398                  }                  }
2399                  else { // active dimension                  else { // active dimension
2400                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2401                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2402                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2403                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2404                                                             dimension == dimension_samplechannel) ? split_type_bit                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                                                                  : 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;  
2405                      Dimensions++;                      Dimensions++;
2406    
2407                        // if this is a layer dimension, remember the amount of layers
2408                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2409                  }                  }
2410                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2411              }              }
2412                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2413    
2414              // 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,
2415              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2416                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
2417                  if (pDimDef->dimension == dimension_velocity) {  
2418                      if (pDimensionRegions[0]->VelocityUpperLimit == 0) {              // jump to start of the wave pool indices (if not already there)
2419                          // no custom defined ranges              if (file->pVersion && file->pVersion->major == 3)
2420                          pDimDef->split_type = split_type_normal;                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2421                          pDimDef->ranges     = NULL;              else
2422                      }                  _3lnk->SetPos(44);
2423                      else { // custom defined ranges  
2424                          pDimDef->split_type = split_type_customvelocity;              // load sample references (if auto loading is enabled)
2425                          pDimDef->ranges     = new range_t[pDimDef->zones];              if (file->GetAutoLoad()) {
2426                          unsigned int bits[5] = {0,0,0,0,0};                  for (uint i = 0; i < DimensionRegions; i++) {
2427                          int previousUpperLimit = -1;                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2428                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {                      if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
                             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;  
                             }  
                         }  
                     }  
2429                  }                  }
2430                    GetSample(); // load global region sample reference
2431                }
2432            } else {
2433                DimensionRegions = 0;
2434                for (int i = 0 ; i < 8 ; i++) {
2435                    pDimensionDefinitions[i].dimension  = dimension_none;
2436                    pDimensionDefinitions[i].bits       = 0;
2437                    pDimensionDefinitions[i].zones      = 0;
2438              }              }
2439            }
2440    
2441              // load sample references          // make sure there is at least one dimension region
2442              _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)          if (!DimensionRegions) {
2443              for (uint i = 0; i < DimensionRegions; i++) {              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2444                  uint32_t wavepoolindex = _3lnk->ReadUint32();              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2445                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2446                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2447                DimensionRegions = 1;
2448            }
2449        }
2450    
2451        /**
2452         * Apply Region settings and all its DimensionRegions to the respective
2453         * RIFF chunks. You have to call File::Save() to make changes persistent.
2454         *
2455         * Usually there is absolutely no need to call this method explicitly.
2456         * It will be called automatically when File::Save() was called.
2457         *
2458         * @throws gig::Exception if samples cannot be dereferenced
2459         */
2460        void Region::UpdateChunks() {
2461            // in the gig format we don't care about the Region's sample reference
2462            // but we still have to provide some existing one to not corrupt the
2463            // file, so to avoid the latter we simply always assign the sample of
2464            // the first dimension region of this region
2465            pSample = pDimensionRegions[0]->pSample;
2466    
2467            // first update base class's chunks
2468            DLS::Region::UpdateChunks();
2469    
2470            // update dimension region's chunks
2471            for (int i = 0; i < DimensionRegions; i++) {
2472                pDimensionRegions[i]->UpdateChunks();
2473            }
2474    
2475            File* pFile = (File*) GetParent()->GetParent();
2476            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2477            const int iMaxDimensions =  version3 ? 8 : 5;
2478            const int iMaxDimensionRegions = version3 ? 256 : 32;
2479    
2480            // make sure '3lnk' chunk exists
2481            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2482            if (!_3lnk) {
2483                const int _3lnkChunkSize = version3 ? 1092 : 172;
2484                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2485                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2486    
2487                // move 3prg to last position
2488                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2489            }
2490    
2491            // update dimension definitions in '3lnk' chunk
2492            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2493            store32(&pData[0], DimensionRegions);
2494            int shift = 0;
2495            for (int i = 0; i < iMaxDimensions; i++) {
2496                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2497                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2498                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2499                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2500                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2501                // next 3 bytes unknown, always zero?
2502    
2503                shift += pDimensionDefinitions[i].bits;
2504            }
2505    
2506            // update wave pool table in '3lnk' chunk
2507            const int iWavePoolOffset = version3 ? 68 : 44;
2508            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2509                int iWaveIndex = -1;
2510                if (i < DimensionRegions) {
2511                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2512                    File::SampleList::iterator iter = pFile->pSamples->begin();
2513                    File::SampleList::iterator end  = pFile->pSamples->end();
2514                    for (int index = 0; iter != end; ++iter, ++index) {
2515                        if (*iter == pDimensionRegions[i]->pSample) {
2516                            iWaveIndex = index;
2517                            break;
2518                        }
2519                    }
2520              }              }
2521                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2522          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2523      }      }
2524    
2525      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 739  namespace gig { Line 2529  namespace gig {
2529              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2530              while (_3ewl) {              while (_3ewl) {
2531                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2532                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2533                      dimensionRegionNr++;                      dimensionRegionNr++;
2534                  }                  }
2535                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 748  namespace gig { Line 2538  namespace gig {
2538          }          }
2539      }      }
2540    
2541      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2542          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
2543              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
2544            // update Region key table for fast lookup
2545            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2546        }
2547    
2548        void Region::UpdateVelocityTable() {
2549            // get velocity dimension's index
2550            int veldim = -1;
2551            for (int i = 0 ; i < Dimensions ; i++) {
2552                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2553                    veldim = i;
2554                    break;
2555                }
2556          }          }
2557          for (int i = 0; i < 32; i++) {          if (veldim == -1) return;
2558    
2559            int step = 1;
2560            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2561            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2562            int end = step * pDimensionDefinitions[veldim].zones;
2563    
2564            // loop through all dimension regions for all dimensions except the velocity dimension
2565            int dim[8] = { 0 };
2566            for (int i = 0 ; i < DimensionRegions ; i++) {
2567    
2568                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2569                    pDimensionRegions[i]->VelocityUpperLimit) {
2570                    // create the velocity table
2571                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2572                    if (!table) {
2573                        table = new uint8_t[128];
2574                        pDimensionRegions[i]->VelocityTable = table;
2575                    }
2576                    int tableidx = 0;
2577                    int velocityZone = 0;
2578                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2579                        for (int k = i ; k < end ; k += step) {
2580                            DimensionRegion *d = pDimensionRegions[k];
2581                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2582                            velocityZone++;
2583                        }
2584                    } else { // gig2
2585                        for (int k = i ; k < end ; k += step) {
2586                            DimensionRegion *d = pDimensionRegions[k];
2587                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2588                            velocityZone++;
2589                        }
2590                    }
2591                } else {
2592                    if (pDimensionRegions[i]->VelocityTable) {
2593                        delete[] pDimensionRegions[i]->VelocityTable;
2594                        pDimensionRegions[i]->VelocityTable = 0;
2595                    }
2596                }
2597    
2598                int j;
2599                int shift = 0;
2600                for (j = 0 ; j < Dimensions ; j++) {
2601                    if (j == veldim) i += skipveldim; // skip velocity dimension
2602                    else {
2603                        dim[j]++;
2604                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2605                        else {
2606                            // skip unused dimension regions
2607                            dim[j] = 0;
2608                            i += ((1 << pDimensionDefinitions[j].bits) -
2609                                  pDimensionDefinitions[j].zones) << shift;
2610                        }
2611                    }
2612                    shift += pDimensionDefinitions[j].bits;
2613                }
2614                if (j == Dimensions) break;
2615            }
2616        }
2617    
2618        /** @brief Einstein would have dreamed of it - create a new dimension.
2619         *
2620         * Creates a new dimension with the dimension definition given by
2621         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2622         * There is a hard limit of dimensions and total amount of "bits" all
2623         * dimensions can have. This limit is dependant to what gig file format
2624         * version this file refers to. The gig v2 (and lower) format has a
2625         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2626         * format has a limit of 8.
2627         *
2628         * @param pDimDef - defintion of the new dimension
2629         * @throws gig::Exception if dimension of the same type exists already
2630         * @throws gig::Exception if amount of dimensions or total amount of
2631         *                        dimension bits limit is violated
2632         */
2633        void Region::AddDimension(dimension_def_t* pDimDef) {
2634            // check if max. amount of dimensions reached
2635            File* file = (File*) GetParent()->GetParent();
2636            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2637            if (Dimensions >= iMaxDimensions)
2638                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2639            // check if max. amount of dimension bits reached
2640            int iCurrentBits = 0;
2641            for (int i = 0; i < Dimensions; i++)
2642                iCurrentBits += pDimensionDefinitions[i].bits;
2643            if (iCurrentBits >= iMaxDimensions)
2644                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2645            const int iNewBits = iCurrentBits + pDimDef->bits;
2646            if (iNewBits > iMaxDimensions)
2647                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2648            // check if there's already a dimensions of the same type
2649            for (int i = 0; i < Dimensions; i++)
2650                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2651                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2652    
2653            // pos is where the new dimension should be placed, normally
2654            // last in list, except for the samplechannel dimension which
2655            // has to be first in list
2656            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2657            int bitpos = 0;
2658            for (int i = 0 ; i < pos ; i++)
2659                bitpos += pDimensionDefinitions[i].bits;
2660    
2661            // make room for the new dimension
2662            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2663            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2664                for (int j = Dimensions ; j > pos ; j--) {
2665                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2666                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2667                }
2668            }
2669    
2670            // assign definition of new dimension
2671            pDimensionDefinitions[pos] = *pDimDef;
2672    
2673            // auto correct certain dimension definition fields (where possible)
2674            pDimensionDefinitions[pos].split_type  =
2675                __resolveSplitType(pDimensionDefinitions[pos].dimension);
2676            pDimensionDefinitions[pos].zone_size =
2677                __resolveZoneSize(pDimensionDefinitions[pos]);
2678    
2679            // create new dimension region(s) for this new dimension, and make
2680            // sure that the dimension regions are placed correctly in both the
2681            // RIFF list and the pDimensionRegions array
2682            RIFF::Chunk* moveTo = NULL;
2683            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2684            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2685                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2686                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2687                }
2688                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2689                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2690                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2691                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2692                        // create a new dimension region and copy all parameter values from
2693                        // an existing dimension region
2694                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2695                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2696    
2697                        DimensionRegions++;
2698                    }
2699                }
2700                moveTo = pDimensionRegions[i]->pParentList;
2701            }
2702    
2703            // initialize the upper limits for this dimension
2704            int mask = (1 << bitpos) - 1;
2705            for (int z = 0 ; z < pDimDef->zones ; z++) {
2706                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2707                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2708                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2709                                      (z << bitpos) |
2710                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2711                }
2712            }
2713    
2714            Dimensions++;
2715    
2716            // if this is a layer dimension, update 'Layers' attribute
2717            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2718    
2719            UpdateVelocityTable();
2720        }
2721    
2722        /** @brief Delete an existing dimension.
2723         *
2724         * Deletes the dimension given by \a pDimDef and deletes all respective
2725         * dimension regions, that is all dimension regions where the dimension's
2726         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2727         * for example this would delete all dimension regions for the case(s)
2728         * where the sustain pedal is pressed down.
2729         *
2730         * @param pDimDef - dimension to delete
2731         * @throws gig::Exception if given dimension cannot be found
2732         */
2733        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2734            // get dimension's index
2735            int iDimensionNr = -1;
2736            for (int i = 0; i < Dimensions; i++) {
2737                if (&pDimensionDefinitions[i] == pDimDef) {
2738                    iDimensionNr = i;
2739                    break;
2740                }
2741            }
2742            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2743    
2744            // get amount of bits below the dimension to delete
2745            int iLowerBits = 0;
2746            for (int i = 0; i < iDimensionNr; i++)
2747                iLowerBits += pDimensionDefinitions[i].bits;
2748    
2749            // get amount ot bits above the dimension to delete
2750            int iUpperBits = 0;
2751            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2752                iUpperBits += pDimensionDefinitions[i].bits;
2753    
2754            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2755    
2756            // delete dimension regions which belong to the given dimension
2757            // (that is where the dimension's bit > 0)
2758            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2759                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2760                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2761                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2762                                        iObsoleteBit << iLowerBits |
2763                                        iLowerBit;
2764    
2765                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2766                        delete pDimensionRegions[iToDelete];
2767                        pDimensionRegions[iToDelete] = NULL;
2768                        DimensionRegions--;
2769                    }
2770                }
2771            }
2772    
2773            // defrag pDimensionRegions array
2774            // (that is remove the NULL spaces within the pDimensionRegions array)
2775            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2776                if (!pDimensionRegions[iTo]) {
2777                    if (iFrom <= iTo) iFrom = iTo + 1;
2778                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2779                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2780                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2781                        pDimensionRegions[iFrom] = NULL;
2782                    }
2783                }
2784            }
2785    
2786            // remove the this dimension from the upper limits arrays
2787            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2788                DimensionRegion* d = pDimensionRegions[j];
2789                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2790                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2791                }
2792                d->DimensionUpperLimits[Dimensions - 1] = 127;
2793            }
2794    
2795            // 'remove' dimension definition
2796            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2797                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2798            }
2799            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2800            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2801            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2802    
2803            Dimensions--;
2804    
2805            // if this was a layer dimension, update 'Layers' attribute
2806            if (pDimDef->dimension == dimension_layer) Layers = 1;
2807        }
2808    
2809        Region::~Region() {
2810            for (int i = 0; i < 256; i++) {
2811              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2812          }          }
2813      }      }
# Line 770  namespace gig { Line 2825  namespace gig {
2825       * 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,
2826       * etc.).       * etc.).
2827       *       *
2828       * @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  
2829       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
2830       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
2831       * @see             Dimensions       * @see             Dimensions
2832       */       */
2833      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2834          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits;
2835            int veldim = -1;
2836            int velbitpos;
2837            int bitpos = 0;
2838            int dimregidx = 0;
2839          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2840              switch (pDimensionDefinitions[i].split_type) {              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2841                  case split_type_normal:                  // the velocity dimension must be handled after the other dimensions
2842                      bits[i] /= pDimensionDefinitions[i].zone_size;                  veldim = i;
2843                      break;                  velbitpos = bitpos;
2844                  case split_type_customvelocity:              } else {
2845                      bits[i] = VelocityTable[bits[i]];                  switch (pDimensionDefinitions[i].split_type) {
2846                      break;                      case split_type_normal:
2847                  // else the value is already the sought dimension bit number                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2848                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2849                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2850                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2851                                }
2852                            } else {
2853                                // gig2: evenly sized zones
2854                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2855                            }
2856                            break;
2857                        case split_type_bit: // the value is already the sought dimension bit number
2858                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2859                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2860                            break;
2861                    }
2862                    dimregidx |= bits << bitpos;
2863              }              }
2864                bitpos += pDimensionDefinitions[i].bits;
2865          }          }
2866          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2867            if (veldim != -1) {
2868                // (dimreg is now the dimension region for the lowest velocity)
2869                if (dimreg->VelocityTable) // custom defined zone ranges
2870                    bits = dimreg->VelocityTable[DimValues[veldim]];
2871                else // normal split type
2872                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2873    
2874                dimregidx |= bits << velbitpos;
2875                dimreg = pDimensionRegions[dimregidx];
2876            }
2877            return dimreg;
2878      }      }
2879    
2880      /**      /**
# Line 800  namespace gig { Line 2882  namespace gig {
2882       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
2883       * instead of calling this method directly!       * instead of calling this method directly!
2884       *       *
2885       * @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  
2886       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
2887       *                 bit numbers       *                 bit numbers
2888       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
2889       */       */
2890      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]) {
2891          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
2892                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
2893                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
2894                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
2895                                                      << pDimensionDefinitions[2].bits | DimBits[2])
2896                                                      << pDimensionDefinitions[1].bits | DimBits[1])
2897                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
2898      }      }
2899    
2900      /**      /**
# Line 830  namespace gig { Line 2911  namespace gig {
2911          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2912      }      }
2913    
2914      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2915            if ((int32_t)WavePoolTableIndex == -1) return NULL;
2916          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2917            if (!file->pWavePoolTable) return NULL;
2918          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2919          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2920            Sample* sample = file->GetFirstSample(pProgress);
2921          while (sample) {          while (sample) {
2922              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2923                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2924              sample = file->GetNextSample();              sample = file->GetNextSample();
2925          }          }
2926          return NULL;          return NULL;
2927      }      }
2928    
2929    
2930    // *************** MidiRule ***************
2931    // *
2932    
2933    MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
2934        _3ewg->SetPos(36);
2935        Triggers = _3ewg->ReadUint8();
2936        _3ewg->SetPos(40);
2937        ControllerNumber = _3ewg->ReadUint8();
2938        _3ewg->SetPos(46);
2939        for (int i = 0 ; i < Triggers ; i++) {
2940            pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
2941            pTriggers[i].Descending = _3ewg->ReadUint8();
2942            pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
2943            pTriggers[i].Key = _3ewg->ReadUint8();
2944            pTriggers[i].NoteOff = _3ewg->ReadUint8();
2945            pTriggers[i].Velocity = _3ewg->ReadUint8();
2946            pTriggers[i].OverridePedal = _3ewg->ReadUint8();
2947            _3ewg->ReadUint8();
2948        }
2949    }
2950    
2951    
2952  // *************** Instrument ***************  // *************** Instrument ***************
2953  // *  // *
2954    
2955      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) {
2956            static const DLS::Info::string_length_t fixedStringLengths[] = {
2957                { CHUNK_ID_INAM, 64 },
2958                { CHUNK_ID_ISFT, 12 },
2959                { 0, 0 }
2960            };
2961            pInfo->SetFixedStringLengths(fixedStringLengths);
2962    
2963          // Initialization          // Initialization
2964          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2965          RegionIndex = -1;          EffectSend = 0;
2966            Attenuation = 0;
2967            FineTune = 0;
2968            PitchbendRange = 0;
2969            PianoReleaseMode = false;
2970            DimensionKeyRange.low = 0;
2971            DimensionKeyRange.high = 0;
2972            pMidiRules = new MidiRule*[3];
2973            pMidiRules[0] = NULL;
2974    
2975          // Loading          // Loading
2976          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 864  namespace gig { Line 2985  namespace gig {
2985                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
2986                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2987                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2988    
2989                    if (_3ewg->GetSize() > 32) {
2990                        // read MIDI rules
2991                        int i = 0;
2992                        _3ewg->SetPos(32);
2993                        uint8_t id1 = _3ewg->ReadUint8();
2994                        uint8_t id2 = _3ewg->ReadUint8();
2995    
2996                        if (id1 == 4 && id2 == 16) {
2997                            pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
2998                        }
2999                        //TODO: all the other types of rules
3000    
3001                        pMidiRules[i] = NULL;
3002                    }
3003              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
3004          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
3005    
3006          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          if (pFile->GetAutoLoad()) {
3007          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");              if (!pRegions) pRegions = new RegionList;
3008          pRegions = new Region*[Regions];              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3009          RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3010          unsigned int iRegion = 0;                  RIFF::List* rgn = lrgn->GetFirstSubList();
3011          while (rgn) {                  while (rgn) {
3012              if (rgn->GetListType() == LIST_TYPE_RGN) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3013                  pRegions[iRegion] = new Region(this, rgn);                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3014                  iRegion++;                          pRegions->push_back(new Region(this, rgn));
3015              }                      }
3016              rgn = lrgn->GetNextSubList();                      rgn = lrgn->GetNextSubList();
3017          }                  }
3018                    // Creating Region Key Table for fast lookup
3019          // Creating Region Key Table for fast lookup                  UpdateRegionKeyTable();
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
3020              }              }
3021          }          }
3022    
3023            __notify_progress(pProgress, 1.0f); // notify done
3024      }      }
3025    
3026      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
3027          for (uint i = 0; i < Regions; i++) {          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3028              if (pRegions) {          RegionList::iterator iter = pRegions->begin();
3029                  if (pRegions[i]) delete (pRegions[i]);          RegionList::iterator end  = pRegions->end();
3030            for (; iter != end; ++iter) {
3031                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
3032                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
3033                    RegionKeyTable[iKey] = pRegion;
3034              }              }
             delete[] pRegions;  
3035          }          }
3036      }      }
3037    
3038        Instrument::~Instrument() {
3039            for (int i = 0 ; pMidiRules[i] ; i++) {
3040                delete pMidiRules[i];
3041            }
3042            delete[] pMidiRules;
3043        }
3044    
3045        /**
3046         * Apply Instrument with all its Regions to the respective RIFF chunks.
3047         * You have to call File::Save() to make changes persistent.
3048         *
3049         * Usually there is absolutely no need to call this method explicitly.
3050         * It will be called automatically when File::Save() was called.
3051         *
3052         * @throws gig::Exception if samples cannot be dereferenced
3053         */
3054        void Instrument::UpdateChunks() {
3055            // first update base classes' chunks
3056            DLS::Instrument::UpdateChunks();
3057    
3058            // update Regions' chunks
3059            {
3060                RegionList::iterator iter = pRegions->begin();
3061                RegionList::iterator end  = pRegions->end();
3062                for (; iter != end; ++iter)
3063                    (*iter)->UpdateChunks();
3064            }
3065    
3066            // make sure 'lart' RIFF list chunk exists
3067            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
3068            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3069            // make sure '3ewg' RIFF chunk exists
3070            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3071            if (!_3ewg)  {
3072                File* pFile = (File*) GetParent();
3073    
3074                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3075                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3076                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3077                memset(_3ewg->LoadChunkData(), 0, size);
3078            }
3079            // update '3ewg' RIFF chunk
3080            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3081            store16(&pData[0], EffectSend);
3082            store32(&pData[2], Attenuation);
3083            store16(&pData[6], FineTune);
3084            store16(&pData[8], PitchbendRange);
3085            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3086                                        DimensionKeyRange.low << 1;
3087            pData[10] = dimkeystart;
3088            pData[11] = DimensionKeyRange.high;
3089        }
3090    
3091      /**      /**
3092       * Returns the appropriate Region for a triggered note.       * Returns the appropriate Region for a triggered note.
3093       *       *
# Line 907  namespace gig { Line 3096  namespace gig {
3096       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3097       */       */
3098      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3099          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3100          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3101    
3102          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
3103              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
3104                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 924  namespace gig { Line 3114  namespace gig {
3114       * @see      GetNextRegion()       * @see      GetNextRegion()
3115       */       */
3116      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
3117          if (!Regions) return NULL;          if (!pRegions) return NULL;
3118          RegionIndex = 1;          RegionsIterator = pRegions->begin();
3119          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3120      }      }
3121    
3122      /**      /**
# Line 938  namespace gig { Line 3128  namespace gig {
3128       * @see      GetFirstRegion()       * @see      GetFirstRegion()
3129       */       */
3130      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
3131          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (!pRegions) return NULL;
3132          return pRegions[RegionIndex++];          RegionsIterator++;
3133            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3134        }
3135    
3136        Region* Instrument::AddRegion() {
3137            // create new Region object (and its RIFF chunks)
3138            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3139            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3140            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3141            Region* pNewRegion = new Region(this, rgn);
3142            pRegions->push_back(pNewRegion);
3143            Regions = pRegions->size();
3144            // update Region key table for fast lookup
3145            UpdateRegionKeyTable();
3146            // done
3147            return pNewRegion;
3148        }
3149    
3150        void Instrument::DeleteRegion(Region* pRegion) {
3151            if (!pRegions) return;
3152            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
3153            // update Region key table for fast lookup
3154            UpdateRegionKeyTable();
3155        }
3156    
3157        /**
3158         * Returns a MIDI rule of the instrument.
3159         *
3160         * The list of MIDI rules, at least in gig v3, always contains at
3161         * most two rules. The second rule can only be the DEF filter
3162         * (which currently isn't supported by libgig).
3163         *
3164         * @param i - MIDI rule number
3165         * @returns   pointer address to MIDI rule number i or NULL if there is none
3166         */
3167        MidiRule* Instrument::GetMidiRule(int i) {
3168            return pMidiRules[i];
3169        }
3170    
3171    
3172    // *************** Group ***************
3173    // *
3174    
3175        /** @brief Constructor.
3176         *
3177         * @param file   - pointer to the gig::File object
3178         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
3179         *                 NULL if this is a new Group
3180         */
3181        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
3182            pFile      = file;
3183            pNameChunk = ck3gnm;
3184            ::LoadString(pNameChunk, Name);
3185        }
3186    
3187        Group::~Group() {
3188            // remove the chunk associated with this group (if any)
3189            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3190        }
3191    
3192        /** @brief Update chunks with current group settings.
3193         *
3194         * Apply current Group field values to the respective chunks. You have
3195         * to call File::Save() to make changes persistent.
3196         *
3197         * Usually there is absolutely no need to call this method explicitly.
3198         * It will be called automatically when File::Save() was called.
3199         */
3200        void Group::UpdateChunks() {
3201            // make sure <3gri> and <3gnl> list chunks exist
3202            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3203            if (!_3gri) {
3204                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3205                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3206            }
3207            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3208            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3209    
3210            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3211                // v3 has a fixed list of 128 strings, find a free one
3212                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3213                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3214                        pNameChunk = ck;
3215                        break;
3216                    }
3217                }
3218            }
3219    
3220            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3221            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3222        }
3223    
3224        /**
3225         * Returns the first Sample of this Group. You have to call this method
3226         * once before you use GetNextSample().
3227         *
3228         * <b>Notice:</b> this method might block for a long time, in case the
3229         * samples of this .gig file were not scanned yet
3230         *
3231         * @returns  pointer address to first Sample or NULL if there is none
3232         *           applied to this Group
3233         * @see      GetNextSample()
3234         */
3235        Sample* Group::GetFirstSample() {
3236            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3237            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
3238                if (pSample->GetGroup() == this) return pSample;
3239            }
3240            return NULL;
3241        }
3242    
3243        /**
3244         * Returns the next Sample of the Group. You have to call
3245         * GetFirstSample() once before you can use this method. By calling this
3246         * method multiple times it iterates through the Samples assigned to
3247         * this Group.
3248         *
3249         * @returns  pointer address to the next Sample of this Group or NULL if
3250         *           end reached
3251         * @see      GetFirstSample()
3252         */
3253        Sample* Group::GetNextSample() {
3254            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3255            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
3256                if (pSample->GetGroup() == this) return pSample;
3257            }
3258            return NULL;
3259        }
3260    
3261        /**
3262         * Move Sample given by \a pSample from another Group to this Group.
3263         */
3264        void Group::AddSample(Sample* pSample) {
3265            pSample->pGroup = this;
3266        }
3267    
3268        /**
3269         * Move all members of this group to another group (preferably the 1st
3270         * one except this). This method is called explicitly by
3271         * File::DeleteGroup() thus when a Group was deleted. This code was
3272         * intentionally not placed in the destructor!
3273         */
3274        void Group::MoveAll() {
3275            // get "that" other group first
3276            Group* pOtherGroup = NULL;
3277            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
3278                if (pOtherGroup != this) break;
3279            }
3280            if (!pOtherGroup) throw Exception(
3281                "Could not move samples to another group, since there is no "
3282                "other Group. This is a bug, report it!"
3283            );
3284            // now move all samples of this group to the other group
3285            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3286                pOtherGroup->AddSample(pSample);
3287            }
3288      }      }
3289    
3290    
# Line 947  namespace gig { Line 3292  namespace gig {
3292  // *************** File ***************  // *************** File ***************
3293  // *  // *
3294    
3295        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3296        const DLS::version_t File::VERSION_2 = {
3297            0, 2, 19980628 & 0xffff, 19980628 >> 16
3298        };
3299    
3300        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3301        const DLS::version_t File::VERSION_3 = {
3302            0, 3, 20030331 & 0xffff, 20030331 >> 16
3303        };
3304    
3305        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3306            { CHUNK_ID_IARL, 256 },
3307            { CHUNK_ID_IART, 128 },
3308            { CHUNK_ID_ICMS, 128 },
3309            { CHUNK_ID_ICMT, 1024 },
3310            { CHUNK_ID_ICOP, 128 },
3311            { CHUNK_ID_ICRD, 128 },
3312            { CHUNK_ID_IENG, 128 },
3313            { CHUNK_ID_IGNR, 128 },
3314            { CHUNK_ID_IKEY, 128 },
3315            { CHUNK_ID_IMED, 128 },
3316            { CHUNK_ID_INAM, 128 },
3317            { CHUNK_ID_IPRD, 128 },
3318            { CHUNK_ID_ISBJ, 128 },
3319            { CHUNK_ID_ISFT, 128 },
3320            { CHUNK_ID_ISRC, 128 },
3321            { CHUNK_ID_ISRF, 128 },
3322            { CHUNK_ID_ITCH, 128 },
3323            { 0, 0 }
3324        };
3325    
3326        File::File() : DLS::File() {
3327            bAutoLoad = true;
3328            *pVersion = VERSION_3;
3329            pGroups = NULL;
3330            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3331            pInfo->ArchivalLocation = String(256, ' ');
3332    
3333            // add some mandatory chunks to get the file chunks in right
3334            // order (INFO chunk will be moved to first position later)
3335            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3336            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3337            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3338    
3339            GenerateDLSID();
3340        }
3341    
3342      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3343          pSamples     = NULL;          bAutoLoad = true;
3344          pInstruments = NULL;          pGroups = NULL;
3345            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3346        }
3347    
3348        File::~File() {
3349            if (pGroups) {
3350                std::list<Group*>::iterator iter = pGroups->begin();
3351                std::list<Group*>::iterator end  = pGroups->end();
3352                while (iter != end) {
3353                    delete *iter;
3354                    ++iter;
3355                }
3356                delete pGroups;
3357            }
3358      }      }
3359    
3360      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
3361          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
3362          if (!pSamples) return NULL;          if (!pSamples) return NULL;
3363          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
3364          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 965  namespace gig { Line 3370  namespace gig {
3370          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3371      }      }
3372    
3373      void File::LoadSamples() {      /** @brief Add a new sample.
3374          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);       *
3375          if (wvpl) {       * This will create a new Sample object for the gig file. You have to
3376              unsigned long wvplFileOffset = wvpl->GetFilePos();       * call Save() to make this persistent to the file.
3377              RIFF::List* wave = wvpl->GetFirstSubList();       *
3378              while (wave) {       * @returns pointer to new Sample object
3379                  if (wave->GetListType() == LIST_TYPE_WAVE) {       */
3380                      if (!pSamples) pSamples = new SampleList;      Sample* File::AddSample() {
3381                      unsigned long waveFileOffset = wave->GetFilePos();         if (!pSamples) LoadSamples();
3382                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));         __ensureMandatoryChunksExist();
3383           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
3384           // create new Sample object and its respective 'wave' list chunk
3385           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3386           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
3387    
3388           // add mandatory chunks to get the chunks in right order
3389           wave->AddSubChunk(CHUNK_ID_FMT, 16);
3390           wave->AddSubList(LIST_TYPE_INFO);
3391    
3392           pSamples->push_back(pSample);
3393           return pSample;
3394        }
3395    
3396        /** @brief Delete a sample.
3397         *
3398         * This will delete the given Sample object from the gig file. Any
3399         * references to this sample from Regions and DimensionRegions will be
3400         * removed. You have to call Save() to make this persistent to the file.
3401         *
3402         * @param pSample - sample to delete
3403         * @throws gig::Exception if given sample could not be found
3404         */
3405        void File::DeleteSample(Sample* pSample) {
3406            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
3407            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
3408            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
3409            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3410            pSamples->erase(iter);
3411            delete pSample;
3412    
3413            SampleList::iterator tmp = SamplesIterator;
3414            // remove all references to the sample
3415            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3416                 instrument = GetNextInstrument()) {
3417                for (Region* region = instrument->GetFirstRegion() ; region ;
3418                     region = instrument->GetNextRegion()) {
3419    
3420                    if (region->GetSample() == pSample) region->SetSample(NULL);
3421    
3422                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3423                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3424                        if (d->pSample == pSample) d->pSample = NULL;
3425                  }                  }
                 wave = wvpl->GetNextSubList();  
3426              }              }
3427          }          }
3428          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          SamplesIterator = tmp; // restore iterator
3429        }
3430    
3431        void File::LoadSamples() {
3432            LoadSamples(NULL);
3433        }
3434    
3435        void File::LoadSamples(progress_t* pProgress) {
3436            // Groups must be loaded before samples, because samples will try
3437            // to resolve the group they belong to
3438            if (!pGroups) LoadGroups();
3439    
3440            if (!pSamples) pSamples = new SampleList;
3441    
3442            RIFF::File* file = pRIFF;
3443    
3444            // just for progress calculation
3445            int iSampleIndex  = 0;
3446            int iTotalSamples = WavePoolCount;
3447    
3448            // check if samples should be loaded from extension files
3449            int lastFileNo = 0;
3450            for (int i = 0 ; i < WavePoolCount ; i++) {
3451                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
3452            }
3453            String name(pRIFF->GetFileName());
3454            int nameLen = name.length();
3455            char suffix[6];
3456            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
3457    
3458            for (int fileNo = 0 ; ; ) {
3459                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
3460                if (wvpl) {
3461                    unsigned long wvplFileOffset = wvpl->GetFilePos();
3462                    RIFF::List* wave = wvpl->GetFirstSubList();
3463                    while (wave) {
3464                        if (wave->GetListType() == LIST_TYPE_WAVE) {
3465                            // notify current progress
3466                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
3467                            __notify_progress(pProgress, subprogress);
3468    
3469                            unsigned long waveFileOffset = wave->GetFilePos();
3470                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
3471    
3472                            iSampleIndex++;
3473                        }
3474                        wave = wvpl->GetNextSubList();
3475                    }
3476    
3477                    if (fileNo == lastFileNo) break;
3478    
3479                    // open extension file (*.gx01, *.gx02, ...)
3480                    fileNo++;
3481                    sprintf(suffix, ".gx%02d", fileNo);
3482                    name.replace(nameLen, 5, suffix);
3483                    file = new RIFF::File(name);
3484                    ExtensionFiles.push_back(file);
3485                } else break;
3486            }
3487    
3488            __notify_progress(pProgress, 1.0); // notify done
3489      }      }
3490    
3491      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
3492          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
3493          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3494          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3495          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3496      }      }
3497    
3498      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
3499          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3500          InstrumentsIterator++;          InstrumentsIterator++;
3501          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3502        }
3503    
3504        /**
3505         * Returns the instrument with the given index.
3506         *
3507         * @param index     - number of the sought instrument (0..n)
3508         * @param pProgress - optional: callback function for progress notification
3509         * @returns  sought instrument or NULL if there's no such instrument
3510         */
3511        Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
3512            if (!pInstruments) {
3513                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
3514    
3515                // sample loading subtask
3516                progress_t subprogress;
3517                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
3518                __notify_progress(&subprogress, 0.0f);
3519                if (GetAutoLoad())
3520                    GetFirstSample(&subprogress); // now force all samples to be loaded
3521                __notify_progress(&subprogress, 1.0f);
3522    
3523                // instrument loading subtask
3524                if (pProgress && pProgress->callback) {
3525                    subprogress.__range_min = subprogress.__range_max;
3526                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
3527                }
3528                __notify_progress(&subprogress, 0.0f);
3529                LoadInstruments(&subprogress);
3530                __notify_progress(&subprogress, 1.0f);
3531            }
3532            if (!pInstruments) return NULL;
3533            InstrumentsIterator = pInstruments->begin();
3534            for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
3535                if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
3536                InstrumentsIterator++;
3537            }
3538            return NULL;
3539        }
3540    
3541        /** @brief Add a new instrument definition.
3542         *
3543         * This will create a new Instrument object for the gig file. You have
3544         * to call Save() to make this persistent to the file.
3545         *
3546         * @returns pointer to new Instrument object
3547         */
3548        Instrument* File::AddInstrument() {
3549           if (!pInstruments) LoadInstruments();
3550           __ensureMandatoryChunksExist();
3551           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3552           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3553    
3554           // add mandatory chunks to get the chunks in right order
3555           lstInstr->AddSubList(LIST_TYPE_INFO);
3556           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
3557    
3558           Instrument* pInstrument = new Instrument(this, lstInstr);
3559           pInstrument->GenerateDLSID();
3560    
3561           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
3562    
3563           // this string is needed for the gig to be loadable in GSt:
3564           pInstrument->pInfo->Software = "Endless Wave";
3565    
3566           pInstruments->push_back(pInstrument);
3567           return pInstrument;
3568        }
3569    
3570        /** @brief Delete an instrument.
3571         *
3572         * This will delete the given Instrument object from the gig file. You
3573         * have to call Save() to make this persistent to the file.
3574         *
3575         * @param pInstrument - instrument to delete
3576         * @throws gig::Exception if given instrument could not be found
3577         */
3578        void File::DeleteInstrument(Instrument* pInstrument) {
3579            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
3580            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3581            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
3582            pInstruments->erase(iter);
3583            delete pInstrument;
3584      }      }
3585    
3586      void File::LoadInstruments() {      void File::LoadInstruments() {
3587            LoadInstruments(NULL);
3588        }
3589    
3590        void File::LoadInstruments(progress_t* pProgress) {
3591            if (!pInstruments) pInstruments = new InstrumentList;
3592          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3593          if (lstInstruments) {          if (lstInstruments) {
3594                int iInstrumentIndex = 0;
3595              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
3596              while (lstInstr) {              while (lstInstr) {
3597                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
3598                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
3599                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
3600                        __notify_progress(pProgress, localProgress);
3601    
3602                        // divide local progress into subprogress for loading current Instrument
3603                        progress_t subprogress;
3604                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3605    
3606                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3607    
3608                        iInstrumentIndex++;
3609                  }                  }
3610                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
3611              }              }
3612                __notify_progress(pProgress, 1.0); // notify done
3613            }
3614        }
3615    
3616        /// Updates the 3crc chunk with the checksum of a sample. The
3617        /// update is done directly to disk, as this method is called
3618        /// after File::Save()
3619        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
3620            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3621            if (!_3crc) return;
3622    
3623            // get the index of the sample
3624            int iWaveIndex = -1;
3625            File::SampleList::iterator iter = pSamples->begin();
3626            File::SampleList::iterator end  = pSamples->end();
3627            for (int index = 0; iter != end; ++iter, ++index) {
3628                if (*iter == pSample) {
3629                    iWaveIndex = index;
3630                    break;
3631                }
3632            }
3633            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
3634    
3635            // write the CRC-32 checksum to disk
3636            _3crc->SetPos(iWaveIndex * 8);
3637            uint32_t tmp = 1;
3638            _3crc->WriteUint32(&tmp); // unknown, always 1?
3639            _3crc->WriteUint32(&crc);
3640        }
3641    
3642        Group* File::GetFirstGroup() {
3643            if (!pGroups) LoadGroups();
3644            // there must always be at least one group
3645            GroupsIterator = pGroups->begin();
3646            return *GroupsIterator;
3647        }
3648    
3649        Group* File::GetNextGroup() {
3650            if (!pGroups) return NULL;
3651            ++GroupsIterator;
3652            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3653        }
3654    
3655        /**
3656         * Returns the group with the given index.
3657         *
3658         * @param index - number of the sought group (0..n)
3659         * @returns sought group or NULL if there's no such group
3660         */
3661        Group* File::GetGroup(uint index) {
3662            if (!pGroups) LoadGroups();
3663            GroupsIterator = pGroups->begin();
3664            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3665                if (i == index) return *GroupsIterator;
3666                ++GroupsIterator;
3667            }
3668            return NULL;
3669        }
3670    
3671        Group* File::AddGroup() {
3672            if (!pGroups) LoadGroups();
3673            // there must always be at least one group
3674            __ensureMandatoryChunksExist();
3675            Group* pGroup = new Group(this, NULL);
3676            pGroups->push_back(pGroup);
3677            return pGroup;
3678        }
3679    
3680        /** @brief Delete a group and its samples.
3681         *
3682         * This will delete the given Group object and all the samples that
3683         * belong to this group from the gig file. You have to call Save() to
3684         * make this persistent to the file.
3685         *
3686         * @param pGroup - group to delete
3687         * @throws gig::Exception if given group could not be found
3688         */
3689        void File::DeleteGroup(Group* pGroup) {
3690            if (!pGroups) LoadGroups();
3691            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3692            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3693            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3694            // delete all members of this group
3695            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
3696                DeleteSample(pSample);
3697            }
3698            // now delete this group object
3699            pGroups->erase(iter);
3700            delete pGroup;
3701        }
3702    
3703        /** @brief Delete a group.
3704         *
3705         * This will delete the given Group object from the gig file. All the
3706         * samples that belong to this group will not be deleted, but instead
3707         * be moved to another group. You have to call Save() to make this
3708         * persistent to the file.
3709         *
3710         * @param pGroup - group to delete
3711         * @throws gig::Exception if given group could not be found
3712         */
3713        void File::DeleteGroupOnly(Group* pGroup) {
3714            if (!pGroups) LoadGroups();
3715            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3716            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3717            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3718            // move all members of this group to another group
3719            pGroup->MoveAll();
3720            pGroups->erase(iter);
3721            delete pGroup;
3722        }
3723    
3724        void File::LoadGroups() {
3725            if (!pGroups) pGroups = new std::list<Group*>;
3726            // try to read defined groups from file
3727            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3728            if (lst3gri) {
3729                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3730                if (lst3gnl) {
3731                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3732                    while (ck) {
3733                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3734                            if (pVersion && pVersion->major == 3 &&
3735                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
3736    
3737                            pGroups->push_back(new Group(this, ck));
3738                        }
3739                        ck = lst3gnl->GetNextSubChunk();
3740                    }
3741                }
3742            }
3743            // if there were no group(s), create at least the mandatory default group
3744            if (!pGroups->size()) {
3745                Group* pGroup = new Group(this, NULL);
3746                pGroup->Name = "Default Group";
3747                pGroups->push_back(pGroup);
3748          }          }
3749          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
3750    
3751        /**
3752         * Apply all the gig file's current instruments, samples, groups and settings
3753         * to the respective RIFF chunks. You have to call Save() to make changes
3754         * persistent.
3755         *
3756         * Usually there is absolutely no need to call this method explicitly.
3757         * It will be called automatically when File::Save() was called.
3758         *
3759         * @throws Exception - on errors
3760         */
3761        void File::UpdateChunks() {
3762            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
3763    
3764            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
3765    
3766            // first update base class's chunks
3767            DLS::File::UpdateChunks();
3768    
3769            if (newFile) {
3770                // INFO was added by Resource::UpdateChunks - make sure it
3771                // is placed first in file
3772                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
3773                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
3774                if (first != info) {
3775                    pRIFF->MoveSubChunk(info, first);
3776                }
3777            }
3778    
3779            // update group's chunks
3780            if (pGroups) {
3781                std::list<Group*>::iterator iter = pGroups->begin();
3782                std::list<Group*>::iterator end  = pGroups->end();
3783                for (; iter != end; ++iter) {
3784                    (*iter)->UpdateChunks();
3785                }
3786    
3787                // v3: make sure the file has 128 3gnm chunks
3788                if (pVersion && pVersion->major == 3) {
3789                    RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);
3790                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
3791                    for (int i = 0 ; i < 128 ; i++) {
3792                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
3793                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
3794                    }
3795                }
3796            }
3797    
3798            // update einf chunk
3799    
3800            // The einf chunk contains statistics about the gig file, such
3801            // as the number of regions and samples used by each
3802            // instrument. It is divided in equally sized parts, where the
3803            // first part contains information about the whole gig file,
3804            // and the rest of the parts map to each instrument in the
3805            // file.
3806            //
3807            // At the end of each part there is a bit map of each sample
3808            // in the file, where a set bit means that the sample is used
3809            // by the file/instrument.
3810            //
3811            // Note that there are several fields with unknown use. These
3812            // are set to zero.
3813    
3814            int sublen = pSamples->size() / 8 + 49;
3815            int einfSize = (Instruments + 1) * sublen;
3816    
3817            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
3818            if (einf) {
3819                if (einf->GetSize() != einfSize) {
3820                    einf->Resize(einfSize);
3821                    memset(einf->LoadChunkData(), 0, einfSize);
3822                }
3823            } else if (newFile) {
3824                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
3825            }
3826            if (einf) {
3827                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
3828    
3829                std::map<gig::Sample*,int> sampleMap;
3830                int sampleIdx = 0;
3831                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3832                    sampleMap[pSample] = sampleIdx++;
3833                }
3834    
3835                int totnbusedsamples = 0;
3836                int totnbusedchannels = 0;
3837                int totnbregions = 0;
3838                int totnbdimregions = 0;
3839                int totnbloops = 0;
3840                int instrumentIdx = 0;
3841    
3842                memset(&pData[48], 0, sublen - 48);
3843    
3844                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3845                     instrument = GetNextInstrument()) {
3846                    int nbusedsamples = 0;
3847                    int nbusedchannels = 0;
3848                    int nbdimregions = 0;
3849                    int nbloops = 0;
3850    
3851                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
3852    
3853                    for (Region* region = instrument->GetFirstRegion() ; region ;
3854                         region = instrument->GetNextRegion()) {
3855                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
3856                            gig::DimensionRegion *d = region->pDimensionRegions[i];
3857                            if (d->pSample) {
3858                                int sampleIdx = sampleMap[d->pSample];
3859                                int byte = 48 + sampleIdx / 8;
3860                                int bit = 1 << (sampleIdx & 7);
3861                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
3862                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
3863                                    nbusedsamples++;
3864                                    nbusedchannels += d->pSample->Channels;
3865    
3866                                    if ((pData[byte] & bit) == 0) {
3867                                        pData[byte] |= bit;
3868                                        totnbusedsamples++;
3869                                        totnbusedchannels += d->pSample->Channels;
3870                                    }
3871                                }
3872                            }
3873                            if (d->SampleLoops) nbloops++;
3874                        }
3875                        nbdimregions += region->DimensionRegions;
3876                    }
3877                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
3878                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
3879                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
3880                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
3881                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
3882                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
3883                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
3884                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
3885                    // next 8 bytes unknown
3886                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
3887                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
3888                    // next 4 bytes unknown
3889    
3890                    totnbregions += instrument->Regions;
3891                    totnbdimregions += nbdimregions;
3892                    totnbloops += nbloops;
3893                    instrumentIdx++;
3894                }
3895                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
3896                // store32(&pData[0], sublen);
3897                store32(&pData[4], totnbusedchannels);
3898                store32(&pData[8], totnbusedsamples);
3899                store32(&pData[12], Instruments);
3900                store32(&pData[16], totnbregions);
3901                store32(&pData[20], totnbdimregions);
3902                store32(&pData[24], totnbloops);
3903                // next 8 bytes unknown
3904                // next 4 bytes unknown, not always 0
3905                store32(&pData[40], pSamples->size());
3906                // next 4 bytes unknown
3907            }
3908    
3909            // update 3crc chunk
3910    
3911            // The 3crc chunk contains CRC-32 checksums for the
3912            // samples. The actual checksum values will be filled in
3913            // later, by Sample::Write.
3914    
3915            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3916            if (_3crc) {
3917                _3crc->Resize(pSamples->size() * 8);
3918            } else if (newFile) {
3919                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
3920                _3crc->LoadChunkData();
3921    
3922                // the order of einf and 3crc is not the same in v2 and v3
3923                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
3924            }
3925        }
3926    
3927        /**
3928         * Enable / disable automatic loading. By default this properyt is
3929         * enabled and all informations are loaded automatically. However
3930         * loading all Regions, DimensionRegions and especially samples might
3931         * take a long time for large .gig files, and sometimes one might only
3932         * be interested in retrieving very superficial informations like the
3933         * amount of instruments and their names. In this case one might disable
3934         * automatic loading to avoid very slow response times.
3935         *
3936         * @e CAUTION: by disabling this property many pointers (i.e. sample
3937         * references) and informations will have invalid or even undefined
3938         * data! This feature is currently only intended for retrieving very
3939         * superficial informations in a very fast way. Don't use it to retrieve
3940         * details like synthesis informations or even to modify .gig files!
3941         */
3942        void File::SetAutoLoad(bool b) {
3943            bAutoLoad = b;
3944        }
3945    
3946        /**
3947         * Returns whether automatic loading is enabled.
3948         * @see SetAutoLoad()
3949         */
3950        bool File::GetAutoLoad() {
3951            return bAutoLoad;
3952      }      }
3953    
3954    
# Line 1022  namespace gig { Line 3963  namespace gig {
3963          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
3964      }      }
3965    
3966    
3967    // *************** functions ***************
3968    // *
3969    
3970        /**
3971         * Returns the name of this C++ library. This is usually "libgig" of
3972         * course. This call is equivalent to RIFF::libraryName() and
3973         * DLS::libraryName().
3974         */
3975        String libraryName() {
3976            return PACKAGE;
3977        }
3978    
3979        /**
3980         * Returns version of this C++ library. This call is equivalent to
3981         * RIFF::libraryVersion() and DLS::libraryVersion().
3982         */
3983        String libraryVersion() {
3984            return VERSION;
3985        }
3986    
3987  } // namespace gig  } // namespace gig

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

  ViewVC Help
Powered by ViewVC