/[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 24 by schoenebeck, Fri Dec 26 16:15:31 2003 UTC revision 2482 by schoenebeck, Mon Nov 25 02:22:38 2013 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-2013 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            __resetCRC(crc);
379    
380          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
382          SampleGroup = _3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
383                pGroup = pFile->GetGroup(iSampleGroup);
384          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          } else { // '3gix' chunk missing
385          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              // by default assigned to that mandatory "Default Group"
386          Manufacturer      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
387          Product           = smpl->ReadInt32();          }
388          SamplePeriod      = smpl->ReadInt32();  
389          MIDIUnityNote     = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
390          FineTune          = smpl->ReadInt32();          if (pCkSmpl) {
391          smpl->Read(&SMPTEFormat, 1, 4);              Manufacturer  = pCkSmpl->ReadInt32();
392          SMPTEOffset       = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
393          Loops             = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
394          uint32_t manufByt = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
395          LoopID            = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
396          smpl->Read(&LoopType, 1, 4);              pCkSmpl->Read(&SMPTEFormat, 1, 4);
397          LoopStart         = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
398          LoopEnd           = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
399          LoopFraction      = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
400          LoopPlayCount     = smpl->ReadInt32();              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 63  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              ScanCompressedSample();              uint32_t version = ewav->ReadInt32();
438              if (!pDecompressionBuffer) {              if (version == 3 && BitDepth == 24) {
439                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];                  Dithered = ewav->ReadInt32();
440                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;                  ewav->SetPos(Channels == 2 ? 84 : 64);
441                    TruncatedBits = ewav->ReadInt32();
442              }              }
443                ScanCompressedSample();
444            }
445    
446            // 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         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518          }          }
519          FrameOffset = 0; // just for streaming compressed samples          pOrig->SetPos(restorePos);
520            delete [] buf;
521        }
522    
523          LoopStart /= FrameSize; // convert to sample points      /**
524          LoopEnd   /= FrameSize; // convert to sample points       * Apply sample and its settings to the respective RIFF chunks. You have
525          LoopSize   = LoopEnd - LoopStart;       * to call File::Save() to make changes persistent.
526         *
527         * Usually there is absolutely no need to call this method explicitly.
528         * It will be called automatically when File::Save() was called.
529         *
530         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
531         *                        was provided yet
532         * @throws gig::Exception if there is any invalid sample setting
533         */
534        void Sample::UpdateChunks() {
535            // first update base class's chunks
536            DLS::Sample::UpdateChunks();
537    
538            // make sure 'smpl' chunk exists
539            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
540            if (!pCkSmpl) {
541                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
542                memset(pCkSmpl->LoadChunkData(), 0, 60);
543            }
544            // update 'smpl' chunk
545            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
546            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
547            store32(&pData[0], Manufacturer);
548            store32(&pData[4], Product);
549            store32(&pData[8], SamplePeriod);
550            store32(&pData[12], MIDIUnityNote);
551            store32(&pData[16], FineTune);
552            store32(&pData[20], SMPTEFormat);
553            store32(&pData[24], SMPTEOffset);
554            store32(&pData[28], Loops);
555    
556            // we skip 'manufByt' for now (4 bytes)
557    
558            store32(&pData[36], LoopID);
559            store32(&pData[40], LoopType);
560            store32(&pData[44], LoopStart);
561            store32(&pData[48], LoopEnd);
562            store32(&pData[52], LoopFraction);
563            store32(&pData[56], LoopPlayCount);
564    
565            // make sure '3gix' chunk exists
566            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
567            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
568            // determine appropriate sample group index (to be stored in chunk)
569            uint16_t iSampleGroup = 0; // 0 refers to default sample group
570            File* pFile = static_cast<File*>(pParent);
571            if (pFile->pGroups) {
572                std::list<Group*>::iterator iter = pFile->pGroups->begin();
573                std::list<Group*>::iterator end  = pFile->pGroups->end();
574                for (int i = 0; iter != end; i++, iter++) {
575                    if (*iter == pGroup) {
576                        iSampleGroup = i;
577                        break; // found
578                    }
579                }
580            }
581            // update '3gix' chunk
582            pData = (uint8_t*) pCk3gix->LoadChunkData();
583            store16(&pData[0], iSampleGroup);
584      }      }
585    
586      /// 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 84  namespace gig { Line 589  namespace gig {
589          this->SamplesTotal = 0;          this->SamplesTotal = 0;
590          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
591    
592            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
593            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
594    
595          // Scanning          // Scanning
596          pCkData->SetPos(0);          pCkData->SetPos(0);
597          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
598              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
599              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
600              this->SamplesTotal += 2048;                  // stored, to save some memory
601              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
602                  case 1:   // left channel compressed  
603                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
604                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
605                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
606                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
607    
608                    if (pCkData->RemainingBytes() <= frameSize) {
609                        SamplesInLastFrame =
610                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
611                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
612                        SamplesTotal += SamplesInLastFrame;
613                      break;                      break;
614                  case 257: // both channels compressed                  }
615                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
616                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
617                }
618            }
619            else { // Mono
620                for (int i = 0 ; ; i++) {
621                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
622    
623                    const int mode = pCkData->ReadUint8();
624                    if (mode > 5) throw gig::Exception("Unknown compression mode");
625                    const unsigned long frameSize = bytesPerFrame[mode];
626    
627                    if (pCkData->RemainingBytes() <= frameSize) {
628                        SamplesInLastFrame =
629                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
630                        SamplesTotal += SamplesInLastFrame;
631                      break;                      break;
632                  default: // both channels uncompressed                  }
633                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
634                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
635              }              }
636          }          }
637          pCkData->SetPos(0);          pCkData->SetPos(0);
638    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
639          // 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)
640          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
641          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 143  namespace gig { Line 671  namespace gig {
671       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
672       * 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
673       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
674       *       * @code
675       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
676       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
677         * @endcode
678       *       *
679       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
680       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 191  namespace gig { Line 720  namespace gig {
720       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
721       * 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
722       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
723       *       * @code
724       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
725       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
726       *       * @endcode
727       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
728       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
729       * 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 215  namespace gig { Line 744  namespace gig {
744          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
745          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
746          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
747            SetPos(0); // reset read position to begin of sample
748          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
749          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
750          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 252  namespace gig { Line 782  namespace gig {
782          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
783          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
784          RAMCache.Size   = 0;          RAMCache.Size   = 0;
785            RAMCache.NullExtensionSize = 0;
786        }
787    
788        /** @brief Resize sample.
789         *
790         * Resizes the sample's wave form data, that is the actual size of
791         * sample wave data possible to be written for this sample. This call
792         * will return immediately and just schedule the resize operation. You
793         * should call File::Save() to actually perform the resize operation(s)
794         * "physically" to the file. As this can take a while on large files, it
795         * is recommended to call Resize() first on all samples which have to be
796         * resized and finally to call File::Save() to perform all those resize
797         * operations in one rush.
798         *
799         * The actual size (in bytes) is dependant to the current FrameSize
800         * value. You may want to set FrameSize before calling Resize().
801         *
802         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
803         * enlarged samples before calling File::Save() as this might exceed the
804         * current sample's boundary!
805         *
806         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
807         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
808         * other formats will fail!
809         *
810         * @param iNewSize - new sample wave data size in sample points (must be
811         *                   greater than zero)
812         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
813         *                         or if \a iNewSize is less than 1
814         * @throws gig::Exception if existing sample is compressed
815         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
816         *      DLS::Sample::FormatTag, File::Save()
817         */
818        void Sample::Resize(int iNewSize) {
819            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
820            DLS::Sample::Resize(iNewSize);
821      }      }
822    
823      /**      /**
# Line 309  namespace gig { Line 875  namespace gig {
875      /**      /**
876       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
877       */       */
878      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
879          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
880          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
881      }      }
# Line 325  namespace gig { Line 891  namespace gig {
891       * for the next time you call this method is stored in \a pPlaybackState.       * for the next time you call this method is stored in \a pPlaybackState.
892       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
893       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
894       *       * @code
895       * <i>       * gig::playback_state_t playbackstate;
896       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
897       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
898       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
899       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
900       * You don't have to take care of things like if there is actually a loop       * You don't have to take care of things like if there is actually a loop
901       * defined or if the current read position is located within a loop area.       * defined or if the current read position is located within a loop area.
902       * The method already handles such cases by itself.       * The method already handles such cases by itself.
903       *       *
904         * <b>Caution:</b> If you are using more than one streaming thread, you
905         * have to use an external decompression buffer for <b>EACH</b>
906         * streaming thread to avoid race conditions and crashes!
907         *
908       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
909       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
910       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
911       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
912         * @param pDimRgn          dimension region with looping information
913         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
914       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
915         * @see                    CreateDecompressionBuffer()
916       */       */
917      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
918                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
919          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
920          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
921    
922          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
923    
924          if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined          if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
925    
926              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
927                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
928    
929                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
930                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
931    
932                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
933                              // determine the end position within the loop first,                          do {
934                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
935                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
936                              // backward playback  
937                                if (!pPlaybackState->reverse) { // forward playback
938                              unsigned long swapareastart       = totalreadsamples;                                  do {
939                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
940                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
941                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
942                                        totalreadsamples += readsamples;
943                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
944                                            pPlaybackState->reverse = true;
945                              // read samples for backward playback                                          break;
946                              do {                                      }
947                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  } while (samplestoread && readsamples);
948                                  samplestoreadinloop -= readsamples;                              }
949                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
950    
951                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
952                                    // determine the end position within the loop first,
953                                    // read forward from that 'end' and finally after
954                                    // reading, swap all sample frames so it reflects
955                                    // backward playback
956    
957                                    unsigned long swapareastart       = totalreadsamples;
958                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
959                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
960                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
961    
962                                    SetPos(reverseplaybackend);
963    
964                                    // read samples for backward playback
965                                    do {
966                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
967                                        samplestoreadinloop -= readsamples;
968                                        samplestoread       -= readsamples;
969                                        totalreadsamples    += readsamples;
970                                    } while (samplestoreadinloop && readsamples);
971    
972                                    SetPos(reverseplaybackend); // pretend we really read backwards
973    
974                                    if (reverseplaybackend == loop.LoopStart) {
975                                        pPlaybackState->loop_cycles_left--;
976                                        pPlaybackState->reverse = false;
977                                    }
978    
979                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
980                                  pPlaybackState->loop_cycles_left--;                                  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!
981                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
982                              }                              }
983                            } while (samplestoread && readsamples);
984                            break;
985                        }
986    
987                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
988                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
989                          }                          if (!pPlaybackState->reverse) do {
990                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
991                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
992                  }                              samplestoread    -= readsamples;
993                                totalreadsamples += readsamples;
994                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
995                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
996                      if (!pPlaybackState->reverse) do {                                  break;
997                          samplestoloopend  = this->LoopEnd - GetPos();                              }
998                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
999    
1000                      if (!samplestoread) break;                          if (!samplestoread) break;
1001    
1002                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
1003                      // determine the end position within the loop first,                          // determine the end position within the loop first,
1004                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
1005                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1006                      // backward playback                          // backward playback
1007    
1008                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
1009                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
1010                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1011                                                                                : samplestoread;                                                                                    : samplestoread;
1012                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1013    
1014                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1015    
1016                      // read samples for backward playback                          // read samples for backward playback
1017                      do {                          do {
1018                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1019                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1020                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
1021                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1022                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1023                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1024                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1025                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1026                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1027                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1028                          }                              }
1029                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1030    
1031                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1032    
1033                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1034                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1035                      break;                          break;
1036                  }                      }
1037    
1038                  default: case loop_type_normal: {                      default: case loop_type_normal: {
1039                      do {                          do {
1040                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1041                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1042                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
1043                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1044                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1045                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1046                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1047                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1048                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1049                          }                              }
1050                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1051                      break;                          break;
1052                        }
1053                  }                  }
1054              }              }
1055          }          }
1056    
1057          // read on without looping          // read on without looping
1058          if (samplestoread) do {          if (samplestoread) do {
1059              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1060              samplestoread    -= readsamples;              samplestoread    -= readsamples;
1061              totalreadsamples += readsamples;              totalreadsamples += readsamples;
1062          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 497  namespace gig { Line 1075  namespace gig {
1075       * 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,
1076       * thus for disk streaming.       * thus for disk streaming.
1077       *       *
1078         * <b>Caution:</b> If you are using more than one streaming thread, you
1079         * have to use an external decompression buffer for <b>EACH</b>
1080         * streaming thread to avoid race conditions and crashes!
1081         *
1082         * For 16 bit samples, the data in the buffer will be int16_t
1083         * (using native endianness). For 24 bit, the buffer will
1084         * contain three bytes per sample, little-endian.
1085         *
1086       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1087       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1088         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
1089       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1090       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
1091       */       */
1092      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1093          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1094          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?          if (!Compressed) {
1095          else { //FIXME: no support for mono compressed samples yet, are there any?              if (BitDepth == 24) {
1096                    return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1097                }
1098                else { // 16 bit
1099                    // (pCkData->Read does endian correction)
1100                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1101                                         : pCkData->Read(pBuffer, SampleCount, 2);
1102                }
1103            }
1104            else {
1105              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1106              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1107              // best case needed buffer size (all frames compressed)              unsigned long assumedsize      = GuessSize(SampleCount),
             unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                              (SampleCount >> 10) + // 10 bytes header per 2048 sample points  
                                              8194,                 // at least one worst case sample frame  
1108                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1109                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1110                            copysamples;                            copysamples, skipsamples,
1111              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
1112              this->FrameOffset = 0;              this->FrameOffset = 0;
1113    
1114              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1115                  // local buffer reallocation - hope this won't happen  
1116                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
1117                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
1118                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1119                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
1120                    remainingsamples = SampleCount;
1121                    assumedsize      = GuessSize(SampleCount);
1122              }              }
1123    
1124              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1125              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1126              int16_t* pDst = (int16_t*) pBuffer;              uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1127              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1128    
1129              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
1130                    unsigned long framesamples = SamplesPerFrame;
1131                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1132                  if (remainingbytes < 8194) {  
1133                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
1134                          this->SamplePos = this->SamplesTotal;  
1135                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
1136                      }                      mode_r = *pSrc++;
1137                      assumedsize    = remainingsamples;                      framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1138                      assumedsize    = (assumedsize << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)                      rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1139                                       (assumedsize >> 10) + // 10 bytes header per 2048 sample points                      nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1140                                       8194;                 // at least one worst case sample frame                      if (remainingbytes < framebytes) { // last frame in sample
1141                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          framesamples = SamplesInLastFrame;
1142                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                          if (mode_l == 4 && (framesamples & 1)) {
1143                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                              rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1144                      pSrc = (int8_t*) this->pDecompressionBuffer;                          }
1145                            else {
1146                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1147                            }
1148                        }
1149                    }
1150                    else {
1151                        framebytes = bytesPerFrame[mode_l] + 1;
1152                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1153                        if (remainingbytes < framebytes) {
1154                            framesamples = SamplesInLastFrame;
1155                        }
1156                  }                  }
1157    
1158                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
1159                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
1160                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
1161                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
1162                            skipsamples = currentframeoffset;
1163                        }
1164                        else {
1165                            copysamples = 0;
1166                            skipsamples = framesamples;
1167                        }
1168                  }                  }
1169                  else {                  else {
1170                        // This frame has enough data for pBuffer, but not
1171                        // all of the frame is needed. Set file position
1172                        // to start of this frame for next call to Read.
1173                      copysamples = remainingsamples;                      copysamples = remainingsamples;
1174                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
1175                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1176                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
1177                      }                  }
1178                      else {                  remainingsamples -= copysamples;
1179    
1180                    if (remainingbytes > framebytes) {
1181                        remainingbytes -= framebytes;
1182                        if (remainingsamples == 0 &&
1183                            currentframeoffset + copysamples == framesamples) {
1184                            // This frame has enough data for pBuffer, and
1185                            // all of the frame is needed. Set file
1186                            // position to start of next frame for next
1187                            // call to Read. FrameOffset is 0.
1188                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
1189                      }                      }
1190                  }                  }
1191                    else remainingbytes = 0;
1192    
1193                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
1194                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
1195                  switch (compressionmode) {                  if (copysamples == 0) {
1196                      case 1: // left channel compressed                      // skip this frame
1197                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
1198                          if (!remainingsamples && copysamples == 2048)                  }
1199                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
1200                        const unsigned char* const param_l = pSrc;
1201                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
1202                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
1203                          while (currentframeoffset) {  
1204                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
1205                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
1206                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
1207                              currentframeoffset--;  
1208                          }                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1209                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
1210                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1211                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
1212                              *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  
1213                          }                          }
1214                          while (copysamples) {                          else { // Mono
1215                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1216                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
1217                              right  -= dright;                              pDst24 += copysamples * 3;
                             *pDst = right; pDst++;  
                             copysamples--;  
1218                          }                          }
1219                          break;                      }
1220                      case 257: // both channels compressed                      else { // 16 bit
1221                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
1222                          if (!remainingsamples && copysamples == 2048)  
1223                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
1224                            if (Channels == 2) { // Stereo
1225                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
1226                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
1227                          right  = *(int16_t*)pSrc; pSrc+=2;  
1228                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
1229                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1230                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1231                              left   -= dleft;                                           skipsamples, copysamples);
1232                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
1233                          }                          }
1234                          while (copysamples) {                          else { // Mono
1235                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
1236                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1237                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
1238                          }                          }
1239                          break;                      }
1240                      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;  
1241                  }                  }
1242              }  
1243                    // reload from disk to local buffer if needed
1244                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1245                        assumedsize    = GuessSize(remainingsamples);
1246                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1247                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1248                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1249                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1250                    }
1251                } // while
1252    
1253              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
1254              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1255              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
1256          }          }
1257      }      }
1258    
1259        /** @brief Write sample wave data.
1260         *
1261         * Writes \a SampleCount number of sample points from the buffer pointed
1262         * by \a pBuffer and increments the position within the sample. Use this
1263         * method to directly write the sample data to disk, i.e. if you don't
1264         * want or cannot load the whole sample data into RAM.
1265         *
1266         * You have to Resize() the sample to the desired size and call
1267         * File::Save() <b>before</b> using Write().
1268         *
1269         * Note: there is currently no support for writing compressed samples.
1270         *
1271         * For 16 bit samples, the data in the source buffer should be
1272         * int16_t (using native endianness). For 24 bit, the buffer
1273         * should contain three bytes per sample, little-endian.
1274         *
1275         * @param pBuffer     - source buffer
1276         * @param SampleCount - number of sample points to write
1277         * @throws DLS::Exception if current sample size is too small
1278         * @throws gig::Exception if sample is compressed
1279         * @see DLS::LoadSampleData()
1280         */
1281        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1282            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1283    
1284            // if this is the first write in this sample, reset the
1285            // checksum calculator
1286            if (pCkData->GetPos() == 0) {
1287                __resetCRC(crc);
1288            }
1289            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1290            unsigned long res;
1291            if (BitDepth == 24) {
1292                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1293            } else { // 16 bit
1294                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1295                                    : pCkData->Write(pBuffer, SampleCount, 2);
1296            }
1297            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1298    
1299            // if this is the last write, update the checksum chunk in the
1300            // file
1301            if (pCkData->GetPos() == pCkData->GetSize()) {
1302                File* pFile = static_cast<File*>(GetParent());
1303                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1304            }
1305            return res;
1306        }
1307    
1308        /**
1309         * Allocates a decompression buffer for streaming (compressed) samples
1310         * with Sample::Read(). If you are using more than one streaming thread
1311         * in your application you <b>HAVE</b> to create a decompression buffer
1312         * for <b>EACH</b> of your streaming threads and provide it with the
1313         * Sample::Read() call in order to avoid race conditions and crashes.
1314         *
1315         * You should free the memory occupied by the allocated buffer(s) once
1316         * you don't need one of your streaming threads anymore by calling
1317         * DestroyDecompressionBuffer().
1318         *
1319         * @param MaxReadSize - the maximum size (in sample points) you ever
1320         *                      expect to read with one Read() call
1321         * @returns allocated decompression buffer
1322         * @see DestroyDecompressionBuffer()
1323         */
1324        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1325            buffer_t result;
1326            const double worstCaseHeaderOverhead =
1327                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1328            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1329            result.pStart            = new int8_t[result.Size];
1330            result.NullExtensionSize = 0;
1331            return result;
1332        }
1333    
1334        /**
1335         * Free decompression buffer, previously created with
1336         * CreateDecompressionBuffer().
1337         *
1338         * @param DecompressionBuffer - previously allocated decompression
1339         *                              buffer to free
1340         */
1341        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1342            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1343                delete[] (int8_t*) DecompressionBuffer.pStart;
1344                DecompressionBuffer.pStart = NULL;
1345                DecompressionBuffer.Size   = 0;
1346                DecompressionBuffer.NullExtensionSize = 0;
1347            }
1348        }
1349    
1350        /**
1351         * Returns pointer to the Group this Sample belongs to. In the .gig
1352         * format a sample always belongs to one group. If it wasn't explicitly
1353         * assigned to a certain group, it will be automatically assigned to a
1354         * default group.
1355         *
1356         * @returns Sample's Group (never NULL)
1357         */
1358        Group* Sample::GetGroup() const {
1359            return pGroup;
1360        }
1361    
1362      Sample::~Sample() {      Sample::~Sample() {
1363          Instances--;          Instances--;
1364          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
1365                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1366                InternalDecompressionBuffer.pStart = NULL;
1367                InternalDecompressionBuffer.Size   = 0;
1368            }
1369          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1370          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1371      }      }
# Line 675  namespace gig { Line 1378  namespace gig {
1378      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1379      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1380    
1381      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1382          Instances++;          Instances++;
1383    
1384          memcpy(&Crossfade, &SamplerOptions, 4);          pSample = NULL;
1385            pRegion = pParent;
1386    
1387            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1388            else memset(&Crossfade, 0, 4);
1389    
1390          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1391    
1392          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1393          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1394          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1395          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1396          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1397          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1398          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1399          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1400          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1401          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1402          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1403          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1404          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1405          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1406          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1407          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1408          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1409          EG1Controller       = static_cast<eg1_ctrl_t>(_3ewa->ReadUint8());              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1410          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1411          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1412          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1413          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1414          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1415          EG2Controller       = static_cast<eg2_ctrl_t>(_3ewa->ReadUint8());              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1416          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1417          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1418          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1419          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1420          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1421          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1422          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1423          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1424          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1425          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1426          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1427          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1428          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1429          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1430          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1431          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1432          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1433          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1434          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1435          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1436          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1437          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1438          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1439          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1440          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1441          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1442          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1443          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1444              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1445              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1446          }                  VelocityResponseDepth = velocityresponse;
1447          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1448              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1449              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1450          }              } else if (velocityresponse < 15) {
1451          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1452              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1453              VelocityResponseDepth = velocityresponse - 10;              } else {
1454                    VelocityResponseCurve = curve_type_unknown;
1455                    VelocityResponseDepth = 0;
1456                }
1457                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1458                if (releasevelocityresponse < 5) {
1459                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1460                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1461                } else if (releasevelocityresponse < 10) {
1462                    ReleaseVelocityResponseCurve = curve_type_linear;
1463                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1464                } else if (releasevelocityresponse < 15) {
1465                    ReleaseVelocityResponseCurve = curve_type_special;
1466                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1467                } else {
1468                    ReleaseVelocityResponseCurve = curve_type_unknown;
1469                    ReleaseVelocityResponseDepth = 0;
1470                }
1471                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1472                AttenuationControllerThreshold = _3ewa->ReadInt8();
1473                _3ewa->ReadInt32(); // unknown
1474                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1475                _3ewa->ReadInt16(); // unknown
1476                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1477                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1478                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1479                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1480                else                                       DimensionBypass = dim_bypass_ctrl_none;
1481                uint8_t pan = _3ewa->ReadUint8();
1482                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1483                SelfMask = _3ewa->ReadInt8() & 0x01;
1484                _3ewa->ReadInt8(); // unknown
1485                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1486                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1487                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1488                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1489                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1490                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1491                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1492                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1493                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1494                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1495                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1496                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1497                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1498                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1499                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1500                                                            : vcf_res_ctrl_none;
1501                uint16_t eg3depth = _3ewa->ReadUint16();
1502                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1503                                            : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1504                _3ewa->ReadInt16(); // unknown
1505                ChannelOffset = _3ewa->ReadUint8() / 4;
1506                uint8_t regoptions = _3ewa->ReadUint8();
1507                MSDecode           = regoptions & 0x01; // bit 0
1508                SustainDefeat      = regoptions & 0x02; // bit 1
1509                _3ewa->ReadInt16(); // unknown
1510                VelocityUpperLimit = _3ewa->ReadInt8();
1511                _3ewa->ReadInt8(); // unknown
1512                _3ewa->ReadInt16(); // unknown
1513                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1514                _3ewa->ReadInt8(); // unknown
1515                _3ewa->ReadInt8(); // unknown
1516                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1517                uint8_t vcfcutoff = _3ewa->ReadUint8();
1518                VCFEnabled = vcfcutoff & 0x80; // bit 7
1519                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1520                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1521                uint8_t vcfvelscale = _3ewa->ReadUint8();
1522                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1523                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1524                _3ewa->ReadInt8(); // unknown
1525                uint8_t vcfresonance = _3ewa->ReadUint8();
1526                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1527                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1528                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1529                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1530                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1531                uint8_t vcfvelocity = _3ewa->ReadUint8();
1532                VCFVelocityDynamicRange = vcfvelocity % 5;
1533                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1534                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1535                if (VCFType == vcf_type_lowpass) {
1536                    if (lfo3ctrl & 0x40) // bit 6
1537                        VCFType = vcf_type_lowpassturbo;
1538                }
1539                if (_3ewa->RemainingBytes() >= 8) {
1540                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1541                } else {
1542                    memset(DimensionUpperLimits, 0, 8);
1543                }
1544            } else { // '3ewa' chunk does not exist yet
1545                // use default values
1546                LFO3Frequency                   = 1.0;
1547                EG3Attack                       = 0.0;
1548                LFO1InternalDepth               = 0;
1549                LFO3InternalDepth               = 0;
1550                LFO1ControlDepth                = 0;
1551                LFO3ControlDepth                = 0;
1552                EG1Attack                       = 0.0;
1553                EG1Decay1                       = 0.005;
1554                EG1Sustain                      = 1000;
1555                EG1Release                      = 0.3;
1556                EG1Controller.type              = eg1_ctrl_t::type_none;
1557                EG1Controller.controller_number = 0;
1558                EG1ControllerInvert             = false;
1559                EG1ControllerAttackInfluence    = 0;
1560                EG1ControllerDecayInfluence     = 0;
1561                EG1ControllerReleaseInfluence   = 0;
1562                EG2Controller.type              = eg2_ctrl_t::type_none;
1563                EG2Controller.controller_number = 0;
1564                EG2ControllerInvert             = false;
1565                EG2ControllerAttackInfluence    = 0;
1566                EG2ControllerDecayInfluence     = 0;
1567                EG2ControllerReleaseInfluence   = 0;
1568                LFO1Frequency                   = 1.0;
1569                EG2Attack                       = 0.0;
1570                EG2Decay1                       = 0.005;
1571                EG2Sustain                      = 1000;
1572                EG2Release                      = 0.3;
1573                LFO2ControlDepth                = 0;
1574                LFO2Frequency                   = 1.0;
1575                LFO2InternalDepth               = 0;
1576                EG1Decay2                       = 0.0;
1577                EG1InfiniteSustain              = true;
1578                EG1PreAttack                    = 0;
1579                EG2Decay2                       = 0.0;
1580                EG2InfiniteSustain              = true;
1581                EG2PreAttack                    = 0;
1582                VelocityResponseCurve           = curve_type_nonlinear;
1583                VelocityResponseDepth           = 3;
1584                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1585                ReleaseVelocityResponseDepth    = 3;
1586                VelocityResponseCurveScaling    = 32;
1587                AttenuationControllerThreshold  = 0;
1588                SampleStartOffset               = 0;
1589                PitchTrack                      = true;
1590                DimensionBypass                 = dim_bypass_ctrl_none;
1591                Pan                             = 0;
1592                SelfMask                        = true;
1593                LFO3Controller                  = lfo3_ctrl_modwheel;
1594                LFO3Sync                        = false;
1595                InvertAttenuationController     = false;
1596                AttenuationController.type      = attenuation_ctrl_t::type_none;
1597                AttenuationController.controller_number = 0;
1598                LFO2Controller                  = lfo2_ctrl_internal;
1599                LFO2FlipPhase                   = false;
1600                LFO2Sync                        = false;
1601                LFO1Controller                  = lfo1_ctrl_internal;
1602                LFO1FlipPhase                   = false;
1603                LFO1Sync                        = false;
1604                VCFResonanceController          = vcf_res_ctrl_none;
1605                EG3Depth                        = 0;
1606                ChannelOffset                   = 0;
1607                MSDecode                        = false;
1608                SustainDefeat                   = false;
1609                VelocityUpperLimit              = 0;
1610                ReleaseTriggerDecay             = 0;
1611                EG1Hold                         = false;
1612                VCFEnabled                      = false;
1613                VCFCutoff                       = 0;
1614                VCFCutoffController             = vcf_cutoff_ctrl_none;
1615                VCFCutoffControllerInvert       = false;
1616                VCFVelocityScale                = 0;
1617                VCFResonance                    = 0;
1618                VCFResonanceDynamic             = false;
1619                VCFKeyboardTracking             = false;
1620                VCFKeyboardTrackingBreakpoint   = 0;
1621                VCFVelocityDynamicRange         = 0x04;
1622                VCFVelocityCurve                = curve_type_linear;
1623                VCFType                         = vcf_type_lowpass;
1624                memset(DimensionUpperLimits, 127, 8);
1625          }          }
1626          else {  
1627              VelocityResponseCurve = curve_type_unknown;          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1628              VelocityResponseDepth = 0;                                                       VelocityResponseDepth,
1629                                                         VelocityResponseCurveScaling);
1630    
1631            pVelocityReleaseTable = GetReleaseVelocityTable(
1632                                        ReleaseVelocityResponseCurve,
1633                                        ReleaseVelocityResponseDepth
1634                                    );
1635    
1636            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1637                                                          VCFVelocityDynamicRange,
1638                                                          VCFVelocityScale,
1639                                                          VCFCutoffController);
1640    
1641            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1642            VelocityTable = 0;
1643        }
1644    
1645        /*
1646         * Constructs a DimensionRegion by copying all parameters from
1647         * another DimensionRegion
1648         */
1649        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1650            Instances++;
1651            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1652            *this = src; // default memberwise shallow copy of all parameters
1653            pParentList = _3ewl; // restore the chunk pointer
1654    
1655            // deep copy of owned structures
1656            if (src.VelocityTable) {
1657                VelocityTable = new uint8_t[128];
1658                for (int k = 0 ; k < 128 ; k++)
1659                    VelocityTable[k] = src.VelocityTable[k];
1660          }          }
1661          uint8_t releasevelocityresponse = _3ewa->ReadUint8();          if (src.pSampleLoops) {
1662          if (releasevelocityresponse < 5) {              pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1663              ReleaseVelocityResponseCurve = curve_type_nonlinear;              for (int k = 0 ; k < src.SampleLoops ; k++)
1664              ReleaseVelocityResponseDepth = releasevelocityresponse;                  pSampleLoops[k] = src.pSampleLoops[k];
         }  
         else if (releasevelocityresponse < 10) {  
             ReleaseVelocityResponseCurve = curve_type_linear;  
             ReleaseVelocityResponseDepth = releasevelocityresponse - 5;  
         }  
         else if (releasevelocityresponse < 15) {  
             ReleaseVelocityResponseCurve = curve_type_special;  
             ReleaseVelocityResponseDepth = releasevelocityresponse - 10;  
1665          }          }
1666          else {      }
1667              ReleaseVelocityResponseCurve = curve_type_unknown;      
1668              ReleaseVelocityResponseDepth = 0;      /**
1669         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1670         * and assign it to this object.
1671         *
1672         * Note that all sample pointers referenced by @a orig are simply copied as
1673         * memory address. Thus the respective samples are shared, not duplicated!
1674         *
1675         * @param orig - original DimensionRegion object to be copied from
1676         */
1677        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1678            CopyAssign(orig, NULL);
1679        }
1680    
1681        /**
1682         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1683         * and assign it to this object.
1684         *
1685         * @param orig - original DimensionRegion object to be copied from
1686         * @param mSamples - crosslink map between the foreign file's samples and
1687         *                   this file's samples
1688         */
1689        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1690            // delete all allocated data first
1691            if (VelocityTable) delete [] VelocityTable;
1692            if (pSampleLoops) delete [] pSampleLoops;
1693            
1694            // backup parent list pointer
1695            RIFF::List* p = pParentList;
1696            
1697            gig::Sample* pOriginalSample = pSample;
1698            gig::Region* pOriginalRegion = pRegion;
1699            
1700            //NOTE: copy code copied from assignment constructor above, see comment there as well
1701            
1702            *this = *orig; // default memberwise shallow copy of all parameters
1703            pParentList = p; // restore the chunk pointer
1704            
1705            // only take the raw sample reference & parent region reference if the
1706            // two DimensionRegion objects are part of the same file
1707            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1708                pRegion = pOriginalRegion;
1709                pSample = pOriginalSample;
1710            }
1711            
1712            if (mSamples && mSamples->count(orig->pSample)) {
1713                pSample = mSamples->find(orig->pSample)->second;
1714          }          }
         VelocityResponseCurveScaling = _3ewa->ReadUint8();  
         AttenuationControlTreshold   = _3ewa->ReadInt8();  
         _3ewa->ReadInt32(); // unknown  
         SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
         _3ewa->ReadInt16(); // unknown  
         uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();  
         PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
         if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;  
         else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
         else                                       DimensionBypass = dim_bypass_ctrl_none;  
         uint8_t pan = _3ewa->ReadUint8();  
         Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;  
         SelfMask = _3ewa->ReadInt8() & 0x01;  
         _3ewa->ReadInt8(); // unknown  
         uint8_t lfo3ctrl = _3ewa->ReadUint8();  
         LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits  
         LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
         InvertAttenuationControl = lfo3ctrl & 0x80; // bit 7  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
         AttenuationControl = static_cast<attenuation_ctrl_t>(_3ewa->ReadUint8());  
         uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
         LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
         LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
         LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
         bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
         uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
         LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
         LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
         LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
         VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
                                                     : vcf_res_ctrl_none;  
         uint16_t eg3depth = _3ewa->ReadUint16();  
         EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
                                       : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */  
         _3ewa->ReadInt16(); // unknown  
         ChannelOffset = _3ewa->ReadUint8() / 4;  
         uint8_t regoptions = _3ewa->ReadUint8();  
         MSDecode           = regoptions & 0x01; // bit 0  
         SustainDefeat      = regoptions & 0x02; // bit 1  
         _3ewa->ReadInt16(); // unknown  
         VelocityUpperLimit = _3ewa->ReadInt8();  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt16(); // unknown  
         ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
1715    
1716          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          // deep copy of owned structures
1717          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          if (orig->VelocityTable) {
1718          if (pVelocityTables->count(tableKey)) { // if key exists              VelocityTable = new uint8_t[128];
1719              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              for (int k = 0 ; k < 128 ; k++)
1720                    VelocityTable[k] = orig->VelocityTable[k];
1721          }          }
1722          else {          if (orig->pSampleLoops) {
1723              pVelocityAttenuationTable = new double[128];              pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1724              switch (VelocityResponseCurve) { // calculate the new table              for (int k = 0 ; k < orig->SampleLoops ; k++)
1725                    pSampleLoops[k] = orig->pSampleLoops[k];
1726            }
1727        }
1728    
1729        /**
1730         * Updates the respective member variable and updates @c SampleAttenuation
1731         * which depends on this value.
1732         */
1733        void DimensionRegion::SetGain(int32_t gain) {
1734            DLS::Sampler::SetGain(gain);
1735            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1736        }
1737    
1738        /**
1739         * Apply dimension region settings to the respective RIFF chunks. You
1740         * have to call File::Save() to make changes persistent.
1741         *
1742         * Usually there is absolutely no need to call this method explicitly.
1743         * It will be called automatically when File::Save() was called.
1744         */
1745        void DimensionRegion::UpdateChunks() {
1746            // first update base class's chunk
1747            DLS::Sampler::UpdateChunks();
1748    
1749            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1750            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1751            pData[12] = Crossfade.in_start;
1752            pData[13] = Crossfade.in_end;
1753            pData[14] = Crossfade.out_start;
1754            pData[15] = Crossfade.out_end;
1755    
1756            // make sure '3ewa' chunk exists
1757            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1758            if (!_3ewa) {
1759                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1760                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1761                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1762            }
1763            pData = (uint8_t*) _3ewa->LoadChunkData();
1764    
1765            // update '3ewa' chunk with DimensionRegion's current settings
1766    
1767            const uint32_t chunksize = _3ewa->GetNewSize();
1768            store32(&pData[0], chunksize); // unknown, always chunk size?
1769    
1770            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1771            store32(&pData[4], lfo3freq);
1772    
1773            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1774            store32(&pData[8], eg3attack);
1775    
1776            // next 2 bytes unknown
1777    
1778            store16(&pData[14], LFO1InternalDepth);
1779    
1780            // next 2 bytes unknown
1781    
1782            store16(&pData[18], LFO3InternalDepth);
1783    
1784            // next 2 bytes unknown
1785    
1786            store16(&pData[22], LFO1ControlDepth);
1787    
1788            // next 2 bytes unknown
1789    
1790            store16(&pData[26], LFO3ControlDepth);
1791    
1792            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1793            store32(&pData[28], eg1attack);
1794    
1795            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1796            store32(&pData[32], eg1decay1);
1797    
1798            // next 2 bytes unknown
1799    
1800            store16(&pData[38], EG1Sustain);
1801    
1802            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1803            store32(&pData[40], eg1release);
1804    
1805            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1806            pData[44] = eg1ctl;
1807    
1808            const uint8_t eg1ctrloptions =
1809                (EG1ControllerInvert ? 0x01 : 0x00) |
1810                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1811                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1812                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1813            pData[45] = eg1ctrloptions;
1814    
1815            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1816            pData[46] = eg2ctl;
1817    
1818            const uint8_t eg2ctrloptions =
1819                (EG2ControllerInvert ? 0x01 : 0x00) |
1820                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1821                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1822                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1823            pData[47] = eg2ctrloptions;
1824    
1825            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1826            store32(&pData[48], lfo1freq);
1827    
1828            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1829            store32(&pData[52], eg2attack);
1830    
1831            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1832            store32(&pData[56], eg2decay1);
1833    
1834            // next 2 bytes unknown
1835    
1836            store16(&pData[62], EG2Sustain);
1837    
1838            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1839            store32(&pData[64], eg2release);
1840    
1841            // next 2 bytes unknown
1842    
1843            store16(&pData[70], LFO2ControlDepth);
1844    
1845            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1846            store32(&pData[72], lfo2freq);
1847    
1848            // next 2 bytes unknown
1849    
1850            store16(&pData[78], LFO2InternalDepth);
1851    
1852            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1853            store32(&pData[80], eg1decay2);
1854    
1855            // next 2 bytes unknown
1856    
1857            store16(&pData[86], EG1PreAttack);
1858    
1859            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1860            store32(&pData[88], eg2decay2);
1861    
1862            // next 2 bytes unknown
1863    
1864            store16(&pData[94], EG2PreAttack);
1865    
1866            {
1867                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1868                uint8_t velocityresponse = VelocityResponseDepth;
1869                switch (VelocityResponseCurve) {
1870                  case curve_type_nonlinear:                  case curve_type_nonlinear:
1871                      for (int velocity = 0; velocity < 128; velocity++) {                      break;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_NONLINEAR((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                      }  
                      break;  
1872                  case curve_type_linear:                  case curve_type_linear:
1873                      for (int velocity = 0; velocity < 128; velocity++) {                      velocityresponse += 5;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_LINEAR((double)velocity,(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
1874                      break;                      break;
1875                  case curve_type_special:                  case curve_type_special:
1876                      for (int velocity = 0; velocity < 128; velocity++) {                      velocityresponse += 10;
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_SPECIAL((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
1877                      break;                      break;
1878                  case curve_type_unknown:                  case curve_type_unknown:
1879                  default:                  default:
1880                      throw gig::Exception("Unknown transform curve type.");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1881              }              }
1882              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              pData[96] = velocityresponse;
1883          }          }
1884    
1885            {
1886                if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1887                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1888                switch (ReleaseVelocityResponseCurve) {
1889                    case curve_type_nonlinear:
1890                        break;
1891                    case curve_type_linear:
1892                        releasevelocityresponse += 5;
1893                        break;
1894                    case curve_type_special:
1895                        releasevelocityresponse += 10;
1896                        break;
1897                    case curve_type_unknown:
1898                    default:
1899                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1900                }
1901                pData[97] = releasevelocityresponse;
1902            }
1903    
1904            pData[98] = VelocityResponseCurveScaling;
1905    
1906            pData[99] = AttenuationControllerThreshold;
1907    
1908            // next 4 bytes unknown
1909    
1910            store16(&pData[104], SampleStartOffset);
1911    
1912            // next 2 bytes unknown
1913    
1914            {
1915                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1916                switch (DimensionBypass) {
1917                    case dim_bypass_ctrl_94:
1918                        pitchTrackDimensionBypass |= 0x10;
1919                        break;
1920                    case dim_bypass_ctrl_95:
1921                        pitchTrackDimensionBypass |= 0x20;
1922                        break;
1923                    case dim_bypass_ctrl_none:
1924                        //FIXME: should we set anything here?
1925                        break;
1926                    default:
1927                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1928                }
1929                pData[108] = pitchTrackDimensionBypass;
1930            }
1931    
1932            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1933            pData[109] = pan;
1934    
1935            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1936            pData[110] = selfmask;
1937    
1938            // next byte unknown
1939    
1940            {
1941                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1942                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1943                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1944                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1945                pData[112] = lfo3ctrl;
1946            }
1947    
1948            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1949            pData[113] = attenctl;
1950    
1951            {
1952                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1953                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1954                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1955                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1956                pData[114] = lfo2ctrl;
1957            }
1958    
1959            {
1960                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1961                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1962                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1963                if (VCFResonanceController != vcf_res_ctrl_none)
1964                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1965                pData[115] = lfo1ctrl;
1966            }
1967    
1968            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1969                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1970            store16(&pData[116], eg3depth);
1971    
1972            // next 2 bytes unknown
1973    
1974            const uint8_t channeloffset = ChannelOffset * 4;
1975            pData[120] = channeloffset;
1976    
1977            {
1978                uint8_t regoptions = 0;
1979                if (MSDecode)      regoptions |= 0x01; // bit 0
1980                if (SustainDefeat) regoptions |= 0x02; // bit 1
1981                pData[121] = regoptions;
1982            }
1983    
1984            // next 2 bytes unknown
1985    
1986            pData[124] = VelocityUpperLimit;
1987    
1988            // next 3 bytes unknown
1989    
1990            pData[128] = ReleaseTriggerDecay;
1991    
1992            // next 2 bytes unknown
1993    
1994            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1995            pData[131] = eg1hold;
1996    
1997            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1998                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
1999            pData[132] = vcfcutoff;
2000    
2001            pData[133] = VCFCutoffController;
2002    
2003            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2004                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
2005            pData[134] = vcfvelscale;
2006    
2007            // next byte unknown
2008    
2009            const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2010                                         (VCFResonance & 0x7f); /* lower 7 bits */
2011            pData[136] = vcfresonance;
2012    
2013            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2014                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2015            pData[137] = vcfbreakpoint;
2016    
2017            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2018                                        VCFVelocityCurve * 5;
2019            pData[138] = vcfvelocity;
2020    
2021            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2022            pData[139] = vcftype;
2023    
2024            if (chunksize >= 148) {
2025                memcpy(&pData[140], DimensionUpperLimits, 8);
2026            }
2027        }
2028    
2029        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2030            curve_type_t curveType = releaseVelocityResponseCurve;
2031            uint8_t depth = releaseVelocityResponseDepth;
2032            // this models a strange behaviour or bug in GSt: two of the
2033            // velocity response curves for release time are not used even
2034            // if specified, instead another curve is chosen.
2035            if ((curveType == curve_type_nonlinear && depth == 0) ||
2036                (curveType == curve_type_special   && depth == 4)) {
2037                curveType = curve_type_nonlinear;
2038                depth = 3;
2039            }
2040            return GetVelocityTable(curveType, depth, 0);
2041        }
2042    
2043        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2044                                                        uint8_t vcfVelocityDynamicRange,
2045                                                        uint8_t vcfVelocityScale,
2046                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2047        {
2048            curve_type_t curveType = vcfVelocityCurve;
2049            uint8_t depth = vcfVelocityDynamicRange;
2050            // even stranger GSt: two of the velocity response curves for
2051            // filter cutoff are not used, instead another special curve
2052            // is chosen. This curve is not used anywhere else.
2053            if ((curveType == curve_type_nonlinear && depth == 0) ||
2054                (curveType == curve_type_special   && depth == 4)) {
2055                curveType = curve_type_special;
2056                depth = 5;
2057            }
2058            return GetVelocityTable(curveType, depth,
2059                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2060                                        ? vcfVelocityScale : 0);
2061        }
2062    
2063        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2064        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2065        {
2066            double* table;
2067            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2068            if (pVelocityTables->count(tableKey)) { // if key exists
2069                table = (*pVelocityTables)[tableKey];
2070            }
2071            else {
2072                table = CreateVelocityTable(curveType, depth, scaling);
2073                (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2074            }
2075            return table;
2076        }
2077    
2078        Region* DimensionRegion::GetParent() const {
2079            return pRegion;
2080        }
2081    
2082        leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2083            leverage_ctrl_t decodedcontroller;
2084            switch (EncodedController) {
2085                // special controller
2086                case _lev_ctrl_none:
2087                    decodedcontroller.type = leverage_ctrl_t::type_none;
2088                    decodedcontroller.controller_number = 0;
2089                    break;
2090                case _lev_ctrl_velocity:
2091                    decodedcontroller.type = leverage_ctrl_t::type_velocity;
2092                    decodedcontroller.controller_number = 0;
2093                    break;
2094                case _lev_ctrl_channelaftertouch:
2095                    decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2096                    decodedcontroller.controller_number = 0;
2097                    break;
2098    
2099                // ordinary MIDI control change controller
2100                case _lev_ctrl_modwheel:
2101                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2102                    decodedcontroller.controller_number = 1;
2103                    break;
2104                case _lev_ctrl_breath:
2105                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2106                    decodedcontroller.controller_number = 2;
2107                    break;
2108                case _lev_ctrl_foot:
2109                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2110                    decodedcontroller.controller_number = 4;
2111                    break;
2112                case _lev_ctrl_effect1:
2113                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2114                    decodedcontroller.controller_number = 12;
2115                    break;
2116                case _lev_ctrl_effect2:
2117                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2118                    decodedcontroller.controller_number = 13;
2119                    break;
2120                case _lev_ctrl_genpurpose1:
2121                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2122                    decodedcontroller.controller_number = 16;
2123                    break;
2124                case _lev_ctrl_genpurpose2:
2125                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2126                    decodedcontroller.controller_number = 17;
2127                    break;
2128                case _lev_ctrl_genpurpose3:
2129                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2130                    decodedcontroller.controller_number = 18;
2131                    break;
2132                case _lev_ctrl_genpurpose4:
2133                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2134                    decodedcontroller.controller_number = 19;
2135                    break;
2136                case _lev_ctrl_portamentotime:
2137                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2138                    decodedcontroller.controller_number = 5;
2139                    break;
2140                case _lev_ctrl_sustainpedal:
2141                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2142                    decodedcontroller.controller_number = 64;
2143                    break;
2144                case _lev_ctrl_portamento:
2145                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2146                    decodedcontroller.controller_number = 65;
2147                    break;
2148                case _lev_ctrl_sostenutopedal:
2149                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2150                    decodedcontroller.controller_number = 66;
2151                    break;
2152                case _lev_ctrl_softpedal:
2153                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2154                    decodedcontroller.controller_number = 67;
2155                    break;
2156                case _lev_ctrl_genpurpose5:
2157                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2158                    decodedcontroller.controller_number = 80;
2159                    break;
2160                case _lev_ctrl_genpurpose6:
2161                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2162                    decodedcontroller.controller_number = 81;
2163                    break;
2164                case _lev_ctrl_genpurpose7:
2165                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2166                    decodedcontroller.controller_number = 82;
2167                    break;
2168                case _lev_ctrl_genpurpose8:
2169                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2170                    decodedcontroller.controller_number = 83;
2171                    break;
2172                case _lev_ctrl_effect1depth:
2173                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2174                    decodedcontroller.controller_number = 91;
2175                    break;
2176                case _lev_ctrl_effect2depth:
2177                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178                    decodedcontroller.controller_number = 92;
2179                    break;
2180                case _lev_ctrl_effect3depth:
2181                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2182                    decodedcontroller.controller_number = 93;
2183                    break;
2184                case _lev_ctrl_effect4depth:
2185                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186                    decodedcontroller.controller_number = 94;
2187                    break;
2188                case _lev_ctrl_effect5depth:
2189                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190                    decodedcontroller.controller_number = 95;
2191                    break;
2192    
2193                // unknown controller type
2194                default:
2195                    throw gig::Exception("Unknown leverage controller type.");
2196            }
2197            return decodedcontroller;
2198        }
2199    
2200        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2201            _lev_ctrl_t encodedcontroller;
2202            switch (DecodedController.type) {
2203                // special controller
2204                case leverage_ctrl_t::type_none:
2205                    encodedcontroller = _lev_ctrl_none;
2206                    break;
2207                case leverage_ctrl_t::type_velocity:
2208                    encodedcontroller = _lev_ctrl_velocity;
2209                    break;
2210                case leverage_ctrl_t::type_channelaftertouch:
2211                    encodedcontroller = _lev_ctrl_channelaftertouch;
2212                    break;
2213    
2214                // ordinary MIDI control change controller
2215                case leverage_ctrl_t::type_controlchange:
2216                    switch (DecodedController.controller_number) {
2217                        case 1:
2218                            encodedcontroller = _lev_ctrl_modwheel;
2219                            break;
2220                        case 2:
2221                            encodedcontroller = _lev_ctrl_breath;
2222                            break;
2223                        case 4:
2224                            encodedcontroller = _lev_ctrl_foot;
2225                            break;
2226                        case 12:
2227                            encodedcontroller = _lev_ctrl_effect1;
2228                            break;
2229                        case 13:
2230                            encodedcontroller = _lev_ctrl_effect2;
2231                            break;
2232                        case 16:
2233                            encodedcontroller = _lev_ctrl_genpurpose1;
2234                            break;
2235                        case 17:
2236                            encodedcontroller = _lev_ctrl_genpurpose2;
2237                            break;
2238                        case 18:
2239                            encodedcontroller = _lev_ctrl_genpurpose3;
2240                            break;
2241                        case 19:
2242                            encodedcontroller = _lev_ctrl_genpurpose4;
2243                            break;
2244                        case 5:
2245                            encodedcontroller = _lev_ctrl_portamentotime;
2246                            break;
2247                        case 64:
2248                            encodedcontroller = _lev_ctrl_sustainpedal;
2249                            break;
2250                        case 65:
2251                            encodedcontroller = _lev_ctrl_portamento;
2252                            break;
2253                        case 66:
2254                            encodedcontroller = _lev_ctrl_sostenutopedal;
2255                            break;
2256                        case 67:
2257                            encodedcontroller = _lev_ctrl_softpedal;
2258                            break;
2259                        case 80:
2260                            encodedcontroller = _lev_ctrl_genpurpose5;
2261                            break;
2262                        case 81:
2263                            encodedcontroller = _lev_ctrl_genpurpose6;
2264                            break;
2265                        case 82:
2266                            encodedcontroller = _lev_ctrl_genpurpose7;
2267                            break;
2268                        case 83:
2269                            encodedcontroller = _lev_ctrl_genpurpose8;
2270                            break;
2271                        case 91:
2272                            encodedcontroller = _lev_ctrl_effect1depth;
2273                            break;
2274                        case 92:
2275                            encodedcontroller = _lev_ctrl_effect2depth;
2276                            break;
2277                        case 93:
2278                            encodedcontroller = _lev_ctrl_effect3depth;
2279                            break;
2280                        case 94:
2281                            encodedcontroller = _lev_ctrl_effect4depth;
2282                            break;
2283                        case 95:
2284                            encodedcontroller = _lev_ctrl_effect5depth;
2285                            break;
2286                        default:
2287                            throw gig::Exception("leverage controller number is not supported by the gig format");
2288                    }
2289                    break;
2290                default:
2291                    throw gig::Exception("Unknown leverage controller type.");
2292            }
2293            return encodedcontroller;
2294      }      }
2295    
2296      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
# Line 885  namespace gig { Line 2306  namespace gig {
2306              delete pVelocityTables;              delete pVelocityTables;
2307              pVelocityTables = NULL;              pVelocityTables = NULL;
2308          }          }
2309            if (VelocityTable) delete[] VelocityTable;
2310      }      }
2311    
2312      /**      /**
# Line 895  namespace gig { Line 2317  namespace gig {
2317       * triggered to get the volume with which the sample should be played       * triggered to get the volume with which the sample should be played
2318       * back.       * back.
2319       *       *
2320       * @param    MIDI velocity value of the triggered key (between 0 and 127)       * @param MIDIKeyVelocity  MIDI velocity value of the triggered key (between 0 and 127)
2321       * @returns  amplitude factor (between 0.0 and 1.0)       * @returns                amplitude factor (between 0.0 and 1.0)
2322       */       */
2323      double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {      double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2324          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
2325      }      }
2326    
2327        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2328            return pVelocityReleaseTable[MIDIKeyVelocity];
2329        }
2330    
2331        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2332            return pVelocityCutoffTable[MIDIKeyVelocity];
2333        }
2334    
2335        /**
2336         * Updates the respective member variable and the lookup table / cache
2337         * that depends on this value.
2338         */
2339        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2340            pVelocityAttenuationTable =
2341                GetVelocityTable(
2342                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2343                );
2344            VelocityResponseCurve = curve;
2345        }
2346    
2347        /**
2348         * Updates the respective member variable and the lookup table / cache
2349         * that depends on this value.
2350         */
2351        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2352            pVelocityAttenuationTable =
2353                GetVelocityTable(
2354                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2355                );
2356            VelocityResponseDepth = depth;
2357        }
2358    
2359        /**
2360         * Updates the respective member variable and the lookup table / cache
2361         * that depends on this value.
2362         */
2363        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2364            pVelocityAttenuationTable =
2365                GetVelocityTable(
2366                    VelocityResponseCurve, VelocityResponseDepth, scaling
2367                );
2368            VelocityResponseCurveScaling = scaling;
2369        }
2370    
2371        /**
2372         * Updates the respective member variable and the lookup table / cache
2373         * that depends on this value.
2374         */
2375        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2376            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2377            ReleaseVelocityResponseCurve = curve;
2378        }
2379    
2380        /**
2381         * Updates the respective member variable and the lookup table / cache
2382         * that depends on this value.
2383         */
2384        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2385            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2386            ReleaseVelocityResponseDepth = depth;
2387        }
2388    
2389        /**
2390         * Updates the respective member variable and the lookup table / cache
2391         * that depends on this value.
2392         */
2393        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2394            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2395            VCFCutoffController = controller;
2396        }
2397    
2398        /**
2399         * Updates the respective member variable and the lookup table / cache
2400         * that depends on this value.
2401         */
2402        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2403            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2404            VCFVelocityCurve = curve;
2405        }
2406    
2407        /**
2408         * Updates the respective member variable and the lookup table / cache
2409         * that depends on this value.
2410         */
2411        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2412            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2413            VCFVelocityDynamicRange = range;
2414        }
2415    
2416        /**
2417         * Updates the respective member variable and the lookup table / cache
2418         * that depends on this value.
2419         */
2420        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2421            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2422            VCFVelocityScale = scaling;
2423        }
2424    
2425        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2426    
2427            // line-segment approximations of the 15 velocity curves
2428    
2429            // linear
2430            const int lin0[] = { 1, 1, 127, 127 };
2431            const int lin1[] = { 1, 21, 127, 127 };
2432            const int lin2[] = { 1, 45, 127, 127 };
2433            const int lin3[] = { 1, 74, 127, 127 };
2434            const int lin4[] = { 1, 127, 127, 127 };
2435    
2436            // non-linear
2437            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2438            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2439                                 127, 127 };
2440            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2441                                 127, 127 };
2442            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2443                                 127, 127 };
2444            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2445    
2446            // special
2447            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2448                                 113, 127, 127, 127 };
2449            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2450                                 118, 127, 127, 127 };
2451            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2452                                 85, 90, 91, 127, 127, 127 };
2453            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2454                                 117, 127, 127, 127 };
2455            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2456                                 127, 127 };
2457    
2458            // this is only used by the VCF velocity curve
2459            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2460                                 91, 127, 127, 127 };
2461    
2462            const int* const curves[] = { non0, non1, non2, non3, non4,
2463                                          lin0, lin1, lin2, lin3, lin4,
2464                                          spe0, spe1, spe2, spe3, spe4, spe5 };
2465    
2466            double* const table = new double[128];
2467    
2468            const int* curve = curves[curveType * 5 + depth];
2469            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2470    
2471            table[0] = 0;
2472            for (int x = 1 ; x < 128 ; x++) {
2473    
2474                if (x > curve[2]) curve += 2;
2475                double y = curve[1] + (x - curve[0]) *
2476                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2477                y = y / 127;
2478    
2479                // Scale up for s > 20, down for s < 20. When
2480                // down-scaling, the curve still ends at 1.0.
2481                if (s < 20 && y >= 0.5)
2482                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2483                else
2484                    y = y * (s / 20.0);
2485                if (y > 1) y = 1;
2486    
2487                table[x] = y;
2488            }
2489            return table;
2490        }
2491    
2492    
2493  // *************** Region ***************  // *************** Region ***************
# Line 910  namespace gig { Line 2496  namespace gig {
2496      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) {
2497          // Initialization          // Initialization
2498          Dimensions = 0;          Dimensions = 0;
2499          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
2500              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
2501          }          }
2502            Layers = 1;
2503            File* file = (File*) GetParent()->GetParent();
2504            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2505    
2506          // Actual Loading          // Actual Loading
2507    
2508            if (!file->GetAutoLoad()) return;
2509    
2510          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2511    
2512          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2513          if (_3lnk) {          if (_3lnk) {
2514              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
2515              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
2516                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2517                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2518                    _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2519                    _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2520                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2521                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2522                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2523                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2524                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2525                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2526                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2527                  }                  }
2528                  else { // active dimension                  else { // active dimension
2529                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2530                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2531                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2532                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2533                                                             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;  
2534                      Dimensions++;                      Dimensions++;
2535    
2536                        // if this is a layer dimension, remember the amount of layers
2537                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2538                  }                  }
2539                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2540              }              }
2541                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2542    
2543              // 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,
2544              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2545                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
2546                  if (pDimDef->dimension == dimension_velocity) {  
2547                      if (pDimensionRegions[0]->VelocityUpperLimit == 0) {              // jump to start of the wave pool indices (if not already there)
2548                          // no custom defined ranges              if (file->pVersion && file->pVersion->major == 3)
2549                          pDimDef->split_type = split_type_normal;                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2550                          pDimDef->ranges     = NULL;              else
2551                      }                  _3lnk->SetPos(44);
2552                      else { // custom defined ranges  
2553                          pDimDef->split_type = split_type_customvelocity;              // load sample references (if auto loading is enabled)
2554                          pDimDef->ranges     = new range_t[pDimDef->zones];              if (file->GetAutoLoad()) {
2555                          unsigned int bits[5] = {0,0,0,0,0};                  for (uint i = 0; i < DimensionRegions; i++) {
2556                          int previousUpperLimit = -1;                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2557                          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;  
                             }  
                         }  
                     }  
2558                  }                  }
2559                    GetSample(); // load global region sample reference
2560              }              }
2561            } else {
2562                DimensionRegions = 0;
2563                for (int i = 0 ; i < 8 ; i++) {
2564                    pDimensionDefinitions[i].dimension  = dimension_none;
2565                    pDimensionDefinitions[i].bits       = 0;
2566                    pDimensionDefinitions[i].zones      = 0;
2567                }
2568            }
2569    
2570            // make sure there is at least one dimension region
2571            if (!DimensionRegions) {
2572                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2573                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2574                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2575                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2576                DimensionRegions = 1;
2577            }
2578        }
2579    
2580        /**
2581         * Apply Region settings and all its DimensionRegions to the respective
2582         * RIFF chunks. You have to call File::Save() to make changes persistent.
2583         *
2584         * Usually there is absolutely no need to call this method explicitly.
2585         * It will be called automatically when File::Save() was called.
2586         *
2587         * @throws gig::Exception if samples cannot be dereferenced
2588         */
2589        void Region::UpdateChunks() {
2590            // in the gig format we don't care about the Region's sample reference
2591            // but we still have to provide some existing one to not corrupt the
2592            // file, so to avoid the latter we simply always assign the sample of
2593            // the first dimension region of this region
2594            pSample = pDimensionRegions[0]->pSample;
2595    
2596            // first update base class's chunks
2597            DLS::Region::UpdateChunks();
2598    
2599            // update dimension region's chunks
2600            for (int i = 0; i < DimensionRegions; i++) {
2601                pDimensionRegions[i]->UpdateChunks();
2602            }
2603    
2604            File* pFile = (File*) GetParent()->GetParent();
2605            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2606            const int iMaxDimensions =  version3 ? 8 : 5;
2607            const int iMaxDimensionRegions = version3 ? 256 : 32;
2608    
2609            // make sure '3lnk' chunk exists
2610            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2611            if (!_3lnk) {
2612                const int _3lnkChunkSize = version3 ? 1092 : 172;
2613                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2614                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2615    
2616                // move 3prg to last position
2617                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2618            }
2619    
2620              // load sample references          // update dimension definitions in '3lnk' chunk
2621              _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2622              for (uint i = 0; i < DimensionRegions; i++) {          store32(&pData[0], DimensionRegions);
2623                  uint32_t wavepoolindex = _3lnk->ReadUint32();          int shift = 0;
2624                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);          for (int i = 0; i < iMaxDimensions; i++) {
2625                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2626                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2627                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2628                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2629                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2630                // next 3 bytes unknown, always zero?
2631    
2632                shift += pDimensionDefinitions[i].bits;
2633            }
2634    
2635            // update wave pool table in '3lnk' chunk
2636            const int iWavePoolOffset = version3 ? 68 : 44;
2637            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2638                int iWaveIndex = -1;
2639                if (i < DimensionRegions) {
2640                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2641                    File::SampleList::iterator iter = pFile->pSamples->begin();
2642                    File::SampleList::iterator end  = pFile->pSamples->end();
2643                    for (int index = 0; iter != end; ++iter, ++index) {
2644                        if (*iter == pDimensionRegions[i]->pSample) {
2645                            iWaveIndex = index;
2646                            break;
2647                        }
2648                    }
2649              }              }
2650                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2651          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2652      }      }
2653    
2654      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 995  namespace gig { Line 2658  namespace gig {
2658              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2659              while (_3ewl) {              while (_3ewl) {
2660                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2661                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2662                      dimensionRegionNr++;                      dimensionRegionNr++;
2663                  }                  }
2664                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 1004  namespace gig { Line 2667  namespace gig {
2667          }          }
2668      }      }
2669    
2670      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2671          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
2672              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
2673            // update Region key table for fast lookup
2674            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2675        }
2676    
2677        void Region::UpdateVelocityTable() {
2678            // get velocity dimension's index
2679            int veldim = -1;
2680            for (int i = 0 ; i < Dimensions ; i++) {
2681                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2682                    veldim = i;
2683                    break;
2684                }
2685            }
2686            if (veldim == -1) return;
2687    
2688            int step = 1;
2689            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2690            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2691            int end = step * pDimensionDefinitions[veldim].zones;
2692    
2693            // loop through all dimension regions for all dimensions except the velocity dimension
2694            int dim[8] = { 0 };
2695            for (int i = 0 ; i < DimensionRegions ; i++) {
2696    
2697                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2698                    pDimensionRegions[i]->VelocityUpperLimit) {
2699                    // create the velocity table
2700                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2701                    if (!table) {
2702                        table = new uint8_t[128];
2703                        pDimensionRegions[i]->VelocityTable = table;
2704                    }
2705                    int tableidx = 0;
2706                    int velocityZone = 0;
2707                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2708                        for (int k = i ; k < end ; k += step) {
2709                            DimensionRegion *d = pDimensionRegions[k];
2710                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2711                            velocityZone++;
2712                        }
2713                    } else { // gig2
2714                        for (int k = i ; k < end ; k += step) {
2715                            DimensionRegion *d = pDimensionRegions[k];
2716                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2717                            velocityZone++;
2718                        }
2719                    }
2720                } else {
2721                    if (pDimensionRegions[i]->VelocityTable) {
2722                        delete[] pDimensionRegions[i]->VelocityTable;
2723                        pDimensionRegions[i]->VelocityTable = 0;
2724                    }
2725                }
2726    
2727                int j;
2728                int shift = 0;
2729                for (j = 0 ; j < Dimensions ; j++) {
2730                    if (j == veldim) i += skipveldim; // skip velocity dimension
2731                    else {
2732                        dim[j]++;
2733                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2734                        else {
2735                            // skip unused dimension regions
2736                            dim[j] = 0;
2737                            i += ((1 << pDimensionDefinitions[j].bits) -
2738                                  pDimensionDefinitions[j].zones) << shift;
2739                        }
2740                    }
2741                    shift += pDimensionDefinitions[j].bits;
2742                }
2743                if (j == Dimensions) break;
2744            }
2745        }
2746    
2747        /** @brief Einstein would have dreamed of it - create a new dimension.
2748         *
2749         * Creates a new dimension with the dimension definition given by
2750         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2751         * There is a hard limit of dimensions and total amount of "bits" all
2752         * dimensions can have. This limit is dependant to what gig file format
2753         * version this file refers to. The gig v2 (and lower) format has a
2754         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2755         * format has a limit of 8.
2756         *
2757         * @param pDimDef - defintion of the new dimension
2758         * @throws gig::Exception if dimension of the same type exists already
2759         * @throws gig::Exception if amount of dimensions or total amount of
2760         *                        dimension bits limit is violated
2761         */
2762        void Region::AddDimension(dimension_def_t* pDimDef) {
2763            // check if max. amount of dimensions reached
2764            File* file = (File*) GetParent()->GetParent();
2765            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2766            if (Dimensions >= iMaxDimensions)
2767                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2768            // check if max. amount of dimension bits reached
2769            int iCurrentBits = 0;
2770            for (int i = 0; i < Dimensions; i++)
2771                iCurrentBits += pDimensionDefinitions[i].bits;
2772            if (iCurrentBits >= iMaxDimensions)
2773                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2774            const int iNewBits = iCurrentBits + pDimDef->bits;
2775            if (iNewBits > iMaxDimensions)
2776                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2777            // check if there's already a dimensions of the same type
2778            for (int i = 0; i < Dimensions; i++)
2779                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2780                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2781    
2782            // pos is where the new dimension should be placed, normally
2783            // last in list, except for the samplechannel dimension which
2784            // has to be first in list
2785            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2786            int bitpos = 0;
2787            for (int i = 0 ; i < pos ; i++)
2788                bitpos += pDimensionDefinitions[i].bits;
2789    
2790            // make room for the new dimension
2791            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2792            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2793                for (int j = Dimensions ; j > pos ; j--) {
2794                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2795                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2796                }
2797            }
2798    
2799            // assign definition of new dimension
2800            pDimensionDefinitions[pos] = *pDimDef;
2801    
2802            // auto correct certain dimension definition fields (where possible)
2803            pDimensionDefinitions[pos].split_type  =
2804                __resolveSplitType(pDimensionDefinitions[pos].dimension);
2805            pDimensionDefinitions[pos].zone_size =
2806                __resolveZoneSize(pDimensionDefinitions[pos]);
2807    
2808            // create new dimension region(s) for this new dimension, and make
2809            // sure that the dimension regions are placed correctly in both the
2810            // RIFF list and the pDimensionRegions array
2811            RIFF::Chunk* moveTo = NULL;
2812            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2813            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2814                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2815                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2816                }
2817                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2818                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2819                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2820                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2821                        // create a new dimension region and copy all parameter values from
2822                        // an existing dimension region
2823                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2824                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2825    
2826                        DimensionRegions++;
2827                    }
2828                }
2829                moveTo = pDimensionRegions[i]->pParentList;
2830            }
2831    
2832            // initialize the upper limits for this dimension
2833            int mask = (1 << bitpos) - 1;
2834            for (int z = 0 ; z < pDimDef->zones ; z++) {
2835                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2836                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2837                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2838                                      (z << bitpos) |
2839                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2840                }
2841            }
2842    
2843            Dimensions++;
2844    
2845            // if this is a layer dimension, update 'Layers' attribute
2846            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2847    
2848            UpdateVelocityTable();
2849        }
2850    
2851        /** @brief Delete an existing dimension.
2852         *
2853         * Deletes the dimension given by \a pDimDef and deletes all respective
2854         * dimension regions, that is all dimension regions where the dimension's
2855         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2856         * for example this would delete all dimension regions for the case(s)
2857         * where the sustain pedal is pressed down.
2858         *
2859         * @param pDimDef - dimension to delete
2860         * @throws gig::Exception if given dimension cannot be found
2861         */
2862        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2863            // get dimension's index
2864            int iDimensionNr = -1;
2865            for (int i = 0; i < Dimensions; i++) {
2866                if (&pDimensionDefinitions[i] == pDimDef) {
2867                    iDimensionNr = i;
2868                    break;
2869                }
2870            }
2871            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2872    
2873            // get amount of bits below the dimension to delete
2874            int iLowerBits = 0;
2875            for (int i = 0; i < iDimensionNr; i++)
2876                iLowerBits += pDimensionDefinitions[i].bits;
2877    
2878            // get amount ot bits above the dimension to delete
2879            int iUpperBits = 0;
2880            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2881                iUpperBits += pDimensionDefinitions[i].bits;
2882    
2883            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2884    
2885            // delete dimension regions which belong to the given dimension
2886            // (that is where the dimension's bit > 0)
2887            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2888                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2889                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2890                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2891                                        iObsoleteBit << iLowerBits |
2892                                        iLowerBit;
2893    
2894                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2895                        delete pDimensionRegions[iToDelete];
2896                        pDimensionRegions[iToDelete] = NULL;
2897                        DimensionRegions--;
2898                    }
2899                }
2900            }
2901    
2902            // defrag pDimensionRegions array
2903            // (that is remove the NULL spaces within the pDimensionRegions array)
2904            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2905                if (!pDimensionRegions[iTo]) {
2906                    if (iFrom <= iTo) iFrom = iTo + 1;
2907                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2908                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2909                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2910                        pDimensionRegions[iFrom] = NULL;
2911                    }
2912                }
2913            }
2914    
2915            // remove the this dimension from the upper limits arrays
2916            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2917                DimensionRegion* d = pDimensionRegions[j];
2918                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2919                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2920                }
2921                d->DimensionUpperLimits[Dimensions - 1] = 127;
2922            }
2923    
2924            // 'remove' dimension definition
2925            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2926                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2927          }          }
2928          for (int i = 0; i < 32; i++) {          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2929            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2930            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2931    
2932            Dimensions--;
2933    
2934            // if this was a layer dimension, update 'Layers' attribute
2935            if (pDimDef->dimension == dimension_layer) Layers = 1;
2936        }
2937    
2938        Region::~Region() {
2939            for (int i = 0; i < 256; i++) {
2940              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2941          }          }
2942      }      }
# Line 1026  namespace gig { Line 2954  namespace gig {
2954       * 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,
2955       * etc.).       * etc.).
2956       *       *
2957       * @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  
2958       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
2959       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
2960       * @see             Dimensions       * @see             Dimensions
2961       */       */
2962      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2963          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits;
2964            int veldim = -1;
2965            int velbitpos;
2966            int bitpos = 0;
2967            int dimregidx = 0;
2968          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2969              switch (pDimensionDefinitions[i].split_type) {              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2970                  case split_type_normal:                  // the velocity dimension must be handled after the other dimensions
2971                      bits[i] /= pDimensionDefinitions[i].zone_size;                  veldim = i;
2972                      break;                  velbitpos = bitpos;
2973                  case split_type_customvelocity:              } else {
2974                      bits[i] = VelocityTable[bits[i]];                  switch (pDimensionDefinitions[i].split_type) {
2975                      break;                      case split_type_normal:
2976                  // else the value is already the sought dimension bit number                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2977                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2978                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2979                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2980                                }
2981                            } else {
2982                                // gig2: evenly sized zones
2983                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2984                            }
2985                            break;
2986                        case split_type_bit: // the value is already the sought dimension bit number
2987                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2988                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2989                            break;
2990                    }
2991                    dimregidx |= bits << bitpos;
2992              }              }
2993                bitpos += pDimensionDefinitions[i].bits;
2994            }
2995            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2996            if (veldim != -1) {
2997                // (dimreg is now the dimension region for the lowest velocity)
2998                if (dimreg->VelocityTable) // custom defined zone ranges
2999                    bits = dimreg->VelocityTable[DimValues[veldim]];
3000                else // normal split type
3001                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
3002    
3003                dimregidx |= bits << velbitpos;
3004                dimreg = pDimensionRegions[dimregidx];
3005          }          }
3006          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          return dimreg;
3007      }      }
3008    
3009      /**      /**
# Line 1056  namespace gig { Line 3011  namespace gig {
3011       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
3012       * instead of calling this method directly!       * instead of calling this method directly!
3013       *       *
3014       * @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  
3015       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
3016       *                 bit numbers       *                 bit numbers
3017       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
3018       */       */
3019      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]) {
3020          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3021                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
3022                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
3023                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
3024                                                      << pDimensionDefinitions[2].bits | DimBits[2])
3025                                                      << pDimensionDefinitions[1].bits | DimBits[1])
3026                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
3027      }      }
3028    
3029      /**      /**
# Line 1086  namespace gig { Line 3040  namespace gig {
3040          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3041      }      }
3042    
3043      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3044            if ((int32_t)WavePoolTableIndex == -1) return NULL;
3045          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3046            if (!file->pWavePoolTable) return NULL;
3047          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3048          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3049            Sample* sample = file->GetFirstSample(pProgress);
3050          while (sample) {          while (sample) {
3051              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
3052                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3053              sample = file->GetNextSample();              sample = file->GetNextSample();
3054          }          }
3055          return NULL;          return NULL;
3056      }      }
3057        
3058        /**
3059         * Make a (semi) deep copy of the Region object given by @a orig
3060         * and assign it to this object.
3061         *
3062         * Note that all sample pointers referenced by @a orig are simply copied as
3063         * memory address. Thus the respective samples are shared, not duplicated!
3064         *
3065         * @param orig - original Region object to be copied from
3066         */
3067        void Region::CopyAssign(const Region* orig) {
3068            CopyAssign(orig, NULL);
3069        }
3070        
3071        /**
3072         * Make a (semi) deep copy of the Region object given by @a orig and
3073         * assign it to this object
3074         *
3075         * @param mSamples - crosslink map between the foreign file's samples and
3076         *                   this file's samples
3077         */
3078        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3079            // handle base classes
3080            DLS::Region::CopyAssign(orig);
3081            
3082            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3083                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3084            }
3085            
3086            // handle own member variables
3087            for (int i = Dimensions - 1; i >= 0; --i) {
3088                DeleteDimension(&pDimensionDefinitions[i]);
3089            }
3090            Layers = 0; // just to be sure
3091            for (int i = 0; i < orig->Dimensions; i++) {
3092                // we need to copy the dim definition here, to avoid the compiler
3093                // complaining about const-ness issue
3094                dimension_def_t def = orig->pDimensionDefinitions[i];
3095                AddDimension(&def);
3096            }
3097            for (int i = 0; i < 256; i++) {
3098                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3099                    pDimensionRegions[i]->CopyAssign(
3100                        orig->pDimensionRegions[i],
3101                        mSamples
3102                    );
3103                }
3104            }
3105            Layers = orig->Layers;
3106        }
3107    
3108    
3109    // *************** MidiRule ***************
3110    // *
3111    
3112        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3113            _3ewg->SetPos(36);
3114            Triggers = _3ewg->ReadUint8();
3115            _3ewg->SetPos(40);
3116            ControllerNumber = _3ewg->ReadUint8();
3117            _3ewg->SetPos(46);
3118            for (int i = 0 ; i < Triggers ; i++) {
3119                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3120                pTriggers[i].Descending = _3ewg->ReadUint8();
3121                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3122                pTriggers[i].Key = _3ewg->ReadUint8();
3123                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3124                pTriggers[i].Velocity = _3ewg->ReadUint8();
3125                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3126                _3ewg->ReadUint8();
3127            }
3128        }
3129    
3130        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3131            ControllerNumber(0),
3132            Triggers(0) {
3133        }
3134    
3135        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3136            pData[32] = 4;
3137            pData[33] = 16;
3138            pData[36] = Triggers;
3139            pData[40] = ControllerNumber;
3140            for (int i = 0 ; i < Triggers ; i++) {
3141                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3142                pData[47 + i * 8] = pTriggers[i].Descending;
3143                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3144                pData[49 + i * 8] = pTriggers[i].Key;
3145                pData[50 + i * 8] = pTriggers[i].NoteOff;
3146                pData[51 + i * 8] = pTriggers[i].Velocity;
3147                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3148            }
3149        }
3150    
3151        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3152            _3ewg->SetPos(36);
3153            LegatoSamples = _3ewg->ReadUint8(); // always 12
3154            _3ewg->SetPos(40);
3155            BypassUseController = _3ewg->ReadUint8();
3156            BypassKey = _3ewg->ReadUint8();
3157            BypassController = _3ewg->ReadUint8();
3158            ThresholdTime = _3ewg->ReadUint16();
3159            _3ewg->ReadInt16();
3160            ReleaseTime = _3ewg->ReadUint16();
3161            _3ewg->ReadInt16();
3162            KeyRange.low = _3ewg->ReadUint8();
3163            KeyRange.high = _3ewg->ReadUint8();
3164            _3ewg->SetPos(64);
3165            ReleaseTriggerKey = _3ewg->ReadUint8();
3166            AltSustain1Key = _3ewg->ReadUint8();
3167            AltSustain2Key = _3ewg->ReadUint8();
3168        }
3169    
3170        MidiRuleLegato::MidiRuleLegato() :
3171            LegatoSamples(12),
3172            BypassUseController(false),
3173            BypassKey(0),
3174            BypassController(1),
3175            ThresholdTime(20),
3176            ReleaseTime(20),
3177            ReleaseTriggerKey(0),
3178            AltSustain1Key(0),
3179            AltSustain2Key(0)
3180        {
3181            KeyRange.low = KeyRange.high = 0;
3182        }
3183    
3184        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3185            pData[32] = 0;
3186            pData[33] = 16;
3187            pData[36] = LegatoSamples;
3188            pData[40] = BypassUseController;
3189            pData[41] = BypassKey;
3190            pData[42] = BypassController;
3191            store16(&pData[43], ThresholdTime);
3192            store16(&pData[47], ReleaseTime);
3193            pData[51] = KeyRange.low;
3194            pData[52] = KeyRange.high;
3195            pData[64] = ReleaseTriggerKey;
3196            pData[65] = AltSustain1Key;
3197            pData[66] = AltSustain2Key;
3198        }
3199    
3200        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3201            _3ewg->SetPos(36);
3202            Articulations = _3ewg->ReadUint8();
3203            int flags = _3ewg->ReadUint8();
3204            Polyphonic = flags & 8;
3205            Chained = flags & 4;
3206            Selector = (flags & 2) ? selector_controller :
3207                (flags & 1) ? selector_key_switch : selector_none;
3208            Patterns = _3ewg->ReadUint8();
3209            _3ewg->ReadUint8(); // chosen row
3210            _3ewg->ReadUint8(); // unknown
3211            _3ewg->ReadUint8(); // unknown
3212            _3ewg->ReadUint8(); // unknown
3213            KeySwitchRange.low = _3ewg->ReadUint8();
3214            KeySwitchRange.high = _3ewg->ReadUint8();
3215            Controller = _3ewg->ReadUint8();
3216            PlayRange.low = _3ewg->ReadUint8();
3217            PlayRange.high = _3ewg->ReadUint8();
3218    
3219            int n = std::min(int(Articulations), 32);
3220            for (int i = 0 ; i < n ; i++) {
3221                _3ewg->ReadString(pArticulations[i], 32);
3222            }
3223            _3ewg->SetPos(1072);
3224            n = std::min(int(Patterns), 32);
3225            for (int i = 0 ; i < n ; i++) {
3226                _3ewg->ReadString(pPatterns[i].Name, 16);
3227                pPatterns[i].Size = _3ewg->ReadUint8();
3228                _3ewg->Read(&pPatterns[i][0], 1, 32);
3229            }
3230        }
3231    
3232        MidiRuleAlternator::MidiRuleAlternator() :
3233            Articulations(0),
3234            Patterns(0),
3235            Selector(selector_none),
3236            Controller(0),
3237            Polyphonic(false),
3238            Chained(false)
3239        {
3240            PlayRange.low = PlayRange.high = 0;
3241            KeySwitchRange.low = KeySwitchRange.high = 0;
3242        }
3243    
3244        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3245            pData[32] = 3;
3246            pData[33] = 16;
3247            pData[36] = Articulations;
3248            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3249                (Selector == selector_controller ? 2 :
3250                 (Selector == selector_key_switch ? 1 : 0));
3251            pData[38] = Patterns;
3252    
3253            pData[43] = KeySwitchRange.low;
3254            pData[44] = KeySwitchRange.high;
3255            pData[45] = Controller;
3256            pData[46] = PlayRange.low;
3257            pData[47] = PlayRange.high;
3258    
3259            char* str = reinterpret_cast<char*>(pData);
3260            int pos = 48;
3261            int n = std::min(int(Articulations), 32);
3262            for (int i = 0 ; i < n ; i++, pos += 32) {
3263                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3264            }
3265    
3266            pos = 1072;
3267            n = std::min(int(Patterns), 32);
3268            for (int i = 0 ; i < n ; i++, pos += 49) {
3269                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3270                pData[pos + 16] = pPatterns[i].Size;
3271                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3272            }
3273        }
3274    
3275  // *************** Instrument ***************  // *************** Instrument ***************
3276  // *  // *
3277    
3278      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) {
3279            static const DLS::Info::string_length_t fixedStringLengths[] = {
3280                { CHUNK_ID_INAM, 64 },
3281                { CHUNK_ID_ISFT, 12 },
3282                { 0, 0 }
3283            };
3284            pInfo->SetFixedStringLengths(fixedStringLengths);
3285    
3286          // Initialization          // Initialization
3287          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3288          RegionIndex = -1;          EffectSend = 0;
3289            Attenuation = 0;
3290            FineTune = 0;
3291            PitchbendRange = 0;
3292            PianoReleaseMode = false;
3293            DimensionKeyRange.low = 0;
3294            DimensionKeyRange.high = 0;
3295            pMidiRules = new MidiRule*[3];
3296            pMidiRules[0] = NULL;
3297    
3298          // Loading          // Loading
3299          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1120  namespace gig { Line 3308  namespace gig {
3308                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3309                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3310                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3311    
3312                    if (_3ewg->GetSize() > 32) {
3313                        // read MIDI rules
3314                        int i = 0;
3315                        _3ewg->SetPos(32);
3316                        uint8_t id1 = _3ewg->ReadUint8();
3317                        uint8_t id2 = _3ewg->ReadUint8();
3318    
3319                        if (id2 == 16) {
3320                            if (id1 == 4) {
3321                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3322                            } else if (id1 == 0) {
3323                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3324                            } else if (id1 == 3) {
3325                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3326                            } else {
3327                                pMidiRules[i++] = new MidiRuleUnknown;
3328                            }
3329                        }
3330                        else if (id1 != 0 || id2 != 0) {
3331                            pMidiRules[i++] = new MidiRuleUnknown;
3332                        }
3333                        //TODO: all the other types of rules
3334    
3335                        pMidiRules[i] = NULL;
3336                    }
3337              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
3338          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
3339    
3340          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          if (pFile->GetAutoLoad()) {
3341          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");              if (!pRegions) pRegions = new RegionList;
3342          pRegions = new Region*[Regions];              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3343          RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3344          unsigned int iRegion = 0;                  RIFF::List* rgn = lrgn->GetFirstSubList();
3345          while (rgn) {                  while (rgn) {
3346              if (rgn->GetListType() == LIST_TYPE_RGN) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3347                  pRegions[iRegion] = new Region(this, rgn);                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3348                  iRegion++;                          pRegions->push_back(new Region(this, rgn));
3349              }                      }
3350              rgn = lrgn->GetNextSubList();                      rgn = lrgn->GetNextSubList();
3351          }                  }
3352                    // Creating Region Key Table for fast lookup
3353          // Creating Region Key Table for fast lookup                  UpdateRegionKeyTable();
3354          for (uint iReg = 0; iReg < Regions; iReg++) {              }
3355              for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {          }
3356                  RegionKeyTable[iKey] = pRegions[iReg];  
3357            __notify_progress(pProgress, 1.0f); // notify done
3358        }
3359    
3360        void Instrument::UpdateRegionKeyTable() {
3361            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3362            RegionList::iterator iter = pRegions->begin();
3363            RegionList::iterator end  = pRegions->end();
3364            for (; iter != end; ++iter) {
3365                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
3366                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
3367                    RegionKeyTable[iKey] = pRegion;
3368              }              }
3369          }          }
3370      }      }
3371    
3372      Instrument::~Instrument() {      Instrument::~Instrument() {
3373          for (uint i = 0; i < Regions; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
3374              if (pRegions) {              delete pMidiRules[i];
3375                  if (pRegions[i]) delete (pRegions[i]);          }
3376            delete[] pMidiRules;
3377        }
3378    
3379        /**
3380         * Apply Instrument with all its Regions to the respective RIFF chunks.
3381         * You have to call File::Save() to make changes persistent.
3382         *
3383         * Usually there is absolutely no need to call this method explicitly.
3384         * It will be called automatically when File::Save() was called.
3385         *
3386         * @throws gig::Exception if samples cannot be dereferenced
3387         */
3388        void Instrument::UpdateChunks() {
3389            // first update base classes' chunks
3390            DLS::Instrument::UpdateChunks();
3391    
3392            // update Regions' chunks
3393            {
3394                RegionList::iterator iter = pRegions->begin();
3395                RegionList::iterator end  = pRegions->end();
3396                for (; iter != end; ++iter)
3397                    (*iter)->UpdateChunks();
3398            }
3399    
3400            // make sure 'lart' RIFF list chunk exists
3401            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
3402            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3403            // make sure '3ewg' RIFF chunk exists
3404            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3405            if (!_3ewg)  {
3406                File* pFile = (File*) GetParent();
3407    
3408                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3409                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3410                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3411                memset(_3ewg->LoadChunkData(), 0, size);
3412            }
3413            // update '3ewg' RIFF chunk
3414            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3415            store16(&pData[0], EffectSend);
3416            store32(&pData[2], Attenuation);
3417            store16(&pData[6], FineTune);
3418            store16(&pData[8], PitchbendRange);
3419            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3420                                        DimensionKeyRange.low << 1;
3421            pData[10] = dimkeystart;
3422            pData[11] = DimensionKeyRange.high;
3423    
3424            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3425                pData[32] = 0;
3426                pData[33] = 0;
3427            } else {
3428                for (int i = 0 ; pMidiRules[i] ; i++) {
3429                    pMidiRules[i]->UpdateChunks(pData);
3430              }              }
             delete[] pRegions;  
3431          }          }
3432      }      }
3433    
# Line 1163  namespace gig { Line 3439  namespace gig {
3439       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3440       */       */
3441      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3442          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3443          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3444    
3445          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
3446              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
3447                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1180  namespace gig { Line 3457  namespace gig {
3457       * @see      GetNextRegion()       * @see      GetNextRegion()
3458       */       */
3459      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
3460          if (!Regions) return NULL;          if (!pRegions) return NULL;
3461          RegionIndex = 1;          RegionsIterator = pRegions->begin();
3462          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3463      }      }
3464    
3465      /**      /**
# Line 1194  namespace gig { Line 3471  namespace gig {
3471       * @see      GetFirstRegion()       * @see      GetFirstRegion()
3472       */       */
3473      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
3474          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (!pRegions) return NULL;
3475          return pRegions[RegionIndex++];          RegionsIterator++;
3476            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3477        }
3478    
3479        Region* Instrument::AddRegion() {
3480            // create new Region object (and its RIFF chunks)
3481            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3482            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3483            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3484            Region* pNewRegion = new Region(this, rgn);
3485            pRegions->push_back(pNewRegion);
3486            Regions = pRegions->size();
3487            // update Region key table for fast lookup
3488            UpdateRegionKeyTable();
3489            // done
3490            return pNewRegion;
3491        }
3492    
3493        void Instrument::DeleteRegion(Region* pRegion) {
3494            if (!pRegions) return;
3495            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
3496            // update Region key table for fast lookup
3497            UpdateRegionKeyTable();
3498        }
3499    
3500        /**
3501         * Returns a MIDI rule of the instrument.
3502         *
3503         * The list of MIDI rules, at least in gig v3, always contains at
3504         * most two rules. The second rule can only be the DEF filter
3505         * (which currently isn't supported by libgig).
3506         *
3507         * @param i - MIDI rule number
3508         * @returns   pointer address to MIDI rule number i or NULL if there is none
3509         */
3510        MidiRule* Instrument::GetMidiRule(int i) {
3511            return pMidiRules[i];
3512        }
3513    
3514        /**
3515         * Adds the "controller trigger" MIDI rule to the instrument.
3516         *
3517         * @returns the new MIDI rule
3518         */
3519        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3520            delete pMidiRules[0];
3521            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3522            pMidiRules[0] = r;
3523            pMidiRules[1] = 0;
3524            return r;
3525        }
3526    
3527        /**
3528         * Adds the legato MIDI rule to the instrument.
3529         *
3530         * @returns the new MIDI rule
3531         */
3532        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3533            delete pMidiRules[0];
3534            MidiRuleLegato* r = new MidiRuleLegato;
3535            pMidiRules[0] = r;
3536            pMidiRules[1] = 0;
3537            return r;
3538        }
3539    
3540        /**
3541         * Adds the alternator MIDI rule to the instrument.
3542         *
3543         * @returns the new MIDI rule
3544         */
3545        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3546            delete pMidiRules[0];
3547            MidiRuleAlternator* r = new MidiRuleAlternator;
3548            pMidiRules[0] = r;
3549            pMidiRules[1] = 0;
3550            return r;
3551        }
3552    
3553        /**
3554         * Deletes a MIDI rule from the instrument.
3555         *
3556         * @param i - MIDI rule number
3557         */
3558        void Instrument::DeleteMidiRule(int i) {
3559            delete pMidiRules[i];
3560            pMidiRules[i] = 0;
3561        }
3562    
3563        /**
3564         * Make a (semi) deep copy of the Instrument object given by @a orig
3565         * and assign it to this object.
3566         *
3567         * Note that all sample pointers referenced by @a orig are simply copied as
3568         * memory address. Thus the respective samples are shared, not duplicated!
3569         *
3570         * @param orig - original Instrument object to be copied from
3571         */
3572        void Instrument::CopyAssign(const Instrument* orig) {
3573            CopyAssign(orig, NULL);
3574        }
3575            
3576        /**
3577         * Make a (semi) deep copy of the Instrument object given by @a orig
3578         * and assign it to this object.
3579         *
3580         * @param orig - original Instrument object to be copied from
3581         * @param mSamples - crosslink map between the foreign file's samples and
3582         *                   this file's samples
3583         */
3584        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3585            // handle base class
3586            // (without copying DLS region stuff)
3587            DLS::Instrument::CopyAssignCore(orig);
3588            
3589            // handle own member variables
3590            Attenuation = orig->Attenuation;
3591            EffectSend = orig->EffectSend;
3592            FineTune = orig->FineTune;
3593            PitchbendRange = orig->PitchbendRange;
3594            PianoReleaseMode = orig->PianoReleaseMode;
3595            DimensionKeyRange = orig->DimensionKeyRange;
3596            
3597            // free old midi rules
3598            for (int i = 0 ; pMidiRules[i] ; i++) {
3599                delete pMidiRules[i];
3600            }
3601            //TODO: MIDI rule copying
3602            pMidiRules[0] = NULL;
3603            
3604            // delete all old regions
3605            while (Regions) DeleteRegion(GetFirstRegion());
3606            // create new regions and copy them from original
3607            {
3608                RegionList::const_iterator it = orig->pRegions->begin();
3609                for (int i = 0; i < orig->Regions; ++i, ++it) {
3610                    Region* dstRgn = AddRegion();
3611                    //NOTE: Region does semi-deep copy !
3612                    dstRgn->CopyAssign(
3613                        static_cast<gig::Region*>(*it),
3614                        mSamples
3615                    );
3616                }
3617            }
3618    
3619            UpdateRegionKeyTable();
3620        }
3621    
3622    
3623    // *************** Group ***************
3624    // *
3625    
3626        /** @brief Constructor.
3627         *
3628         * @param file   - pointer to the gig::File object
3629         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
3630         *                 NULL if this is a new Group
3631         */
3632        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
3633            pFile      = file;
3634            pNameChunk = ck3gnm;
3635            ::LoadString(pNameChunk, Name);
3636        }
3637    
3638        Group::~Group() {
3639            // remove the chunk associated with this group (if any)
3640            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3641        }
3642    
3643        /** @brief Update chunks with current group settings.
3644         *
3645         * Apply current Group field values to the respective chunks. You have
3646         * to call File::Save() to make changes persistent.
3647         *
3648         * Usually there is absolutely no need to call this method explicitly.
3649         * It will be called automatically when File::Save() was called.
3650         */
3651        void Group::UpdateChunks() {
3652            // make sure <3gri> and <3gnl> list chunks exist
3653            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3654            if (!_3gri) {
3655                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3656                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3657            }
3658            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3659            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3660    
3661            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3662                // v3 has a fixed list of 128 strings, find a free one
3663                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3664                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3665                        pNameChunk = ck;
3666                        break;
3667                    }
3668                }
3669            }
3670    
3671            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3672            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3673        }
3674    
3675        /**
3676         * Returns the first Sample of this Group. You have to call this method
3677         * once before you use GetNextSample().
3678         *
3679         * <b>Notice:</b> this method might block for a long time, in case the
3680         * samples of this .gig file were not scanned yet
3681         *
3682         * @returns  pointer address to first Sample or NULL if there is none
3683         *           applied to this Group
3684         * @see      GetNextSample()
3685         */
3686        Sample* Group::GetFirstSample() {
3687            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3688            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
3689                if (pSample->GetGroup() == this) return pSample;
3690            }
3691            return NULL;
3692        }
3693    
3694        /**
3695         * Returns the next Sample of the Group. You have to call
3696         * GetFirstSample() once before you can use this method. By calling this
3697         * method multiple times it iterates through the Samples assigned to
3698         * this Group.
3699         *
3700         * @returns  pointer address to the next Sample of this Group or NULL if
3701         *           end reached
3702         * @see      GetFirstSample()
3703         */
3704        Sample* Group::GetNextSample() {
3705            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3706            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
3707                if (pSample->GetGroup() == this) return pSample;
3708            }
3709            return NULL;
3710        }
3711    
3712        /**
3713         * Move Sample given by \a pSample from another Group to this Group.
3714         */
3715        void Group::AddSample(Sample* pSample) {
3716            pSample->pGroup = this;
3717        }
3718    
3719        /**
3720         * Move all members of this group to another group (preferably the 1st
3721         * one except this). This method is called explicitly by
3722         * File::DeleteGroup() thus when a Group was deleted. This code was
3723         * intentionally not placed in the destructor!
3724         */
3725        void Group::MoveAll() {
3726            // get "that" other group first
3727            Group* pOtherGroup = NULL;
3728            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
3729                if (pOtherGroup != this) break;
3730            }
3731            if (!pOtherGroup) throw Exception(
3732                "Could not move samples to another group, since there is no "
3733                "other Group. This is a bug, report it!"
3734            );
3735            // now move all samples of this group to the other group
3736            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3737                pOtherGroup->AddSample(pSample);
3738            }
3739      }      }
3740    
3741    
# Line 1203  namespace gig { Line 3743  namespace gig {
3743  // *************** File ***************  // *************** File ***************
3744  // *  // *
3745    
3746        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3747        const DLS::version_t File::VERSION_2 = {
3748            0, 2, 19980628 & 0xffff, 19980628 >> 16
3749        };
3750    
3751        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3752        const DLS::version_t File::VERSION_3 = {
3753            0, 3, 20030331 & 0xffff, 20030331 >> 16
3754        };
3755    
3756        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3757            { CHUNK_ID_IARL, 256 },
3758            { CHUNK_ID_IART, 128 },
3759            { CHUNK_ID_ICMS, 128 },
3760            { CHUNK_ID_ICMT, 1024 },
3761            { CHUNK_ID_ICOP, 128 },
3762            { CHUNK_ID_ICRD, 128 },
3763            { CHUNK_ID_IENG, 128 },
3764            { CHUNK_ID_IGNR, 128 },
3765            { CHUNK_ID_IKEY, 128 },
3766            { CHUNK_ID_IMED, 128 },
3767            { CHUNK_ID_INAM, 128 },
3768            { CHUNK_ID_IPRD, 128 },
3769            { CHUNK_ID_ISBJ, 128 },
3770            { CHUNK_ID_ISFT, 128 },
3771            { CHUNK_ID_ISRC, 128 },
3772            { CHUNK_ID_ISRF, 128 },
3773            { CHUNK_ID_ITCH, 128 },
3774            { 0, 0 }
3775        };
3776    
3777        File::File() : DLS::File() {
3778            bAutoLoad = true;
3779            *pVersion = VERSION_3;
3780            pGroups = NULL;
3781            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3782            pInfo->ArchivalLocation = String(256, ' ');
3783    
3784            // add some mandatory chunks to get the file chunks in right
3785            // order (INFO chunk will be moved to first position later)
3786            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3787            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3788            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3789    
3790            GenerateDLSID();
3791        }
3792    
3793      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3794          pSamples     = NULL;          bAutoLoad = true;
3795          pInstruments = NULL;          pGroups = NULL;
3796            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3797      }      }
3798    
3799      Sample* File::GetFirstSample() {      File::~File() {
3800          if (!pSamples) LoadSamples();          if (pGroups) {
3801                std::list<Group*>::iterator iter = pGroups->begin();
3802                std::list<Group*>::iterator end  = pGroups->end();
3803                while (iter != end) {
3804                    delete *iter;
3805                    ++iter;
3806                }
3807                delete pGroups;
3808            }
3809        }
3810    
3811        Sample* File::GetFirstSample(progress_t* pProgress) {
3812            if (!pSamples) LoadSamples(pProgress);
3813          if (!pSamples) return NULL;          if (!pSamples) return NULL;
3814          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
3815          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1220  namespace gig { Line 3820  namespace gig {
3820          SamplesIterator++;          SamplesIterator++;
3821          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3822      }      }
3823        
3824        /**
3825         * Returns Sample object of @a index.
3826         *
3827         * @returns sample object or NULL if index is out of bounds
3828         */
3829        Sample* File::GetSample(uint index) {
3830            if (!pSamples) LoadSamples();
3831            if (!pSamples) return NULL;
3832            DLS::File::SampleList::iterator it = pSamples->begin();
3833            for (int i = 0; i < index; ++i) {
3834                ++it;
3835                if (it == pSamples->end()) return NULL;
3836            }
3837            if (it == pSamples->end()) return NULL;
3838            return static_cast<gig::Sample*>( *it );
3839        }
3840    
3841      void File::LoadSamples() {      /** @brief Add a new sample.
3842          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);       *
3843          if (wvpl) {       * This will create a new Sample object for the gig file. You have to
3844              unsigned long wvplFileOffset = wvpl->GetFilePos();       * call Save() to make this persistent to the file.
3845              RIFF::List* wave = wvpl->GetFirstSubList();       *
3846              while (wave) {       * @returns pointer to new Sample object
3847                  if (wave->GetListType() == LIST_TYPE_WAVE) {       */
3848                      if (!pSamples) pSamples = new SampleList;      Sample* File::AddSample() {
3849                      unsigned long waveFileOffset = wave->GetFilePos();         if (!pSamples) LoadSamples();
3850                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));         __ensureMandatoryChunksExist();
3851           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
3852           // create new Sample object and its respective 'wave' list chunk
3853           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3854           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
3855    
3856           // add mandatory chunks to get the chunks in right order
3857           wave->AddSubChunk(CHUNK_ID_FMT, 16);
3858           wave->AddSubList(LIST_TYPE_INFO);
3859    
3860           pSamples->push_back(pSample);
3861           return pSample;
3862        }
3863    
3864        /** @brief Delete a sample.
3865         *
3866         * This will delete the given Sample object from the gig file. Any
3867         * references to this sample from Regions and DimensionRegions will be
3868         * removed. You have to call Save() to make this persistent to the file.
3869         *
3870         * @param pSample - sample to delete
3871         * @throws gig::Exception if given sample could not be found
3872         */
3873        void File::DeleteSample(Sample* pSample) {
3874            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
3875            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
3876            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
3877            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3878            pSamples->erase(iter);
3879            delete pSample;
3880    
3881            SampleList::iterator tmp = SamplesIterator;
3882            // remove all references to the sample
3883            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3884                 instrument = GetNextInstrument()) {
3885                for (Region* region = instrument->GetFirstRegion() ; region ;
3886                     region = instrument->GetNextRegion()) {
3887    
3888                    if (region->GetSample() == pSample) region->SetSample(NULL);
3889    
3890                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3891                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3892                        if (d->pSample == pSample) d->pSample = NULL;
3893                  }                  }
                 wave = wvpl->GetNextSubList();  
3894              }              }
3895          }          }
3896          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          SamplesIterator = tmp; // restore iterator
3897        }
3898    
3899        void File::LoadSamples() {
3900            LoadSamples(NULL);
3901        }
3902    
3903        void File::LoadSamples(progress_t* pProgress) {
3904            // Groups must be loaded before samples, because samples will try
3905            // to resolve the group they belong to
3906            if (!pGroups) LoadGroups();
3907    
3908            if (!pSamples) pSamples = new SampleList;
3909    
3910            RIFF::File* file = pRIFF;
3911    
3912            // just for progress calculation
3913            int iSampleIndex  = 0;
3914            int iTotalSamples = WavePoolCount;
3915    
3916            // check if samples should be loaded from extension files
3917            int lastFileNo = 0;
3918            for (int i = 0 ; i < WavePoolCount ; i++) {
3919                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
3920            }
3921            String name(pRIFF->GetFileName());
3922            int nameLen = name.length();
3923            char suffix[6];
3924            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
3925    
3926            for (int fileNo = 0 ; ; ) {
3927                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
3928                if (wvpl) {
3929                    unsigned long wvplFileOffset = wvpl->GetFilePos();
3930                    RIFF::List* wave = wvpl->GetFirstSubList();
3931                    while (wave) {
3932                        if (wave->GetListType() == LIST_TYPE_WAVE) {
3933                            // notify current progress
3934                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
3935                            __notify_progress(pProgress, subprogress);
3936    
3937                            unsigned long waveFileOffset = wave->GetFilePos();
3938                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
3939    
3940                            iSampleIndex++;
3941                        }
3942                        wave = wvpl->GetNextSubList();
3943                    }
3944    
3945                    if (fileNo == lastFileNo) break;
3946    
3947                    // open extension file (*.gx01, *.gx02, ...)
3948                    fileNo++;
3949                    sprintf(suffix, ".gx%02d", fileNo);
3950                    name.replace(nameLen, 5, suffix);
3951                    file = new RIFF::File(name);
3952                    ExtensionFiles.push_back(file);
3953                } else break;
3954            }
3955    
3956            __notify_progress(pProgress, 1.0); // notify done
3957      }      }
3958    
3959      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
3960          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
3961          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3962          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3963          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3964      }      }
3965    
3966      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
3967          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3968          InstrumentsIterator++;          InstrumentsIterator++;
3969          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3970      }      }
3971    
3972      /**      /**
3973       * Returns the instrument with the given index.       * Returns the instrument with the given index.
3974       *       *
3975         * @param index     - number of the sought instrument (0..n)
3976         * @param pProgress - optional: callback function for progress notification
3977       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
3978       */       */
3979      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
3980          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
3981                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
3982    
3983                // sample loading subtask
3984                progress_t subprogress;
3985                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
3986                __notify_progress(&subprogress, 0.0f);
3987                if (GetAutoLoad())
3988                    GetFirstSample(&subprogress); // now force all samples to be loaded
3989                __notify_progress(&subprogress, 1.0f);
3990    
3991                // instrument loading subtask
3992                if (pProgress && pProgress->callback) {
3993                    subprogress.__range_min = subprogress.__range_max;
3994                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
3995                }
3996                __notify_progress(&subprogress, 0.0f);
3997                LoadInstruments(&subprogress);
3998                __notify_progress(&subprogress, 1.0f);
3999            }
4000          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
4001          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
4002          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
4003              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
4004              InstrumentsIterator++;              InstrumentsIterator++;
4005          }          }
4006          return NULL;          return NULL;
4007      }      }
4008    
4009        /** @brief Add a new instrument definition.
4010         *
4011         * This will create a new Instrument object for the gig file. You have
4012         * to call Save() to make this persistent to the file.
4013         *
4014         * @returns pointer to new Instrument object
4015         */
4016        Instrument* File::AddInstrument() {
4017           if (!pInstruments) LoadInstruments();
4018           __ensureMandatoryChunksExist();
4019           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4020           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4021    
4022           // add mandatory chunks to get the chunks in right order
4023           lstInstr->AddSubList(LIST_TYPE_INFO);
4024           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4025    
4026           Instrument* pInstrument = new Instrument(this, lstInstr);
4027           pInstrument->GenerateDLSID();
4028    
4029           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4030    
4031           // this string is needed for the gig to be loadable in GSt:
4032           pInstrument->pInfo->Software = "Endless Wave";
4033    
4034           pInstruments->push_back(pInstrument);
4035           return pInstrument;
4036        }
4037        
4038        /** @brief Add a duplicate of an existing instrument.
4039         *
4040         * Duplicates the instrument definition given by @a orig and adds it
4041         * to this file. This allows in an instrument editor application to
4042         * easily create variations of an instrument, which will be stored in
4043         * the same .gig file, sharing i.e. the same samples.
4044         *
4045         * Note that all sample pointers referenced by @a orig are simply copied as
4046         * memory address. Thus the respective samples are shared, not duplicated!
4047         *
4048         * You have to call Save() to make this persistent to the file.
4049         *
4050         * @param orig - original instrument to be copied
4051         * @returns duplicated copy of the given instrument
4052         */
4053        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4054            Instrument* instr = AddInstrument();
4055            instr->CopyAssign(orig);
4056            return instr;
4057        }
4058        
4059        /** @brief Add content of another existing file.
4060         *
4061         * Duplicates the samples, groups and instruments of the original file
4062         * given by @a pFile and adds them to @c this File. In case @c this File is
4063         * a new one that you haven't saved before, then you have to call
4064         * SetFileName() before calling AddContentOf(), because this method will
4065         * automatically save this file during operation, which is required for
4066         * writing the sample waveform data by disk streaming.
4067         *
4068         * @param pFile - original file whose's content shall be copied from
4069         */
4070        void File::AddContentOf(File* pFile) {
4071            static int iCallCount = -1;
4072            iCallCount++;
4073            std::map<Group*,Group*> mGroups;
4074            std::map<Sample*,Sample*> mSamples;
4075            
4076            // clone sample groups
4077            for (int i = 0; pFile->GetGroup(i); ++i) {
4078                Group* g = AddGroup();
4079                g->Name =
4080                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4081                mGroups[pFile->GetGroup(i)] = g;
4082            }
4083            
4084            // clone samples (not waveform data here yet)
4085            for (int i = 0; pFile->GetSample(i); ++i) {
4086                Sample* s = AddSample();
4087                s->CopyAssignMeta(pFile->GetSample(i));
4088                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4089                mSamples[pFile->GetSample(i)] = s;
4090            }
4091            
4092            //BUG: For some reason this method only works with this additional
4093            //     Save() call in between here.
4094            //
4095            // Important: The correct one of the 2 Save() methods has to be called
4096            // here, depending on whether the file is completely new or has been
4097            // saved to disk already, otherwise it will result in data corruption.
4098            if (pRIFF->IsNew())
4099                Save(GetFileName());
4100            else
4101                Save();
4102            
4103            // clone instruments
4104            // (passing the crosslink table here for the cloned samples)
4105            for (int i = 0; pFile->GetInstrument(i); ++i) {
4106                Instrument* instr = AddInstrument();
4107                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4108            }
4109            
4110            // Mandatory: file needs to be saved to disk at this point, so this
4111            // file has the correct size and data layout for writing the samples'
4112            // waveform data to disk.
4113            Save();
4114            
4115            // clone samples' waveform data
4116            // (using direct read & write disk streaming)
4117            for (int i = 0; pFile->GetSample(i); ++i) {
4118                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4119            }
4120        }
4121    
4122        /** @brief Delete an instrument.
4123         *
4124         * This will delete the given Instrument object from the gig file. You
4125         * have to call Save() to make this persistent to the file.
4126         *
4127         * @param pInstrument - instrument to delete
4128         * @throws gig::Exception if given instrument could not be found
4129         */
4130        void File::DeleteInstrument(Instrument* pInstrument) {
4131            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
4132            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
4133            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
4134            pInstruments->erase(iter);
4135            delete pInstrument;
4136        }
4137    
4138      void File::LoadInstruments() {      void File::LoadInstruments() {
4139            LoadInstruments(NULL);
4140        }
4141    
4142        void File::LoadInstruments(progress_t* pProgress) {
4143            if (!pInstruments) pInstruments = new InstrumentList;
4144          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4145          if (lstInstruments) {          if (lstInstruments) {
4146                int iInstrumentIndex = 0;
4147              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
4148              while (lstInstr) {              while (lstInstr) {
4149                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
4150                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
4151                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
4152                        __notify_progress(pProgress, localProgress);
4153    
4154                        // divide local progress into subprogress for loading current Instrument
4155                        progress_t subprogress;
4156                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
4157    
4158                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
4159    
4160                        iInstrumentIndex++;
4161                  }                  }
4162                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
4163              }              }
4164                __notify_progress(pProgress, 1.0); // notify done
4165            }
4166        }
4167    
4168        /// Updates the 3crc chunk with the checksum of a sample. The
4169        /// update is done directly to disk, as this method is called
4170        /// after File::Save()
4171        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4172            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4173            if (!_3crc) return;
4174    
4175            // get the index of the sample
4176            int iWaveIndex = -1;
4177            File::SampleList::iterator iter = pSamples->begin();
4178            File::SampleList::iterator end  = pSamples->end();
4179            for (int index = 0; iter != end; ++iter, ++index) {
4180                if (*iter == pSample) {
4181                    iWaveIndex = index;
4182                    break;
4183                }
4184            }
4185            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4186    
4187            // write the CRC-32 checksum to disk
4188            _3crc->SetPos(iWaveIndex * 8);
4189            uint32_t tmp = 1;
4190            _3crc->WriteUint32(&tmp); // unknown, always 1?
4191            _3crc->WriteUint32(&crc);
4192        }
4193    
4194        Group* File::GetFirstGroup() {
4195            if (!pGroups) LoadGroups();
4196            // there must always be at least one group
4197            GroupsIterator = pGroups->begin();
4198            return *GroupsIterator;
4199        }
4200    
4201        Group* File::GetNextGroup() {
4202            if (!pGroups) return NULL;
4203            ++GroupsIterator;
4204            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
4205        }
4206    
4207        /**
4208         * Returns the group with the given index.
4209         *
4210         * @param index - number of the sought group (0..n)
4211         * @returns sought group or NULL if there's no such group
4212         */
4213        Group* File::GetGroup(uint index) {
4214            if (!pGroups) LoadGroups();
4215            GroupsIterator = pGroups->begin();
4216            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4217                if (i == index) return *GroupsIterator;
4218                ++GroupsIterator;
4219            }
4220            return NULL;
4221        }
4222    
4223        Group* File::AddGroup() {
4224            if (!pGroups) LoadGroups();
4225            // there must always be at least one group
4226            __ensureMandatoryChunksExist();
4227            Group* pGroup = new Group(this, NULL);
4228            pGroups->push_back(pGroup);
4229            return pGroup;
4230        }
4231    
4232        /** @brief Delete a group and its samples.
4233         *
4234         * This will delete the given Group object and all the samples that
4235         * belong to this group from the gig file. You have to call Save() to
4236         * make this persistent to the file.
4237         *
4238         * @param pGroup - group to delete
4239         * @throws gig::Exception if given group could not be found
4240         */
4241        void File::DeleteGroup(Group* pGroup) {
4242            if (!pGroups) LoadGroups();
4243            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4244            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4245            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4246            // delete all members of this group
4247            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
4248                DeleteSample(pSample);
4249          }          }
4250          else throw gig::Exception("Mandatory <lins> list chunk not found.");          // now delete this group object
4251            pGroups->erase(iter);
4252            delete pGroup;
4253        }
4254    
4255        /** @brief Delete a group.
4256         *
4257         * This will delete the given Group object from the gig file. All the
4258         * samples that belong to this group will not be deleted, but instead
4259         * be moved to another group. You have to call Save() to make this
4260         * persistent to the file.
4261         *
4262         * @param pGroup - group to delete
4263         * @throws gig::Exception if given group could not be found
4264         */
4265        void File::DeleteGroupOnly(Group* pGroup) {
4266            if (!pGroups) LoadGroups();
4267            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4268            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4269            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4270            // move all members of this group to another group
4271            pGroup->MoveAll();
4272            pGroups->erase(iter);
4273            delete pGroup;
4274        }
4275    
4276        void File::LoadGroups() {
4277            if (!pGroups) pGroups = new std::list<Group*>;
4278            // try to read defined groups from file
4279            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4280            if (lst3gri) {
4281                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
4282                if (lst3gnl) {
4283                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4284                    while (ck) {
4285                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4286                            if (pVersion && pVersion->major == 3 &&
4287                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4288    
4289                            pGroups->push_back(new Group(this, ck));
4290                        }
4291                        ck = lst3gnl->GetNextSubChunk();
4292                    }
4293                }
4294            }
4295            // if there were no group(s), create at least the mandatory default group
4296            if (!pGroups->size()) {
4297                Group* pGroup = new Group(this, NULL);
4298                pGroup->Name = "Default Group";
4299                pGroups->push_back(pGroup);
4300            }
4301        }
4302    
4303        /**
4304         * Apply all the gig file's current instruments, samples, groups and settings
4305         * to the respective RIFF chunks. You have to call Save() to make changes
4306         * persistent.
4307         *
4308         * Usually there is absolutely no need to call this method explicitly.
4309         * It will be called automatically when File::Save() was called.
4310         *
4311         * @throws Exception - on errors
4312         */
4313        void File::UpdateChunks() {
4314            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4315    
4316            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4317    
4318            // first update base class's chunks
4319            DLS::File::UpdateChunks();
4320    
4321            if (newFile) {
4322                // INFO was added by Resource::UpdateChunks - make sure it
4323                // is placed first in file
4324                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4325                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4326                if (first != info) {
4327                    pRIFF->MoveSubChunk(info, first);
4328                }
4329            }
4330    
4331            // update group's chunks
4332            if (pGroups) {
4333                // make sure '3gri' and '3gnl' list chunks exist
4334                // (before updating the Group chunks)
4335                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4336                if (!_3gri) {
4337                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4338                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4339                }
4340                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4341                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4342    
4343                // v3: make sure the file has 128 3gnm chunks
4344                // (before updating the Group chunks)
4345                if (pVersion && pVersion->major == 3) {
4346                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4347                    for (int i = 0 ; i < 128 ; i++) {
4348                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4349                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4350                    }
4351                }
4352    
4353                std::list<Group*>::iterator iter = pGroups->begin();
4354                std::list<Group*>::iterator end  = pGroups->end();
4355                for (; iter != end; ++iter) {
4356                    (*iter)->UpdateChunks();
4357                }
4358            }
4359    
4360            // update einf chunk
4361    
4362            // The einf chunk contains statistics about the gig file, such
4363            // as the number of regions and samples used by each
4364            // instrument. It is divided in equally sized parts, where the
4365            // first part contains information about the whole gig file,
4366            // and the rest of the parts map to each instrument in the
4367            // file.
4368            //
4369            // At the end of each part there is a bit map of each sample
4370            // in the file, where a set bit means that the sample is used
4371            // by the file/instrument.
4372            //
4373            // Note that there are several fields with unknown use. These
4374            // are set to zero.
4375    
4376            int sublen = pSamples->size() / 8 + 49;
4377            int einfSize = (Instruments + 1) * sublen;
4378    
4379            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4380            if (einf) {
4381                if (einf->GetSize() != einfSize) {
4382                    einf->Resize(einfSize);
4383                    memset(einf->LoadChunkData(), 0, einfSize);
4384                }
4385            } else if (newFile) {
4386                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4387            }
4388            if (einf) {
4389                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4390    
4391                std::map<gig::Sample*,int> sampleMap;
4392                int sampleIdx = 0;
4393                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4394                    sampleMap[pSample] = sampleIdx++;
4395                }
4396    
4397                int totnbusedsamples = 0;
4398                int totnbusedchannels = 0;
4399                int totnbregions = 0;
4400                int totnbdimregions = 0;
4401                int totnbloops = 0;
4402                int instrumentIdx = 0;
4403    
4404                memset(&pData[48], 0, sublen - 48);
4405    
4406                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4407                     instrument = GetNextInstrument()) {
4408                    int nbusedsamples = 0;
4409                    int nbusedchannels = 0;
4410                    int nbdimregions = 0;
4411                    int nbloops = 0;
4412    
4413                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4414    
4415                    for (Region* region = instrument->GetFirstRegion() ; region ;
4416                         region = instrument->GetNextRegion()) {
4417                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
4418                            gig::DimensionRegion *d = region->pDimensionRegions[i];
4419                            if (d->pSample) {
4420                                int sampleIdx = sampleMap[d->pSample];
4421                                int byte = 48 + sampleIdx / 8;
4422                                int bit = 1 << (sampleIdx & 7);
4423                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4424                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4425                                    nbusedsamples++;
4426                                    nbusedchannels += d->pSample->Channels;
4427    
4428                                    if ((pData[byte] & bit) == 0) {
4429                                        pData[byte] |= bit;
4430                                        totnbusedsamples++;
4431                                        totnbusedchannels += d->pSample->Channels;
4432                                    }
4433                                }
4434                            }
4435                            if (d->SampleLoops) nbloops++;
4436                        }
4437                        nbdimregions += region->DimensionRegions;
4438                    }
4439                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4440                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4441                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4442                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4443                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4444                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4445                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4446                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4447                    // next 8 bytes unknown
4448                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4449                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4450                    // next 4 bytes unknown
4451    
4452                    totnbregions += instrument->Regions;
4453                    totnbdimregions += nbdimregions;
4454                    totnbloops += nbloops;
4455                    instrumentIdx++;
4456                }
4457                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4458                // store32(&pData[0], sublen);
4459                store32(&pData[4], totnbusedchannels);
4460                store32(&pData[8], totnbusedsamples);
4461                store32(&pData[12], Instruments);
4462                store32(&pData[16], totnbregions);
4463                store32(&pData[20], totnbdimregions);
4464                store32(&pData[24], totnbloops);
4465                // next 8 bytes unknown
4466                // next 4 bytes unknown, not always 0
4467                store32(&pData[40], pSamples->size());
4468                // next 4 bytes unknown
4469            }
4470    
4471            // update 3crc chunk
4472    
4473            // The 3crc chunk contains CRC-32 checksums for the
4474            // samples. The actual checksum values will be filled in
4475            // later, by Sample::Write.
4476    
4477            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4478            if (_3crc) {
4479                _3crc->Resize(pSamples->size() * 8);
4480            } else if (newFile) {
4481                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4482                _3crc->LoadChunkData();
4483    
4484                // the order of einf and 3crc is not the same in v2 and v3
4485                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4486            }
4487        }
4488    
4489        /**
4490         * Enable / disable automatic loading. By default this properyt is
4491         * enabled and all informations are loaded automatically. However
4492         * loading all Regions, DimensionRegions and especially samples might
4493         * take a long time for large .gig files, and sometimes one might only
4494         * be interested in retrieving very superficial informations like the
4495         * amount of instruments and their names. In this case one might disable
4496         * automatic loading to avoid very slow response times.
4497         *
4498         * @e CAUTION: by disabling this property many pointers (i.e. sample
4499         * references) and informations will have invalid or even undefined
4500         * data! This feature is currently only intended for retrieving very
4501         * superficial informations in a very fast way. Don't use it to retrieve
4502         * details like synthesis informations or even to modify .gig files!
4503         */
4504        void File::SetAutoLoad(bool b) {
4505            bAutoLoad = b;
4506        }
4507    
4508        /**
4509         * Returns whether automatic loading is enabled.
4510         * @see SetAutoLoad()
4511         */
4512        bool File::GetAutoLoad() {
4513            return bAutoLoad;
4514      }      }
4515    
4516    
# Line 1294  namespace gig { Line 4525  namespace gig {
4525          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
4526      }      }
4527    
4528    
4529    // *************** functions ***************
4530    // *
4531    
4532        /**
4533         * Returns the name of this C++ library. This is usually "libgig" of
4534         * course. This call is equivalent to RIFF::libraryName() and
4535         * DLS::libraryName().
4536         */
4537        String libraryName() {
4538            return PACKAGE;
4539        }
4540    
4541        /**
4542         * Returns version of this C++ library. This call is equivalent to
4543         * RIFF::libraryVersion() and DLS::libraryVersion().
4544         */
4545        String libraryVersion() {
4546            return VERSION;
4547        }
4548    
4549  } // namespace gig  } // namespace gig

Legend:
Removed from v.24  
changed lines
  Added in v.2482

  ViewVC Help
Powered by ViewVC