/[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 36 by schoenebeck, Wed Mar 10 21:34:28 2004 UTC revision 2682 by schoenebeck, Mon Dec 29 16:25:51 2014 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-2014 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    #include <assert.h>
32    
33    /// Initial size of the sample buffer which is used for decompression of
34    /// compressed sample wave streams - this value should always be bigger than
35    /// the biggest sample piece expected to be read by the sampler engine,
36    /// otherwise the buffer size will be raised at runtime and thus the buffer
37    /// reallocated which is time consuming and unefficient.
38    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
39    
40    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
41    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
42    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
43    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
44    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
45    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
46    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
47    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
48    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
49    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
50    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
51    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
52    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
53    
54  namespace gig {  namespace gig {
55    
56    // *************** Internal functions for sample decompression ***************
57    // *
58    
59    namespace {
60    
61        inline int get12lo(const unsigned char* pSrc)
62        {
63            const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
64            return x & 0x800 ? x - 0x1000 : x;
65        }
66    
67        inline int get12hi(const unsigned char* pSrc)
68        {
69            const int x = pSrc[1] >> 4 | pSrc[2] << 4;
70            return x & 0x800 ? x - 0x1000 : x;
71        }
72    
73        inline int16_t get16(const unsigned char* pSrc)
74        {
75            return int16_t(pSrc[0] | pSrc[1] << 8);
76        }
77    
78        inline int get24(const unsigned char* pSrc)
79        {
80            const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
81            return x & 0x800000 ? x - 0x1000000 : x;
82        }
83    
84        inline void store24(unsigned char* pDst, int x)
85        {
86            pDst[0] = x;
87            pDst[1] = x >> 8;
88            pDst[2] = x >> 16;
89        }
90    
91        void Decompress16(int compressionmode, const unsigned char* params,
92                          int srcStep, int dstStep,
93                          const unsigned char* pSrc, int16_t* pDst,
94                          unsigned long currentframeoffset,
95                          unsigned long copysamples)
96        {
97            switch (compressionmode) {
98                case 0: // 16 bit uncompressed
99                    pSrc += currentframeoffset * srcStep;
100                    while (copysamples) {
101                        *pDst = get16(pSrc);
102                        pDst += dstStep;
103                        pSrc += srcStep;
104                        copysamples--;
105                    }
106                    break;
107    
108                case 1: // 16 bit compressed to 8 bit
109                    int y  = get16(params);
110                    int dy = get16(params + 2);
111                    while (currentframeoffset) {
112                        dy -= int8_t(*pSrc);
113                        y  -= dy;
114                        pSrc += srcStep;
115                        currentframeoffset--;
116                    }
117                    while (copysamples) {
118                        dy -= int8_t(*pSrc);
119                        y  -= dy;
120                        *pDst = y;
121                        pDst += dstStep;
122                        pSrc += srcStep;
123                        copysamples--;
124                    }
125                    break;
126            }
127        }
128    
129        void Decompress24(int compressionmode, const unsigned char* params,
130                          int dstStep, const unsigned char* pSrc, uint8_t* pDst,
131                          unsigned long currentframeoffset,
132                          unsigned long copysamples, int truncatedBits)
133        {
134            int y, dy, ddy, dddy;
135    
136    #define GET_PARAMS(params)                      \
137            y    = get24(params);                   \
138            dy   = y - get24((params) + 3);         \
139            ddy  = get24((params) + 6);             \
140            dddy = get24((params) + 9)
141    
142    #define SKIP_ONE(x)                             \
143            dddy -= (x);                            \
144            ddy  -= dddy;                           \
145            dy   =  -dy - ddy;                      \
146            y    += dy
147    
148    #define COPY_ONE(x)                             \
149            SKIP_ONE(x);                            \
150            store24(pDst, y << truncatedBits);      \
151            pDst += dstStep
152    
153            switch (compressionmode) {
154                case 2: // 24 bit uncompressed
155                    pSrc += currentframeoffset * 3;
156                    while (copysamples) {
157                        store24(pDst, get24(pSrc) << truncatedBits);
158                        pDst += dstStep;
159                        pSrc += 3;
160                        copysamples--;
161                    }
162                    break;
163    
164                case 3: // 24 bit compressed to 16 bit
165                    GET_PARAMS(params);
166                    while (currentframeoffset) {
167                        SKIP_ONE(get16(pSrc));
168                        pSrc += 2;
169                        currentframeoffset--;
170                    }
171                    while (copysamples) {
172                        COPY_ONE(get16(pSrc));
173                        pSrc += 2;
174                        copysamples--;
175                    }
176                    break;
177    
178                case 4: // 24 bit compressed to 12 bit
179                    GET_PARAMS(params);
180                    while (currentframeoffset > 1) {
181                        SKIP_ONE(get12lo(pSrc));
182                        SKIP_ONE(get12hi(pSrc));
183                        pSrc += 3;
184                        currentframeoffset -= 2;
185                    }
186                    if (currentframeoffset) {
187                        SKIP_ONE(get12lo(pSrc));
188                        currentframeoffset--;
189                        if (copysamples) {
190                            COPY_ONE(get12hi(pSrc));
191                            pSrc += 3;
192                            copysamples--;
193                        }
194                    }
195                    while (copysamples > 1) {
196                        COPY_ONE(get12lo(pSrc));
197                        COPY_ONE(get12hi(pSrc));
198                        pSrc += 3;
199                        copysamples -= 2;
200                    }
201                    if (copysamples) {
202                        COPY_ONE(get12lo(pSrc));
203                    }
204                    break;
205    
206                case 5: // 24 bit compressed to 8 bit
207                    GET_PARAMS(params);
208                    while (currentframeoffset) {
209                        SKIP_ONE(int8_t(*pSrc++));
210                        currentframeoffset--;
211                    }
212                    while (copysamples) {
213                        COPY_ONE(int8_t(*pSrc++));
214                        copysamples--;
215                    }
216                    break;
217            }
218        }
219    
220        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
221        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
222        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
223        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
224    }
225    
226    
227    
228    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
229    // *
230    
231        static uint32_t* __initCRCTable() {
232            static uint32_t res[256];
233    
234            for (int i = 0 ; i < 256 ; i++) {
235                uint32_t c = i;
236                for (int j = 0 ; j < 8 ; j++) {
237                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
238                }
239                res[i] = c;
240            }
241            return res;
242        }
243    
244        static const uint32_t* __CRCTable = __initCRCTable();
245    
246        /**
247         * Initialize a CRC variable.
248         *
249         * @param crc - variable to be initialized
250         */
251        inline static void __resetCRC(uint32_t& crc) {
252            crc = 0xffffffff;
253        }
254    
255        /**
256         * Used to calculate checksums of the sample data in a gig file. The
257         * checksums are stored in the 3crc chunk of the gig file and
258         * automatically updated when a sample is written with Sample::Write().
259         *
260         * One should call __resetCRC() to initialize the CRC variable to be
261         * used before calling this function the first time.
262         *
263         * After initializing the CRC variable one can call this function
264         * arbitrary times, i.e. to split the overall CRC calculation into
265         * steps.
266         *
267         * Once the whole data was processed by __calculateCRC(), one should
268         * call __encodeCRC() to get the final CRC result.
269         *
270         * @param buf     - pointer to data the CRC shall be calculated of
271         * @param bufSize - size of the data to be processed
272         * @param crc     - variable the CRC sum shall be stored to
273         */
274        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
275            for (int i = 0 ; i < bufSize ; i++) {
276                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
277            }
278        }
279    
280        /**
281         * Returns the final CRC result.
282         *
283         * @param crc - variable previously passed to __calculateCRC()
284         */
285        inline static uint32_t __encodeCRC(const uint32_t& crc) {
286            return crc ^ 0xffffffff;
287        }
288    
289    
290    
291    // *************** Other Internal functions  ***************
292    // *
293    
294        static split_type_t __resolveSplitType(dimension_t dimension) {
295            return (
296                dimension == dimension_layer ||
297                dimension == dimension_samplechannel ||
298                dimension == dimension_releasetrigger ||
299                dimension == dimension_keyboard ||
300                dimension == dimension_roundrobin ||
301                dimension == dimension_random ||
302                dimension == dimension_smartmidi ||
303                dimension == dimension_roundrobinkeyboard
304            ) ? split_type_bit : split_type_normal;
305        }
306    
307        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
308            return (dimension_definition.split_type == split_type_normal)
309            ? int(128.0 / dimension_definition.zones) : 0;
310        }
311    
312    
313    
314  // *************** Sample ***************  // *************** Sample ***************
315  // *  // *
316    
317      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
318      void*         Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
319    
320      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
321         *
322         * Load an existing sample or create a new one. A 'wave' list chunk must
323         * be given to this constructor. In case the given 'wave' list chunk
324         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
325         * format and sample data will be loaded from there, otherwise default
326         * values will be used and those chunks will be created when
327         * File::Save() will be called later on.
328         *
329         * @param pFile          - pointer to gig::File where this sample is
330         *                         located (or will be located)
331         * @param waveList       - pointer to 'wave' list chunk which is (or
332         *                         will be) associated with this sample
333         * @param WavePoolOffset - offset of this sample data from wave pool
334         *                         ('wvpl') list chunk
335         * @param fileNo         - number of an extension file where this sample
336         *                         is located, 0 otherwise
337         */
338        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
339            static const DLS::Info::string_length_t fixedStringLengths[] = {
340                { CHUNK_ID_INAM, 64 },
341                { 0, 0 }
342            };
343            pInfo->SetFixedStringLengths(fixedStringLengths);
344          Instances++;          Instances++;
345            FileNo = fileNo;
346    
347            __resetCRC(crc);
348    
349          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
350          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
351          SampleGroup = _3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
352                pGroup = pFile->GetGroup(iSampleGroup);
353          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          } else { // '3gix' chunk missing
354          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              // by default assigned to that mandatory "Default Group"
355          Manufacturer      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
356          Product           = smpl->ReadInt32();          }
357          SamplePeriod      = smpl->ReadInt32();  
358          MIDIUnityNote     = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
359          FineTune          = smpl->ReadInt32();          if (pCkSmpl) {
360          smpl->Read(&SMPTEFormat, 1, 4);              Manufacturer  = pCkSmpl->ReadInt32();
361          SMPTEOffset       = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
362          Loops             = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
363          uint32_t manufByt = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
364          LoopID            = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
365          smpl->Read(&LoopType, 1, 4);              pCkSmpl->Read(&SMPTEFormat, 1, 4);
366          LoopStart         = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
367          LoopEnd           = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
368          LoopFraction      = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
369          LoopPlayCount     = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
370                pCkSmpl->Read(&LoopType, 1, 4);
371                LoopStart     = pCkSmpl->ReadInt32();
372                LoopEnd       = pCkSmpl->ReadInt32();
373                LoopFraction  = pCkSmpl->ReadInt32();
374                LoopPlayCount = pCkSmpl->ReadInt32();
375            } else { // 'smpl' chunk missing
376                // use default values
377                Manufacturer  = 0;
378                Product       = 0;
379                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
380                MIDIUnityNote = 60;
381                FineTune      = 0;
382                SMPTEFormat   = smpte_format_no_offset;
383                SMPTEOffset   = 0;
384                Loops         = 0;
385                LoopID        = 0;
386                LoopType      = loop_type_normal;
387                LoopStart     = 0;
388                LoopEnd       = 0;
389                LoopFraction  = 0;
390                LoopPlayCount = 0;
391            }
392    
393          FrameTable                 = NULL;          FrameTable                 = NULL;
394          SamplePos                  = 0;          SamplePos                  = 0;
# Line 63  namespace gig { Line 396  namespace gig {
396          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
397          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
398    
399          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
400    
401            RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
402            Compressed        = ewav;
403            Dithered          = false;
404            TruncatedBits     = 0;
405          if (Compressed) {          if (Compressed) {
406              ScanCompressedSample();              uint32_t version = ewav->ReadInt32();
407              if (!pDecompressionBuffer) {              if (version == 3 && BitDepth == 24) {
408                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];                  Dithered = ewav->ReadInt32();
409                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;                  ewav->SetPos(Channels == 2 ? 84 : 64);
410                    TruncatedBits = ewav->ReadInt32();
411              }              }
412                ScanCompressedSample();
413            }
414    
415            // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
416            if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
417                InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
418                InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
419          }          }
420          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
421    
422          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
423        }
424    
425        /**
426         * Make a (semi) deep copy of the Sample object given by @a orig (without
427         * the actual waveform data) and assign it to this object.
428         *
429         * Discussion: copying .gig samples is a bit tricky. It requires three
430         * steps:
431         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
432         *    its new sample waveform data size.
433         * 2. Saving the file (done by File::Save()) so that it gains correct size
434         *    and layout for writing the actual wave form data directly to disc
435         *    in next step.
436         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
437         *
438         * @param orig - original Sample object to be copied from
439         */
440        void Sample::CopyAssignMeta(const Sample* orig) {
441            // handle base classes
442            DLS::Sample::CopyAssignCore(orig);
443            
444            // handle actual own attributes of this class
445            Manufacturer = orig->Manufacturer;
446            Product = orig->Product;
447            SamplePeriod = orig->SamplePeriod;
448            MIDIUnityNote = orig->MIDIUnityNote;
449            FineTune = orig->FineTune;
450            SMPTEFormat = orig->SMPTEFormat;
451            SMPTEOffset = orig->SMPTEOffset;
452            Loops = orig->Loops;
453            LoopID = orig->LoopID;
454            LoopType = orig->LoopType;
455            LoopStart = orig->LoopStart;
456            LoopEnd = orig->LoopEnd;
457            LoopSize = orig->LoopSize;
458            LoopFraction = orig->LoopFraction;
459            LoopPlayCount = orig->LoopPlayCount;
460            
461            // schedule resizing this sample to the given sample's size
462            Resize(orig->GetSize());
463        }
464    
465        /**
466         * Should be called after CopyAssignMeta() and File::Save() sequence.
467         * Read more about it in the discussion of CopyAssignMeta(). This method
468         * copies the actual waveform data by disk streaming.
469         *
470         * @e CAUTION: this method is currently not thread safe! During this
471         * operation the sample must not be used for other purposes by other
472         * threads!
473         *
474         * @param orig - original Sample object to be copied from
475         */
476        void Sample::CopyAssignWave(const Sample* orig) {
477            const int iReadAtOnce = 32*1024;
478            char* buf = new char[iReadAtOnce * orig->FrameSize];
479            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
480            unsigned long restorePos = pOrig->GetPos();
481            pOrig->SetPos(0);
482            SetPos(0);
483            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
484                               n = pOrig->Read(buf, iReadAtOnce))
485            {
486                Write(buf, n);
487            }
488            pOrig->SetPos(restorePos);
489            delete [] buf;
490        }
491    
492        /**
493         * Apply sample and its settings to the respective RIFF chunks. You have
494         * to call File::Save() to make changes persistent.
495         *
496         * Usually there is absolutely no need to call this method explicitly.
497         * It will be called automatically when File::Save() was called.
498         *
499         * @param pProgress - callback function for progress notification
500         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
501         *                        was provided yet
502         * @throws gig::Exception if there is any invalid sample setting
503         */
504        void Sample::UpdateChunks(progress_t* pProgress) {
505            // first update base class's chunks
506            DLS::Sample::UpdateChunks(pProgress);
507    
508            // make sure 'smpl' chunk exists
509            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
510            if (!pCkSmpl) {
511                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
512                memset(pCkSmpl->LoadChunkData(), 0, 60);
513            }
514            // update 'smpl' chunk
515            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
516            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
517            store32(&pData[0], Manufacturer);
518            store32(&pData[4], Product);
519            store32(&pData[8], SamplePeriod);
520            store32(&pData[12], MIDIUnityNote);
521            store32(&pData[16], FineTune);
522            store32(&pData[20], SMPTEFormat);
523            store32(&pData[24], SMPTEOffset);
524            store32(&pData[28], Loops);
525    
526            // we skip 'manufByt' for now (4 bytes)
527    
528            store32(&pData[36], LoopID);
529            store32(&pData[40], LoopType);
530            store32(&pData[44], LoopStart);
531            store32(&pData[48], LoopEnd);
532            store32(&pData[52], LoopFraction);
533            store32(&pData[56], LoopPlayCount);
534    
535            // make sure '3gix' chunk exists
536            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
537            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
538            // determine appropriate sample group index (to be stored in chunk)
539            uint16_t iSampleGroup = 0; // 0 refers to default sample group
540            File* pFile = static_cast<File*>(pParent);
541            if (pFile->pGroups) {
542                std::list<Group*>::iterator iter = pFile->pGroups->begin();
543                std::list<Group*>::iterator end  = pFile->pGroups->end();
544                for (int i = 0; iter != end; i++, iter++) {
545                    if (*iter == pGroup) {
546                        iSampleGroup = i;
547                        break; // found
548                    }
549                }
550            }
551            // update '3gix' chunk
552            pData = (uint8_t*) pCk3gix->LoadChunkData();
553            store16(&pData[0], iSampleGroup);
554    
555            // if the library user toggled the "Compressed" attribute from true to
556            // false, then the EWAV chunk associated with compressed samples needs
557            // to be deleted
558            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
559            if (ewav && !Compressed) {
560                pWaveList->DeleteSubChunk(ewav);
561            }
562      }      }
563    
564      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 82  namespace gig { Line 567  namespace gig {
567          this->SamplesTotal = 0;          this->SamplesTotal = 0;
568          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
569    
570            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
571            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
572    
573          // Scanning          // Scanning
574          pCkData->SetPos(0);          pCkData->SetPos(0);
575          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
576              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
577              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
578              this->SamplesTotal += 2048;                  // stored, to save some memory
579              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
580                  case 1:   // left channel compressed  
581                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
582                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
583                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
584                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
585    
586                    if (pCkData->RemainingBytes() <= frameSize) {
587                        SamplesInLastFrame =
588                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
589                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
590                        SamplesTotal += SamplesInLastFrame;
591                      break;                      break;
592                  case 257: // both channels compressed                  }
593                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
594                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
595                }
596            }
597            else { // Mono
598                for (int i = 0 ; ; i++) {
599                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
600    
601                    const int mode = pCkData->ReadUint8();
602                    if (mode > 5) throw gig::Exception("Unknown compression mode");
603                    const unsigned long frameSize = bytesPerFrame[mode];
604    
605                    if (pCkData->RemainingBytes() <= frameSize) {
606                        SamplesInLastFrame =
607                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
608                        SamplesTotal += SamplesInLastFrame;
609                      break;                      break;
610                  default: // both channels uncompressed                  }
611                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
612                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
613              }              }
614          }          }
615          pCkData->SetPos(0);          pCkData->SetPos(0);
616    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
617          // 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)
618          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
619          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 141  namespace gig { Line 649  namespace gig {
649       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
650       * 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
651       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
652       *       * @code
653       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
654       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
655         * @endcode
656       *       *
657       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
658       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 189  namespace gig { Line 698  namespace gig {
698       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
699       * 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
700       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
701       *       * @code
702       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
703       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
704       *       * @endcode
705       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
706       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
707       * 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 213  namespace gig { Line 722  namespace gig {
722          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
723          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
724          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
725            SetPos(0); // reset read position to begin of sample
726          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
727          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
728          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 250  namespace gig { Line 760  namespace gig {
760          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
761          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
762          RAMCache.Size   = 0;          RAMCache.Size   = 0;
763            RAMCache.NullExtensionSize = 0;
764        }
765    
766        /** @brief Resize sample.
767         *
768         * Resizes the sample's wave form data, that is the actual size of
769         * sample wave data possible to be written for this sample. This call
770         * will return immediately and just schedule the resize operation. You
771         * should call File::Save() to actually perform the resize operation(s)
772         * "physically" to the file. As this can take a while on large files, it
773         * is recommended to call Resize() first on all samples which have to be
774         * resized and finally to call File::Save() to perform all those resize
775         * operations in one rush.
776         *
777         * The actual size (in bytes) is dependant to the current FrameSize
778         * value. You may want to set FrameSize before calling Resize().
779         *
780         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
781         * enlarged samples before calling File::Save() as this might exceed the
782         * current sample's boundary!
783         *
784         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
785         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
786         * other formats will fail!
787         *
788         * @param iNewSize - new sample wave data size in sample points (must be
789         *                   greater than zero)
790         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
791         *                         or if \a iNewSize is less than 1
792         * @throws gig::Exception if existing sample is compressed
793         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
794         *      DLS::Sample::FormatTag, File::Save()
795         */
796        void Sample::Resize(int iNewSize) {
797            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
798            DLS::Sample::Resize(iNewSize);
799      }      }
800    
801      /**      /**
# Line 307  namespace gig { Line 853  namespace gig {
853      /**      /**
854       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
855       */       */
856      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
857          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
858          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
859      }      }
# Line 323  namespace gig { Line 869  namespace gig {
869       * 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.
870       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
871       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
872       *       * @code
873       * <i>       * gig::playback_state_t playbackstate;
874       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
875       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
876       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
877       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
878       * 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
879       * 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.
880       * The method already handles such cases by itself.       * The method already handles such cases by itself.
881       *       *
882         * <b>Caution:</b> If you are using more than one streaming thread, you
883         * have to use an external decompression buffer for <b>EACH</b>
884         * streaming thread to avoid race conditions and crashes!
885         *
886       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
887       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
888       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
889       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
890         * @param pDimRgn          dimension region with looping information
891         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
892       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
893         * @see                    CreateDecompressionBuffer()
894       */       */
895      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,
896                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
897          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
898          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
899    
900          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
901    
902          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
903    
904              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
905                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
906    
907                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
908                      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  
909    
910                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
911                              // determine the end position within the loop first,                          do {
912                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
913                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
914                              // backward playback  
915                                if (!pPlaybackState->reverse) { // forward playback
916                              unsigned long swapareastart       = totalreadsamples;                                  do {
917                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
918                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
919                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
920                                        totalreadsamples += readsamples;
921                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
922                                            pPlaybackState->reverse = true;
923                              // read samples for backward playback                                          break;
924                              do {                                      }
925                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  } while (samplestoread && readsamples);
926                                  samplestoreadinloop -= readsamples;                              }
927                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
928    
929                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
930                                    // determine the end position within the loop first,
931                                    // read forward from that 'end' and finally after
932                                    // reading, swap all sample frames so it reflects
933                                    // backward playback
934    
935                                    unsigned long swapareastart       = totalreadsamples;
936                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
937                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
938                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
939    
940                                    SetPos(reverseplaybackend);
941    
942                                    // read samples for backward playback
943                                    do {
944                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
945                                        samplestoreadinloop -= readsamples;
946                                        samplestoread       -= readsamples;
947                                        totalreadsamples    += readsamples;
948                                    } while (samplestoreadinloop && readsamples);
949    
950                                    SetPos(reverseplaybackend); // pretend we really read backwards
951    
952                                    if (reverseplaybackend == loop.LoopStart) {
953                                        pPlaybackState->loop_cycles_left--;
954                                        pPlaybackState->reverse = false;
955                                    }
956    
957                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
958                                  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!
959                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
960                              }                              }
961                            } while (samplestoread && readsamples);
962                            break;
963                        }
964    
965                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
966                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
967                          }                          if (!pPlaybackState->reverse) do {
968                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
969                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
970                  }                              samplestoread    -= readsamples;
971                                totalreadsamples += readsamples;
972                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
973                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
974                      if (!pPlaybackState->reverse) do {                                  break;
975                          samplestoloopend  = this->LoopEnd - GetPos();                              }
976                          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);  
977    
978                      if (!samplestoread) break;                          if (!samplestoread) break;
979    
980                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
981                      // determine the end position within the loop first,                          // determine the end position within the loop first,
982                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
983                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
984                      // backward playback                          // backward playback
985    
986                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
987                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
988                      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)
989                                                                                : samplestoread;                                                                                    : samplestoread;
990                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
991    
992                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
993    
994                      // read samples for backward playback                          // read samples for backward playback
995                      do {                          do {
996                          // 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
997                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
998                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
999                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1000                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1001                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1002                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1003                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1004                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1005                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1006                          }                              }
1007                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1008    
1009                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1010    
1011                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1012                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1013                      break;                          break;
1014                  }                      }
1015    
1016                  default: case loop_type_normal: {                      default: case loop_type_normal: {
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(samplestoread, samplestoloopend));                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1022                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1023                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1024                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1025                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1026                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1027                          }                              }
1028                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1029                      break;                          break;
1030                        }
1031                  }                  }
1032              }              }
1033          }          }
1034    
1035          // read on without looping          // read on without looping
1036          if (samplestoread) do {          if (samplestoread) do {
1037              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1038              samplestoread    -= readsamples;              samplestoread    -= readsamples;
1039              totalreadsamples += readsamples;              totalreadsamples += readsamples;
1040          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 495  namespace gig { Line 1053  namespace gig {
1053       * 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,
1054       * thus for disk streaming.       * thus for disk streaming.
1055       *       *
1056         * <b>Caution:</b> If you are using more than one streaming thread, you
1057         * have to use an external decompression buffer for <b>EACH</b>
1058         * streaming thread to avoid race conditions and crashes!
1059         *
1060         * For 16 bit samples, the data in the buffer will be int16_t
1061         * (using native endianness). For 24 bit, the buffer will
1062         * contain three bytes per sample, little-endian.
1063         *
1064       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1065       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1066         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
1067       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1068       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
1069       */       */
1070      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1071          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1072          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?          if (!Compressed) {
1073          else { //FIXME: no support for mono compressed samples yet, are there any?              if (BitDepth == 24) {
1074                    return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1075                }
1076                else { // 16 bit
1077                    // (pCkData->Read does endian correction)
1078                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1079                                         : pCkData->Read(pBuffer, SampleCount, 2);
1080                }
1081            }
1082            else {
1083              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1084              //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
1085              // 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  
1086                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1087                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1088                            copysamples;                            copysamples, skipsamples,
1089              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
1090              this->FrameOffset = 0;              this->FrameOffset = 0;
1091    
1092              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1093                  // local buffer reallocation - hope this won't happen  
1094                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
1095                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
1096                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1097                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
1098                    remainingsamples = SampleCount;
1099                    assumedsize      = GuessSize(SampleCount);
1100              }              }
1101    
1102              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1103              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1104              int16_t* pDst = (int16_t*) pBuffer;              uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1105              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1106    
1107              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
1108                    unsigned long framesamples = SamplesPerFrame;
1109                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1110                  if (remainingbytes < 8194) {  
1111                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
1112                          this->SamplePos = this->SamplesTotal;  
1113                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
1114                      }                      mode_r = *pSrc++;
1115                      assumedsize    = remainingsamples;                      framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1116                      assumedsize    = (assumedsize << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)                      rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1117                                       (assumedsize >> 10) + // 10 bytes header per 2048 sample points                      nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1118                                       8194;                 // at least one worst case sample frame                      if (remainingbytes < framebytes) { // last frame in sample
1119                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          framesamples = SamplesInLastFrame;
1120                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                          if (mode_l == 4 && (framesamples & 1)) {
1121                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                              rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1122                      pSrc = (int8_t*) this->pDecompressionBuffer;                          }
1123                            else {
1124                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1125                            }
1126                        }
1127                    }
1128                    else {
1129                        framebytes = bytesPerFrame[mode_l] + 1;
1130                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1131                        if (remainingbytes < framebytes) {
1132                            framesamples = SamplesInLastFrame;
1133                        }
1134                  }                  }
1135    
1136                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
1137                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
1138                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
1139                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
1140                            skipsamples = currentframeoffset;
1141                        }
1142                        else {
1143                            copysamples = 0;
1144                            skipsamples = framesamples;
1145                        }
1146                  }                  }
1147                  else {                  else {
1148                        // This frame has enough data for pBuffer, but not
1149                        // all of the frame is needed. Set file position
1150                        // to start of this frame for next call to Read.
1151                      copysamples = remainingsamples;                      copysamples = remainingsamples;
1152                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
1153                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1154                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
1155                      }                  }
1156                      else {                  remainingsamples -= copysamples;
1157    
1158                    if (remainingbytes > framebytes) {
1159                        remainingbytes -= framebytes;
1160                        if (remainingsamples == 0 &&
1161                            currentframeoffset + copysamples == framesamples) {
1162                            // This frame has enough data for pBuffer, and
1163                            // all of the frame is needed. Set file
1164                            // position to start of next frame for next
1165                            // call to Read. FrameOffset is 0.
1166                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
1167                      }                      }
1168                  }                  }
1169                    else remainingbytes = 0;
1170    
1171                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
1172                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
1173                  switch (compressionmode) {                  if (copysamples == 0) {
1174                      case 1: // left channel compressed                      // skip this frame
1175                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
1176                          if (!remainingsamples && copysamples == 2048)                  }
1177                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
1178                        const unsigned char* const param_l = pSrc;
1179                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
1180                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
1181                          while (currentframeoffset) {  
1182                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
1183                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
1184                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
1185                              currentframeoffset--;  
1186                          }                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1187                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
1188                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1189                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
1190                              *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  
1191                          }                          }
1192                          while (copysamples) {                          else { // Mono
1193                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1194                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
1195                              right  -= dright;                              pDst24 += copysamples * 3;
                             *pDst = right; pDst++;  
                             copysamples--;  
1196                          }                          }
1197                          break;                      }
1198                      case 257: // both channels compressed                      else { // 16 bit
1199                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
1200                          if (!remainingsamples && copysamples == 2048)  
1201                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
1202                            if (Channels == 2) { // Stereo
1203                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
1204                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
1205                          right  = *(int16_t*)pSrc; pSrc+=2;  
1206                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
1207                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1208                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1209                              left   -= dleft;                                           skipsamples, copysamples);
1210                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
1211                          }                          }
1212                          while (copysamples) {                          else { // Mono
1213                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
1214                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1215                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
1216                          }                          }
1217                          break;                      }
1218                      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;  
1219                  }                  }
1220              }  
1221                    // reload from disk to local buffer if needed
1222                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1223                        assumedsize    = GuessSize(remainingsamples);
1224                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1225                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1226                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1227                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1228                    }
1229                } // while
1230    
1231              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
1232              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1233              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
1234          }          }
1235      }      }
1236    
1237        /** @brief Write sample wave data.
1238         *
1239         * Writes \a SampleCount number of sample points from the buffer pointed
1240         * by \a pBuffer and increments the position within the sample. Use this
1241         * method to directly write the sample data to disk, i.e. if you don't
1242         * want or cannot load the whole sample data into RAM.
1243         *
1244         * You have to Resize() the sample to the desired size and call
1245         * File::Save() <b>before</b> using Write().
1246         *
1247         * Note: there is currently no support for writing compressed samples.
1248         *
1249         * For 16 bit samples, the data in the source buffer should be
1250         * int16_t (using native endianness). For 24 bit, the buffer
1251         * should contain three bytes per sample, little-endian.
1252         *
1253         * @param pBuffer     - source buffer
1254         * @param SampleCount - number of sample points to write
1255         * @throws DLS::Exception if current sample size is too small
1256         * @throws gig::Exception if sample is compressed
1257         * @see DLS::LoadSampleData()
1258         */
1259        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1260            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1261    
1262            // if this is the first write in this sample, reset the
1263            // checksum calculator
1264            if (pCkData->GetPos() == 0) {
1265                __resetCRC(crc);
1266            }
1267            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1268            unsigned long res;
1269            if (BitDepth == 24) {
1270                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1271            } else { // 16 bit
1272                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1273                                    : pCkData->Write(pBuffer, SampleCount, 2);
1274            }
1275            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1276    
1277            // if this is the last write, update the checksum chunk in the
1278            // file
1279            if (pCkData->GetPos() == pCkData->GetSize()) {
1280                File* pFile = static_cast<File*>(GetParent());
1281                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1282            }
1283            return res;
1284        }
1285    
1286        /**
1287         * Allocates a decompression buffer for streaming (compressed) samples
1288         * with Sample::Read(). If you are using more than one streaming thread
1289         * in your application you <b>HAVE</b> to create a decompression buffer
1290         * for <b>EACH</b> of your streaming threads and provide it with the
1291         * Sample::Read() call in order to avoid race conditions and crashes.
1292         *
1293         * You should free the memory occupied by the allocated buffer(s) once
1294         * you don't need one of your streaming threads anymore by calling
1295         * DestroyDecompressionBuffer().
1296         *
1297         * @param MaxReadSize - the maximum size (in sample points) you ever
1298         *                      expect to read with one Read() call
1299         * @returns allocated decompression buffer
1300         * @see DestroyDecompressionBuffer()
1301         */
1302        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1303            buffer_t result;
1304            const double worstCaseHeaderOverhead =
1305                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1306            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1307            result.pStart            = new int8_t[result.Size];
1308            result.NullExtensionSize = 0;
1309            return result;
1310        }
1311    
1312        /**
1313         * Free decompression buffer, previously created with
1314         * CreateDecompressionBuffer().
1315         *
1316         * @param DecompressionBuffer - previously allocated decompression
1317         *                              buffer to free
1318         */
1319        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1320            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1321                delete[] (int8_t*) DecompressionBuffer.pStart;
1322                DecompressionBuffer.pStart = NULL;
1323                DecompressionBuffer.Size   = 0;
1324                DecompressionBuffer.NullExtensionSize = 0;
1325            }
1326        }
1327    
1328        /**
1329         * Returns pointer to the Group this Sample belongs to. In the .gig
1330         * format a sample always belongs to one group. If it wasn't explicitly
1331         * assigned to a certain group, it will be automatically assigned to a
1332         * default group.
1333         *
1334         * @returns Sample's Group (never NULL)
1335         */
1336        Group* Sample::GetGroup() const {
1337            return pGroup;
1338        }
1339    
1340      Sample::~Sample() {      Sample::~Sample() {
1341          Instances--;          Instances--;
1342          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
1343                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1344                InternalDecompressionBuffer.pStart = NULL;
1345                InternalDecompressionBuffer.Size   = 0;
1346            }
1347          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1348          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1349      }      }
# Line 673  namespace gig { Line 1356  namespace gig {
1356      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1357      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1358    
1359      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1360          Instances++;          Instances++;
1361    
1362          memcpy(&Crossfade, &SamplerOptions, 4);          pSample = NULL;
1363            pRegion = pParent;
1364    
1365            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1366            else memset(&Crossfade, 0, 4);
1367    
1368          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1369    
1370          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1371          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1372          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1373          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1374          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1375          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1376          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1377          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1378          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1379          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1380          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1381          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1382          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1383          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1384          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1385          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1386          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1387          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1388          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1389          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1390          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1391          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1392          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1393          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1394          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1395          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1396          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1397          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1398          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1399          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1400          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1401          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1402          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1403          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1404          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1405          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1406          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1407          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1408          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1409          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1410          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1411          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1412          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1413          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1414          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1415          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1416          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1417          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1418          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1419          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1420          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1421          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1422              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1423              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1424          }                  VelocityResponseDepth = velocityresponse;
1425          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1426              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1427              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1428          }              } else if (velocityresponse < 15) {
1429          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1430              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1431              VelocityResponseDepth = velocityresponse - 10;              } else {
1432                    VelocityResponseCurve = curve_type_unknown;
1433                    VelocityResponseDepth = 0;
1434                }
1435                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1436                if (releasevelocityresponse < 5) {
1437                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1438                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1439                } else if (releasevelocityresponse < 10) {
1440                    ReleaseVelocityResponseCurve = curve_type_linear;
1441                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1442                } else if (releasevelocityresponse < 15) {
1443                    ReleaseVelocityResponseCurve = curve_type_special;
1444                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1445                } else {
1446                    ReleaseVelocityResponseCurve = curve_type_unknown;
1447                    ReleaseVelocityResponseDepth = 0;
1448                }
1449                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1450                AttenuationControllerThreshold = _3ewa->ReadInt8();
1451                _3ewa->ReadInt32(); // unknown
1452                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1453                _3ewa->ReadInt16(); // unknown
1454                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1455                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1456                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1457                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1458                else                                       DimensionBypass = dim_bypass_ctrl_none;
1459                uint8_t pan = _3ewa->ReadUint8();
1460                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1461                SelfMask = _3ewa->ReadInt8() & 0x01;
1462                _3ewa->ReadInt8(); // unknown
1463                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1464                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1465                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1466                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1467                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1468                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1469                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1470                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1471                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1472                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1473                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1474                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1475                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1476                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1477                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1478                                                            : vcf_res_ctrl_none;
1479                uint16_t eg3depth = _3ewa->ReadUint16();
1480                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1481                                            : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1482                _3ewa->ReadInt16(); // unknown
1483                ChannelOffset = _3ewa->ReadUint8() / 4;
1484                uint8_t regoptions = _3ewa->ReadUint8();
1485                MSDecode           = regoptions & 0x01; // bit 0
1486                SustainDefeat      = regoptions & 0x02; // bit 1
1487                _3ewa->ReadInt16(); // unknown
1488                VelocityUpperLimit = _3ewa->ReadInt8();
1489                _3ewa->ReadInt8(); // unknown
1490                _3ewa->ReadInt16(); // unknown
1491                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1492                _3ewa->ReadInt8(); // unknown
1493                _3ewa->ReadInt8(); // unknown
1494                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1495                uint8_t vcfcutoff = _3ewa->ReadUint8();
1496                VCFEnabled = vcfcutoff & 0x80; // bit 7
1497                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1498                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1499                uint8_t vcfvelscale = _3ewa->ReadUint8();
1500                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1501                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1502                _3ewa->ReadInt8(); // unknown
1503                uint8_t vcfresonance = _3ewa->ReadUint8();
1504                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1505                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1506                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1507                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1508                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1509                uint8_t vcfvelocity = _3ewa->ReadUint8();
1510                VCFVelocityDynamicRange = vcfvelocity % 5;
1511                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1512                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1513                if (VCFType == vcf_type_lowpass) {
1514                    if (lfo3ctrl & 0x40) // bit 6
1515                        VCFType = vcf_type_lowpassturbo;
1516                }
1517                if (_3ewa->RemainingBytes() >= 8) {
1518                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1519                } else {
1520                    memset(DimensionUpperLimits, 0, 8);
1521                }
1522            } else { // '3ewa' chunk does not exist yet
1523                // use default values
1524                LFO3Frequency                   = 1.0;
1525                EG3Attack                       = 0.0;
1526                LFO1InternalDepth               = 0;
1527                LFO3InternalDepth               = 0;
1528                LFO1ControlDepth                = 0;
1529                LFO3ControlDepth                = 0;
1530                EG1Attack                       = 0.0;
1531                EG1Decay1                       = 0.005;
1532                EG1Sustain                      = 1000;
1533                EG1Release                      = 0.3;
1534                EG1Controller.type              = eg1_ctrl_t::type_none;
1535                EG1Controller.controller_number = 0;
1536                EG1ControllerInvert             = false;
1537                EG1ControllerAttackInfluence    = 0;
1538                EG1ControllerDecayInfluence     = 0;
1539                EG1ControllerReleaseInfluence   = 0;
1540                EG2Controller.type              = eg2_ctrl_t::type_none;
1541                EG2Controller.controller_number = 0;
1542                EG2ControllerInvert             = false;
1543                EG2ControllerAttackInfluence    = 0;
1544                EG2ControllerDecayInfluence     = 0;
1545                EG2ControllerReleaseInfluence   = 0;
1546                LFO1Frequency                   = 1.0;
1547                EG2Attack                       = 0.0;
1548                EG2Decay1                       = 0.005;
1549                EG2Sustain                      = 1000;
1550                EG2Release                      = 0.3;
1551                LFO2ControlDepth                = 0;
1552                LFO2Frequency                   = 1.0;
1553                LFO2InternalDepth               = 0;
1554                EG1Decay2                       = 0.0;
1555                EG1InfiniteSustain              = true;
1556                EG1PreAttack                    = 0;
1557                EG2Decay2                       = 0.0;
1558                EG2InfiniteSustain              = true;
1559                EG2PreAttack                    = 0;
1560                VelocityResponseCurve           = curve_type_nonlinear;
1561                VelocityResponseDepth           = 3;
1562                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1563                ReleaseVelocityResponseDepth    = 3;
1564                VelocityResponseCurveScaling    = 32;
1565                AttenuationControllerThreshold  = 0;
1566                SampleStartOffset               = 0;
1567                PitchTrack                      = true;
1568                DimensionBypass                 = dim_bypass_ctrl_none;
1569                Pan                             = 0;
1570                SelfMask                        = true;
1571                LFO3Controller                  = lfo3_ctrl_modwheel;
1572                LFO3Sync                        = false;
1573                InvertAttenuationController     = false;
1574                AttenuationController.type      = attenuation_ctrl_t::type_none;
1575                AttenuationController.controller_number = 0;
1576                LFO2Controller                  = lfo2_ctrl_internal;
1577                LFO2FlipPhase                   = false;
1578                LFO2Sync                        = false;
1579                LFO1Controller                  = lfo1_ctrl_internal;
1580                LFO1FlipPhase                   = false;
1581                LFO1Sync                        = false;
1582                VCFResonanceController          = vcf_res_ctrl_none;
1583                EG3Depth                        = 0;
1584                ChannelOffset                   = 0;
1585                MSDecode                        = false;
1586                SustainDefeat                   = false;
1587                VelocityUpperLimit              = 0;
1588                ReleaseTriggerDecay             = 0;
1589                EG1Hold                         = false;
1590                VCFEnabled                      = false;
1591                VCFCutoff                       = 0;
1592                VCFCutoffController             = vcf_cutoff_ctrl_none;
1593                VCFCutoffControllerInvert       = false;
1594                VCFVelocityScale                = 0;
1595                VCFResonance                    = 0;
1596                VCFResonanceDynamic             = false;
1597                VCFKeyboardTracking             = false;
1598                VCFKeyboardTrackingBreakpoint   = 0;
1599                VCFVelocityDynamicRange         = 0x04;
1600                VCFVelocityCurve                = curve_type_linear;
1601                VCFType                         = vcf_type_lowpass;
1602                memset(DimensionUpperLimits, 127, 8);
1603          }          }
1604          else {  
1605              VelocityResponseCurve = curve_type_unknown;          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1606              VelocityResponseDepth = 0;                                                       VelocityResponseDepth,
1607                                                         VelocityResponseCurveScaling);
1608    
1609            pVelocityReleaseTable = GetReleaseVelocityTable(
1610                                        ReleaseVelocityResponseCurve,
1611                                        ReleaseVelocityResponseDepth
1612                                    );
1613    
1614            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1615                                                          VCFVelocityDynamicRange,
1616                                                          VCFVelocityScale,
1617                                                          VCFCutoffController);
1618    
1619            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1620            VelocityTable = 0;
1621        }
1622    
1623        /*
1624         * Constructs a DimensionRegion by copying all parameters from
1625         * another DimensionRegion
1626         */
1627        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1628            Instances++;
1629            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1630            *this = src; // default memberwise shallow copy of all parameters
1631            pParentList = _3ewl; // restore the chunk pointer
1632    
1633            // deep copy of owned structures
1634            if (src.VelocityTable) {
1635                VelocityTable = new uint8_t[128];
1636                for (int k = 0 ; k < 128 ; k++)
1637                    VelocityTable[k] = src.VelocityTable[k];
1638          }          }
1639          uint8_t releasevelocityresponse = _3ewa->ReadUint8();          if (src.pSampleLoops) {
1640          if (releasevelocityresponse < 5) {              pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1641              ReleaseVelocityResponseCurve = curve_type_nonlinear;              for (int k = 0 ; k < src.SampleLoops ; k++)
1642              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;  
1643          }          }
1644          else {      }
1645              ReleaseVelocityResponseCurve = curve_type_unknown;      
1646              ReleaseVelocityResponseDepth = 0;      /**
1647         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1648         * and assign it to this object.
1649         *
1650         * Note that all sample pointers referenced by @a orig are simply copied as
1651         * memory address. Thus the respective samples are shared, not duplicated!
1652         *
1653         * @param orig - original DimensionRegion object to be copied from
1654         */
1655        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1656            CopyAssign(orig, NULL);
1657        }
1658    
1659        /**
1660         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1661         * and assign it to this object.
1662         *
1663         * @param orig - original DimensionRegion object to be copied from
1664         * @param mSamples - crosslink map between the foreign file's samples and
1665         *                   this file's samples
1666         */
1667        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1668            // delete all allocated data first
1669            if (VelocityTable) delete [] VelocityTable;
1670            if (pSampleLoops) delete [] pSampleLoops;
1671            
1672            // backup parent list pointer
1673            RIFF::List* p = pParentList;
1674            
1675            gig::Sample* pOriginalSample = pSample;
1676            gig::Region* pOriginalRegion = pRegion;
1677            
1678            //NOTE: copy code copied from assignment constructor above, see comment there as well
1679            
1680            *this = *orig; // default memberwise shallow copy of all parameters
1681            
1682            // restore members that shall not be altered
1683            pParentList = p; // restore the chunk pointer
1684            pRegion = pOriginalRegion;
1685            
1686            // only take the raw sample reference reference if the
1687            // two DimensionRegion objects are part of the same file
1688            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1689                pSample = pOriginalSample;
1690            }
1691            
1692            if (mSamples && mSamples->count(orig->pSample)) {
1693                pSample = mSamples->find(orig->pSample)->second;
1694          }          }
         VelocityResponseCurveScaling = _3ewa->ReadUint8();  
         AttenuationControllerThreshold = _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  
         InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
         AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
         uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
         LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
         LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
         LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
         bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
         uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
         LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
         LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
         LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
         VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
                                                     : vcf_res_ctrl_none;  
         uint16_t eg3depth = _3ewa->ReadUint16();  
         EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
                                       : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */  
         _3ewa->ReadInt16(); // unknown  
         ChannelOffset = _3ewa->ReadUint8() / 4;  
         uint8_t regoptions = _3ewa->ReadUint8();  
         MSDecode           = regoptions & 0x01; // bit 0  
         SustainDefeat      = regoptions & 0x02; // bit 1  
         _3ewa->ReadInt16(); // unknown  
         VelocityUpperLimit = _3ewa->ReadInt8();  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt16(); // unknown  
         ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
1695    
1696          // 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
1697          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          if (orig->VelocityTable) {
1698          if (pVelocityTables->count(tableKey)) { // if key exists              VelocityTable = new uint8_t[128];
1699              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              for (int k = 0 ; k < 128 ; k++)
1700                    VelocityTable[k] = orig->VelocityTable[k];
1701          }          }
1702          else {          if (orig->pSampleLoops) {
1703              pVelocityAttenuationTable = new double[128];              pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1704              switch (VelocityResponseCurve) { // calculate the new table              for (int k = 0 ; k < orig->SampleLoops ; k++)
1705                    pSampleLoops[k] = orig->pSampleLoops[k];
1706            }
1707        }
1708    
1709        /**
1710         * Updates the respective member variable and updates @c SampleAttenuation
1711         * which depends on this value.
1712         */
1713        void DimensionRegion::SetGain(int32_t gain) {
1714            DLS::Sampler::SetGain(gain);
1715            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1716        }
1717    
1718        /**
1719         * Apply dimension region settings to the respective RIFF chunks. You
1720         * have to call File::Save() to make changes persistent.
1721         *
1722         * Usually there is absolutely no need to call this method explicitly.
1723         * It will be called automatically when File::Save() was called.
1724         *
1725         * @param pProgress - callback function for progress notification
1726         */
1727        void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1728            // first update base class's chunk
1729            DLS::Sampler::UpdateChunks(pProgress);
1730    
1731            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1732            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1733            pData[12] = Crossfade.in_start;
1734            pData[13] = Crossfade.in_end;
1735            pData[14] = Crossfade.out_start;
1736            pData[15] = Crossfade.out_end;
1737    
1738            // make sure '3ewa' chunk exists
1739            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1740            if (!_3ewa) {
1741                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1742                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1743                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1744            }
1745            pData = (uint8_t*) _3ewa->LoadChunkData();
1746    
1747            // update '3ewa' chunk with DimensionRegion's current settings
1748    
1749            const uint32_t chunksize = _3ewa->GetNewSize();
1750            store32(&pData[0], chunksize); // unknown, always chunk size?
1751    
1752            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1753            store32(&pData[4], lfo3freq);
1754    
1755            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1756            store32(&pData[8], eg3attack);
1757    
1758            // next 2 bytes unknown
1759    
1760            store16(&pData[14], LFO1InternalDepth);
1761    
1762            // next 2 bytes unknown
1763    
1764            store16(&pData[18], LFO3InternalDepth);
1765    
1766            // next 2 bytes unknown
1767    
1768            store16(&pData[22], LFO1ControlDepth);
1769    
1770            // next 2 bytes unknown
1771    
1772            store16(&pData[26], LFO3ControlDepth);
1773    
1774            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1775            store32(&pData[28], eg1attack);
1776    
1777            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1778            store32(&pData[32], eg1decay1);
1779    
1780            // next 2 bytes unknown
1781    
1782            store16(&pData[38], EG1Sustain);
1783    
1784            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1785            store32(&pData[40], eg1release);
1786    
1787            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1788            pData[44] = eg1ctl;
1789    
1790            const uint8_t eg1ctrloptions =
1791                (EG1ControllerInvert ? 0x01 : 0x00) |
1792                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1793                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1794                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1795            pData[45] = eg1ctrloptions;
1796    
1797            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1798            pData[46] = eg2ctl;
1799    
1800            const uint8_t eg2ctrloptions =
1801                (EG2ControllerInvert ? 0x01 : 0x00) |
1802                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1803                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1804                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1805            pData[47] = eg2ctrloptions;
1806    
1807            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1808            store32(&pData[48], lfo1freq);
1809    
1810            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1811            store32(&pData[52], eg2attack);
1812    
1813            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1814            store32(&pData[56], eg2decay1);
1815    
1816            // next 2 bytes unknown
1817    
1818            store16(&pData[62], EG2Sustain);
1819    
1820            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1821            store32(&pData[64], eg2release);
1822    
1823            // next 2 bytes unknown
1824    
1825            store16(&pData[70], LFO2ControlDepth);
1826    
1827            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1828            store32(&pData[72], lfo2freq);
1829    
1830            // next 2 bytes unknown
1831    
1832            store16(&pData[78], LFO2InternalDepth);
1833    
1834            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1835            store32(&pData[80], eg1decay2);
1836    
1837            // next 2 bytes unknown
1838    
1839            store16(&pData[86], EG1PreAttack);
1840    
1841            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1842            store32(&pData[88], eg2decay2);
1843    
1844            // next 2 bytes unknown
1845    
1846            store16(&pData[94], EG2PreAttack);
1847    
1848            {
1849                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1850                uint8_t velocityresponse = VelocityResponseDepth;
1851                switch (VelocityResponseCurve) {
1852                  case curve_type_nonlinear:                  case curve_type_nonlinear:
1853                      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;  
1854                  case curve_type_linear:                  case curve_type_linear:
1855                      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;  
                     }  
1856                      break;                      break;
1857                  case curve_type_special:                  case curve_type_special:
1858                      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;  
                     }  
1859                      break;                      break;
1860                  case curve_type_unknown:                  case curve_type_unknown:
1861                  default:                  default:
1862                      throw gig::Exception("Unknown transform curve type.");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1863                }
1864                pData[96] = velocityresponse;
1865            }
1866    
1867            {
1868                if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1869                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1870                switch (ReleaseVelocityResponseCurve) {
1871                    case curve_type_nonlinear:
1872                        break;
1873                    case curve_type_linear:
1874                        releasevelocityresponse += 5;
1875                        break;
1876                    case curve_type_special:
1877                        releasevelocityresponse += 10;
1878                        break;
1879                    case curve_type_unknown:
1880                    default:
1881                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1882                }
1883                pData[97] = releasevelocityresponse;
1884            }
1885    
1886            pData[98] = VelocityResponseCurveScaling;
1887    
1888            pData[99] = AttenuationControllerThreshold;
1889    
1890            // next 4 bytes unknown
1891    
1892            store16(&pData[104], SampleStartOffset);
1893    
1894            // next 2 bytes unknown
1895    
1896            {
1897                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1898                switch (DimensionBypass) {
1899                    case dim_bypass_ctrl_94:
1900                        pitchTrackDimensionBypass |= 0x10;
1901                        break;
1902                    case dim_bypass_ctrl_95:
1903                        pitchTrackDimensionBypass |= 0x20;
1904                        break;
1905                    case dim_bypass_ctrl_none:
1906                        //FIXME: should we set anything here?
1907                        break;
1908                    default:
1909                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1910              }              }
1911              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              pData[108] = pitchTrackDimensionBypass;
1912            }
1913    
1914            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1915            pData[109] = pan;
1916    
1917            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1918            pData[110] = selfmask;
1919    
1920            // next byte unknown
1921    
1922            {
1923                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1924                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1925                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1926                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1927                pData[112] = lfo3ctrl;
1928            }
1929    
1930            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1931            pData[113] = attenctl;
1932    
1933            {
1934                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1935                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1936                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1937                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1938                pData[114] = lfo2ctrl;
1939            }
1940    
1941            {
1942                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1943                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1944                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1945                if (VCFResonanceController != vcf_res_ctrl_none)
1946                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1947                pData[115] = lfo1ctrl;
1948            }
1949    
1950            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1951                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1952            store16(&pData[116], eg3depth);
1953    
1954            // next 2 bytes unknown
1955    
1956            const uint8_t channeloffset = ChannelOffset * 4;
1957            pData[120] = channeloffset;
1958    
1959            {
1960                uint8_t regoptions = 0;
1961                if (MSDecode)      regoptions |= 0x01; // bit 0
1962                if (SustainDefeat) regoptions |= 0x02; // bit 1
1963                pData[121] = regoptions;
1964            }
1965    
1966            // next 2 bytes unknown
1967    
1968            pData[124] = VelocityUpperLimit;
1969    
1970            // next 3 bytes unknown
1971    
1972            pData[128] = ReleaseTriggerDecay;
1973    
1974            // next 2 bytes unknown
1975    
1976            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1977            pData[131] = eg1hold;
1978    
1979            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1980                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
1981            pData[132] = vcfcutoff;
1982    
1983            pData[133] = VCFCutoffController;
1984    
1985            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1986                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
1987            pData[134] = vcfvelscale;
1988    
1989            // next byte unknown
1990    
1991            const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1992                                         (VCFResonance & 0x7f); /* lower 7 bits */
1993            pData[136] = vcfresonance;
1994    
1995            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1996                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1997            pData[137] = vcfbreakpoint;
1998    
1999            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2000                                        VCFVelocityCurve * 5;
2001            pData[138] = vcfvelocity;
2002    
2003            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2004            pData[139] = vcftype;
2005    
2006            if (chunksize >= 148) {
2007                memcpy(&pData[140], DimensionUpperLimits, 8);
2008          }          }
2009      }      }
2010        
2011        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2012            curve_type_t curveType = releaseVelocityResponseCurve;
2013            uint8_t depth = releaseVelocityResponseDepth;
2014            // this models a strange behaviour or bug in GSt: two of the
2015            // velocity response curves for release time are not used even
2016            // if specified, instead another curve is chosen.
2017            if ((curveType == curve_type_nonlinear && depth == 0) ||
2018                (curveType == curve_type_special   && depth == 4)) {
2019                curveType = curve_type_nonlinear;
2020                depth = 3;
2021            }
2022            return GetVelocityTable(curveType, depth, 0);
2023        }
2024    
2025        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2026                                                        uint8_t vcfVelocityDynamicRange,
2027                                                        uint8_t vcfVelocityScale,
2028                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2029        {
2030            curve_type_t curveType = vcfVelocityCurve;
2031            uint8_t depth = vcfVelocityDynamicRange;
2032            // even stranger GSt: two of the velocity response curves for
2033            // filter cutoff are not used, instead another special curve
2034            // is chosen. This curve is not used anywhere else.
2035            if ((curveType == curve_type_nonlinear && depth == 0) ||
2036                (curveType == curve_type_special   && depth == 4)) {
2037                curveType = curve_type_special;
2038                depth = 5;
2039            }
2040            return GetVelocityTable(curveType, depth,
2041                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2042                                        ? vcfVelocityScale : 0);
2043        }
2044    
2045        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2046        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2047        {
2048            double* table;
2049            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2050            if (pVelocityTables->count(tableKey)) { // if key exists
2051                table = (*pVelocityTables)[tableKey];
2052            }
2053            else {
2054                table = CreateVelocityTable(curveType, depth, scaling);
2055                (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2056            }
2057            return table;
2058        }
2059    
2060        Region* DimensionRegion::GetParent() const {
2061            return pRegion;
2062        }
2063    
2064    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2065    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2066    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2067    //#pragma GCC diagnostic push
2068    //#pragma GCC diagnostic error "-Wswitch"
2069    
2070      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2071          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2072          switch (EncodedController) {          switch (EncodedController) {
# Line 886  namespace gig { Line 2083  namespace gig {
2083                  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;                  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2084                  decodedcontroller.controller_number = 0;                  decodedcontroller.controller_number = 0;
2085                  break;                  break;
2086                
2087              // ordinary MIDI control change controller              // ordinary MIDI control change controller
2088              case _lev_ctrl_modwheel:              case _lev_ctrl_modwheel:
2089                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
# Line 980  namespace gig { Line 2177  namespace gig {
2177                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2179                  break;                  break;
2180                
2181                // format extension (these controllers are so far only supported by
2182                // LinuxSampler & gigedit) they will *NOT* work with
2183                // Gigasampler/GigaStudio !
2184                case _lev_ctrl_CC3_EXT:
2185                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186                    decodedcontroller.controller_number = 3;
2187                    break;
2188                case _lev_ctrl_CC6_EXT:
2189                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190                    decodedcontroller.controller_number = 6;
2191                    break;
2192                case _lev_ctrl_CC7_EXT:
2193                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194                    decodedcontroller.controller_number = 7;
2195                    break;
2196                case _lev_ctrl_CC8_EXT:
2197                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198                    decodedcontroller.controller_number = 8;
2199                    break;
2200                case _lev_ctrl_CC9_EXT:
2201                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202                    decodedcontroller.controller_number = 9;
2203                    break;
2204                case _lev_ctrl_CC10_EXT:
2205                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206                    decodedcontroller.controller_number = 10;
2207                    break;
2208                case _lev_ctrl_CC11_EXT:
2209                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2210                    decodedcontroller.controller_number = 11;
2211                    break;
2212                case _lev_ctrl_CC14_EXT:
2213                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214                    decodedcontroller.controller_number = 14;
2215                    break;
2216                case _lev_ctrl_CC15_EXT:
2217                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218                    decodedcontroller.controller_number = 15;
2219                    break;
2220                case _lev_ctrl_CC20_EXT:
2221                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222                    decodedcontroller.controller_number = 20;
2223                    break;
2224                case _lev_ctrl_CC21_EXT:
2225                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226                    decodedcontroller.controller_number = 21;
2227                    break;
2228                case _lev_ctrl_CC22_EXT:
2229                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230                    decodedcontroller.controller_number = 22;
2231                    break;
2232                case _lev_ctrl_CC23_EXT:
2233                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234                    decodedcontroller.controller_number = 23;
2235                    break;
2236                case _lev_ctrl_CC24_EXT:
2237                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238                    decodedcontroller.controller_number = 24;
2239                    break;
2240                case _lev_ctrl_CC25_EXT:
2241                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242                    decodedcontroller.controller_number = 25;
2243                    break;
2244                case _lev_ctrl_CC26_EXT:
2245                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246                    decodedcontroller.controller_number = 26;
2247                    break;
2248                case _lev_ctrl_CC27_EXT:
2249                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250                    decodedcontroller.controller_number = 27;
2251                    break;
2252                case _lev_ctrl_CC28_EXT:
2253                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254                    decodedcontroller.controller_number = 28;
2255                    break;
2256                case _lev_ctrl_CC29_EXT:
2257                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258                    decodedcontroller.controller_number = 29;
2259                    break;
2260                case _lev_ctrl_CC30_EXT:
2261                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262                    decodedcontroller.controller_number = 30;
2263                    break;
2264                case _lev_ctrl_CC31_EXT:
2265                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2266                    decodedcontroller.controller_number = 31;
2267                    break;
2268                case _lev_ctrl_CC68_EXT:
2269                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270                    decodedcontroller.controller_number = 68;
2271                    break;
2272                case _lev_ctrl_CC69_EXT:
2273                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274                    decodedcontroller.controller_number = 69;
2275                    break;
2276                case _lev_ctrl_CC70_EXT:
2277                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278                    decodedcontroller.controller_number = 70;
2279                    break;
2280                case _lev_ctrl_CC71_EXT:
2281                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282                    decodedcontroller.controller_number = 71;
2283                    break;
2284                case _lev_ctrl_CC72_EXT:
2285                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286                    decodedcontroller.controller_number = 72;
2287                    break;
2288                case _lev_ctrl_CC73_EXT:
2289                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290                    decodedcontroller.controller_number = 73;
2291                    break;
2292                case _lev_ctrl_CC74_EXT:
2293                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294                    decodedcontroller.controller_number = 74;
2295                    break;
2296                case _lev_ctrl_CC75_EXT:
2297                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298                    decodedcontroller.controller_number = 75;
2299                    break;
2300                case _lev_ctrl_CC76_EXT:
2301                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302                    decodedcontroller.controller_number = 76;
2303                    break;
2304                case _lev_ctrl_CC77_EXT:
2305                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306                    decodedcontroller.controller_number = 77;
2307                    break;
2308                case _lev_ctrl_CC78_EXT:
2309                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310                    decodedcontroller.controller_number = 78;
2311                    break;
2312                case _lev_ctrl_CC79_EXT:
2313                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314                    decodedcontroller.controller_number = 79;
2315                    break;
2316                case _lev_ctrl_CC84_EXT:
2317                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318                    decodedcontroller.controller_number = 84;
2319                    break;
2320                case _lev_ctrl_CC85_EXT:
2321                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322                    decodedcontroller.controller_number = 85;
2323                    break;
2324                case _lev_ctrl_CC86_EXT:
2325                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326                    decodedcontroller.controller_number = 86;
2327                    break;
2328                case _lev_ctrl_CC87_EXT:
2329                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330                    decodedcontroller.controller_number = 87;
2331                    break;
2332                case _lev_ctrl_CC89_EXT:
2333                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334                    decodedcontroller.controller_number = 89;
2335                    break;
2336                case _lev_ctrl_CC90_EXT:
2337                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338                    decodedcontroller.controller_number = 90;
2339                    break;
2340                case _lev_ctrl_CC96_EXT:
2341                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342                    decodedcontroller.controller_number = 96;
2343                    break;
2344                case _lev_ctrl_CC97_EXT:
2345                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346                    decodedcontroller.controller_number = 97;
2347                    break;
2348                case _lev_ctrl_CC102_EXT:
2349                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350                    decodedcontroller.controller_number = 102;
2351                    break;
2352                case _lev_ctrl_CC103_EXT:
2353                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354                    decodedcontroller.controller_number = 103;
2355                    break;
2356                case _lev_ctrl_CC104_EXT:
2357                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358                    decodedcontroller.controller_number = 104;
2359                    break;
2360                case _lev_ctrl_CC105_EXT:
2361                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362                    decodedcontroller.controller_number = 105;
2363                    break;
2364                case _lev_ctrl_CC106_EXT:
2365                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366                    decodedcontroller.controller_number = 106;
2367                    break;
2368                case _lev_ctrl_CC107_EXT:
2369                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370                    decodedcontroller.controller_number = 107;
2371                    break;
2372                case _lev_ctrl_CC108_EXT:
2373                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374                    decodedcontroller.controller_number = 108;
2375                    break;
2376                case _lev_ctrl_CC109_EXT:
2377                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378                    decodedcontroller.controller_number = 109;
2379                    break;
2380                case _lev_ctrl_CC110_EXT:
2381                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382                    decodedcontroller.controller_number = 110;
2383                    break;
2384                case _lev_ctrl_CC111_EXT:
2385                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386                    decodedcontroller.controller_number = 111;
2387                    break;
2388                case _lev_ctrl_CC112_EXT:
2389                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390                    decodedcontroller.controller_number = 112;
2391                    break;
2392                case _lev_ctrl_CC113_EXT:
2393                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394                    decodedcontroller.controller_number = 113;
2395                    break;
2396                case _lev_ctrl_CC114_EXT:
2397                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398                    decodedcontroller.controller_number = 114;
2399                    break;
2400                case _lev_ctrl_CC115_EXT:
2401                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402                    decodedcontroller.controller_number = 115;
2403                    break;
2404                case _lev_ctrl_CC116_EXT:
2405                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406                    decodedcontroller.controller_number = 116;
2407                    break;
2408                case _lev_ctrl_CC117_EXT:
2409                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410                    decodedcontroller.controller_number = 117;
2411                    break;
2412                case _lev_ctrl_CC118_EXT:
2413                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414                    decodedcontroller.controller_number = 118;
2415                    break;
2416                case _lev_ctrl_CC119_EXT:
2417                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418                    decodedcontroller.controller_number = 119;
2419                    break;
2420    
2421              // unknown controller type              // unknown controller type
2422              default:              default:
2423                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2424          }          }
2425          return decodedcontroller;          return decodedcontroller;
2426      }      }
2427        
2428    // see above (diagnostic push not supported prior GCC 4.6)
2429    //#pragma GCC diagnostic pop
2430    
2431        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2432            _lev_ctrl_t encodedcontroller;
2433            switch (DecodedController.type) {
2434                // special controller
2435                case leverage_ctrl_t::type_none:
2436                    encodedcontroller = _lev_ctrl_none;
2437                    break;
2438                case leverage_ctrl_t::type_velocity:
2439                    encodedcontroller = _lev_ctrl_velocity;
2440                    break;
2441                case leverage_ctrl_t::type_channelaftertouch:
2442                    encodedcontroller = _lev_ctrl_channelaftertouch;
2443                    break;
2444    
2445                // ordinary MIDI control change controller
2446                case leverage_ctrl_t::type_controlchange:
2447                    switch (DecodedController.controller_number) {
2448                        case 1:
2449                            encodedcontroller = _lev_ctrl_modwheel;
2450                            break;
2451                        case 2:
2452                            encodedcontroller = _lev_ctrl_breath;
2453                            break;
2454                        case 4:
2455                            encodedcontroller = _lev_ctrl_foot;
2456                            break;
2457                        case 12:
2458                            encodedcontroller = _lev_ctrl_effect1;
2459                            break;
2460                        case 13:
2461                            encodedcontroller = _lev_ctrl_effect2;
2462                            break;
2463                        case 16:
2464                            encodedcontroller = _lev_ctrl_genpurpose1;
2465                            break;
2466                        case 17:
2467                            encodedcontroller = _lev_ctrl_genpurpose2;
2468                            break;
2469                        case 18:
2470                            encodedcontroller = _lev_ctrl_genpurpose3;
2471                            break;
2472                        case 19:
2473                            encodedcontroller = _lev_ctrl_genpurpose4;
2474                            break;
2475                        case 5:
2476                            encodedcontroller = _lev_ctrl_portamentotime;
2477                            break;
2478                        case 64:
2479                            encodedcontroller = _lev_ctrl_sustainpedal;
2480                            break;
2481                        case 65:
2482                            encodedcontroller = _lev_ctrl_portamento;
2483                            break;
2484                        case 66:
2485                            encodedcontroller = _lev_ctrl_sostenutopedal;
2486                            break;
2487                        case 67:
2488                            encodedcontroller = _lev_ctrl_softpedal;
2489                            break;
2490                        case 80:
2491                            encodedcontroller = _lev_ctrl_genpurpose5;
2492                            break;
2493                        case 81:
2494                            encodedcontroller = _lev_ctrl_genpurpose6;
2495                            break;
2496                        case 82:
2497                            encodedcontroller = _lev_ctrl_genpurpose7;
2498                            break;
2499                        case 83:
2500                            encodedcontroller = _lev_ctrl_genpurpose8;
2501                            break;
2502                        case 91:
2503                            encodedcontroller = _lev_ctrl_effect1depth;
2504                            break;
2505                        case 92:
2506                            encodedcontroller = _lev_ctrl_effect2depth;
2507                            break;
2508                        case 93:
2509                            encodedcontroller = _lev_ctrl_effect3depth;
2510                            break;
2511                        case 94:
2512                            encodedcontroller = _lev_ctrl_effect4depth;
2513                            break;
2514                        case 95:
2515                            encodedcontroller = _lev_ctrl_effect5depth;
2516                            break;
2517    
2518                        // format extension (these controllers are so far only
2519                        // supported by LinuxSampler & gigedit) they will *NOT*
2520                        // work with Gigasampler/GigaStudio !
2521                        case 3:
2522                            encodedcontroller = _lev_ctrl_CC3_EXT;
2523                            break;
2524                        case 6:
2525                            encodedcontroller = _lev_ctrl_CC6_EXT;
2526                            break;
2527                        case 7:
2528                            encodedcontroller = _lev_ctrl_CC7_EXT;
2529                            break;
2530                        case 8:
2531                            encodedcontroller = _lev_ctrl_CC8_EXT;
2532                            break;
2533                        case 9:
2534                            encodedcontroller = _lev_ctrl_CC9_EXT;
2535                            break;
2536                        case 10:
2537                            encodedcontroller = _lev_ctrl_CC10_EXT;
2538                            break;
2539                        case 11:
2540                            encodedcontroller = _lev_ctrl_CC11_EXT;
2541                            break;
2542                        case 14:
2543                            encodedcontroller = _lev_ctrl_CC14_EXT;
2544                            break;
2545                        case 15:
2546                            encodedcontroller = _lev_ctrl_CC15_EXT;
2547                            break;
2548                        case 20:
2549                            encodedcontroller = _lev_ctrl_CC20_EXT;
2550                            break;
2551                        case 21:
2552                            encodedcontroller = _lev_ctrl_CC21_EXT;
2553                            break;
2554                        case 22:
2555                            encodedcontroller = _lev_ctrl_CC22_EXT;
2556                            break;
2557                        case 23:
2558                            encodedcontroller = _lev_ctrl_CC23_EXT;
2559                            break;
2560                        case 24:
2561                            encodedcontroller = _lev_ctrl_CC24_EXT;
2562                            break;
2563                        case 25:
2564                            encodedcontroller = _lev_ctrl_CC25_EXT;
2565                            break;
2566                        case 26:
2567                            encodedcontroller = _lev_ctrl_CC26_EXT;
2568                            break;
2569                        case 27:
2570                            encodedcontroller = _lev_ctrl_CC27_EXT;
2571                            break;
2572                        case 28:
2573                            encodedcontroller = _lev_ctrl_CC28_EXT;
2574                            break;
2575                        case 29:
2576                            encodedcontroller = _lev_ctrl_CC29_EXT;
2577                            break;
2578                        case 30:
2579                            encodedcontroller = _lev_ctrl_CC30_EXT;
2580                            break;
2581                        case 31:
2582                            encodedcontroller = _lev_ctrl_CC31_EXT;
2583                            break;
2584                        case 68:
2585                            encodedcontroller = _lev_ctrl_CC68_EXT;
2586                            break;
2587                        case 69:
2588                            encodedcontroller = _lev_ctrl_CC69_EXT;
2589                            break;
2590                        case 70:
2591                            encodedcontroller = _lev_ctrl_CC70_EXT;
2592                            break;
2593                        case 71:
2594                            encodedcontroller = _lev_ctrl_CC71_EXT;
2595                            break;
2596                        case 72:
2597                            encodedcontroller = _lev_ctrl_CC72_EXT;
2598                            break;
2599                        case 73:
2600                            encodedcontroller = _lev_ctrl_CC73_EXT;
2601                            break;
2602                        case 74:
2603                            encodedcontroller = _lev_ctrl_CC74_EXT;
2604                            break;
2605                        case 75:
2606                            encodedcontroller = _lev_ctrl_CC75_EXT;
2607                            break;
2608                        case 76:
2609                            encodedcontroller = _lev_ctrl_CC76_EXT;
2610                            break;
2611                        case 77:
2612                            encodedcontroller = _lev_ctrl_CC77_EXT;
2613                            break;
2614                        case 78:
2615                            encodedcontroller = _lev_ctrl_CC78_EXT;
2616                            break;
2617                        case 79:
2618                            encodedcontroller = _lev_ctrl_CC79_EXT;
2619                            break;
2620                        case 84:
2621                            encodedcontroller = _lev_ctrl_CC84_EXT;
2622                            break;
2623                        case 85:
2624                            encodedcontroller = _lev_ctrl_CC85_EXT;
2625                            break;
2626                        case 86:
2627                            encodedcontroller = _lev_ctrl_CC86_EXT;
2628                            break;
2629                        case 87:
2630                            encodedcontroller = _lev_ctrl_CC87_EXT;
2631                            break;
2632                        case 89:
2633                            encodedcontroller = _lev_ctrl_CC89_EXT;
2634                            break;
2635                        case 90:
2636                            encodedcontroller = _lev_ctrl_CC90_EXT;
2637                            break;
2638                        case 96:
2639                            encodedcontroller = _lev_ctrl_CC96_EXT;
2640                            break;
2641                        case 97:
2642                            encodedcontroller = _lev_ctrl_CC97_EXT;
2643                            break;
2644                        case 102:
2645                            encodedcontroller = _lev_ctrl_CC102_EXT;
2646                            break;
2647                        case 103:
2648                            encodedcontroller = _lev_ctrl_CC103_EXT;
2649                            break;
2650                        case 104:
2651                            encodedcontroller = _lev_ctrl_CC104_EXT;
2652                            break;
2653                        case 105:
2654                            encodedcontroller = _lev_ctrl_CC105_EXT;
2655                            break;
2656                        case 106:
2657                            encodedcontroller = _lev_ctrl_CC106_EXT;
2658                            break;
2659                        case 107:
2660                            encodedcontroller = _lev_ctrl_CC107_EXT;
2661                            break;
2662                        case 108:
2663                            encodedcontroller = _lev_ctrl_CC108_EXT;
2664                            break;
2665                        case 109:
2666                            encodedcontroller = _lev_ctrl_CC109_EXT;
2667                            break;
2668                        case 110:
2669                            encodedcontroller = _lev_ctrl_CC110_EXT;
2670                            break;
2671                        case 111:
2672                            encodedcontroller = _lev_ctrl_CC111_EXT;
2673                            break;
2674                        case 112:
2675                            encodedcontroller = _lev_ctrl_CC112_EXT;
2676                            break;
2677                        case 113:
2678                            encodedcontroller = _lev_ctrl_CC113_EXT;
2679                            break;
2680                        case 114:
2681                            encodedcontroller = _lev_ctrl_CC114_EXT;
2682                            break;
2683                        case 115:
2684                            encodedcontroller = _lev_ctrl_CC115_EXT;
2685                            break;
2686                        case 116:
2687                            encodedcontroller = _lev_ctrl_CC116_EXT;
2688                            break;
2689                        case 117:
2690                            encodedcontroller = _lev_ctrl_CC117_EXT;
2691                            break;
2692                        case 118:
2693                            encodedcontroller = _lev_ctrl_CC118_EXT;
2694                            break;
2695                        case 119:
2696                            encodedcontroller = _lev_ctrl_CC119_EXT;
2697                            break;
2698    
2699                        default:
2700                            throw gig::Exception("leverage controller number is not supported by the gig format");
2701                    }
2702                    break;
2703                default:
2704                    throw gig::Exception("Unknown leverage controller type.");
2705            }
2706            return encodedcontroller;
2707        }
2708    
2709      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
2710          Instances--;          Instances--;
# Line 1001  namespace gig { Line 2719  namespace gig {
2719              delete pVelocityTables;              delete pVelocityTables;
2720              pVelocityTables = NULL;              pVelocityTables = NULL;
2721          }          }
2722            if (VelocityTable) delete[] VelocityTable;
2723      }      }
2724    
2725      /**      /**
# Line 1018  namespace gig { Line 2737  namespace gig {
2737          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
2738      }      }
2739    
2740        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2741            return pVelocityReleaseTable[MIDIKeyVelocity];
2742        }
2743    
2744        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2745            return pVelocityCutoffTable[MIDIKeyVelocity];
2746        }
2747    
2748        /**
2749         * Updates the respective member variable and the lookup table / cache
2750         * that depends on this value.
2751         */
2752        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2753            pVelocityAttenuationTable =
2754                GetVelocityTable(
2755                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2756                );
2757            VelocityResponseCurve = curve;
2758        }
2759    
2760        /**
2761         * Updates the respective member variable and the lookup table / cache
2762         * that depends on this value.
2763         */
2764        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2765            pVelocityAttenuationTable =
2766                GetVelocityTable(
2767                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2768                );
2769            VelocityResponseDepth = depth;
2770        }
2771    
2772        /**
2773         * Updates the respective member variable and the lookup table / cache
2774         * that depends on this value.
2775         */
2776        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2777            pVelocityAttenuationTable =
2778                GetVelocityTable(
2779                    VelocityResponseCurve, VelocityResponseDepth, scaling
2780                );
2781            VelocityResponseCurveScaling = scaling;
2782        }
2783    
2784        /**
2785         * Updates the respective member variable and the lookup table / cache
2786         * that depends on this value.
2787         */
2788        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2789            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2790            ReleaseVelocityResponseCurve = curve;
2791        }
2792    
2793        /**
2794         * Updates the respective member variable and the lookup table / cache
2795         * that depends on this value.
2796         */
2797        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2798            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2799            ReleaseVelocityResponseDepth = depth;
2800        }
2801    
2802        /**
2803         * Updates the respective member variable and the lookup table / cache
2804         * that depends on this value.
2805         */
2806        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2807            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2808            VCFCutoffController = controller;
2809        }
2810    
2811        /**
2812         * Updates the respective member variable and the lookup table / cache
2813         * that depends on this value.
2814         */
2815        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2816            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2817            VCFVelocityCurve = curve;
2818        }
2819    
2820        /**
2821         * Updates the respective member variable and the lookup table / cache
2822         * that depends on this value.
2823         */
2824        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2825            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2826            VCFVelocityDynamicRange = range;
2827        }
2828    
2829        /**
2830         * Updates the respective member variable and the lookup table / cache
2831         * that depends on this value.
2832         */
2833        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2834            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2835            VCFVelocityScale = scaling;
2836        }
2837    
2838        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2839    
2840            // line-segment approximations of the 15 velocity curves
2841    
2842            // linear
2843            const int lin0[] = { 1, 1, 127, 127 };
2844            const int lin1[] = { 1, 21, 127, 127 };
2845            const int lin2[] = { 1, 45, 127, 127 };
2846            const int lin3[] = { 1, 74, 127, 127 };
2847            const int lin4[] = { 1, 127, 127, 127 };
2848    
2849            // non-linear
2850            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2851            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2852                                 127, 127 };
2853            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2854                                 127, 127 };
2855            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2856                                 127, 127 };
2857            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2858    
2859            // special
2860            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2861                                 113, 127, 127, 127 };
2862            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2863                                 118, 127, 127, 127 };
2864            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2865                                 85, 90, 91, 127, 127, 127 };
2866            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2867                                 117, 127, 127, 127 };
2868            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2869                                 127, 127 };
2870    
2871            // this is only used by the VCF velocity curve
2872            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2873                                 91, 127, 127, 127 };
2874    
2875            const int* const curves[] = { non0, non1, non2, non3, non4,
2876                                          lin0, lin1, lin2, lin3, lin4,
2877                                          spe0, spe1, spe2, spe3, spe4, spe5 };
2878    
2879            double* const table = new double[128];
2880    
2881            const int* curve = curves[curveType * 5 + depth];
2882            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2883    
2884            table[0] = 0;
2885            for (int x = 1 ; x < 128 ; x++) {
2886    
2887                if (x > curve[2]) curve += 2;
2888                double y = curve[1] + (x - curve[0]) *
2889                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2890                y = y / 127;
2891    
2892                // Scale up for s > 20, down for s < 20. When
2893                // down-scaling, the curve still ends at 1.0.
2894                if (s < 20 && y >= 0.5)
2895                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2896                else
2897                    y = y * (s / 20.0);
2898                if (y > 1) y = 1;
2899    
2900                table[x] = y;
2901            }
2902            return table;
2903        }
2904    
2905    
2906  // *************** Region ***************  // *************** Region ***************
# Line 1026  namespace gig { Line 2909  namespace gig {
2909      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) {
2910          // Initialization          // Initialization
2911          Dimensions = 0;          Dimensions = 0;
2912          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
2913              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
2914          }          }
2915            Layers = 1;
2916            File* file = (File*) GetParent()->GetParent();
2917            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2918    
2919          // Actual Loading          // Actual Loading
2920    
2921            if (!file->GetAutoLoad()) return;
2922    
2923          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2924    
2925          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2926          if (_3lnk) {          if (_3lnk) {
2927              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
2928              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
2929                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2930                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2931                    _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2932                    _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2933                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2934                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2935                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2936                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2937                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2938                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2939                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2940                  }                  }
2941                  else { // active dimension                  else { // active dimension
2942                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2943                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2944                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2945                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2946                                                             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;  
2947                      Dimensions++;                      Dimensions++;
2948    
2949                        // if this is a layer dimension, remember the amount of layers
2950                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2951                  }                  }
2952                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2953              }              }
2954                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2955    
2956              // 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,
2957              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2958                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
2959                  if (pDimDef->dimension == dimension_velocity) {  
2960                      if (pDimensionRegions[0]->VelocityUpperLimit == 0) {              // jump to start of the wave pool indices (if not already there)
2961                          // no custom defined ranges              if (file->pVersion && file->pVersion->major == 3)
2962                          pDimDef->split_type = split_type_normal;                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2963                          pDimDef->ranges     = NULL;              else
2964                      }                  _3lnk->SetPos(44);
2965                      else { // custom defined ranges  
2966                          pDimDef->split_type = split_type_customvelocity;              // load sample references (if auto loading is enabled)
2967                          pDimDef->ranges     = new range_t[pDimDef->zones];              if (file->GetAutoLoad()) {
2968                          unsigned int bits[5] = {0,0,0,0,0};                  for (uint i = 0; i < DimensionRegions; i++) {
2969                          int previousUpperLimit = -1;                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2970                          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;  
                             }  
                         }  
                     }  
2971                  }                  }
2972                    GetSample(); // load global region sample reference
2973                }
2974            } else {
2975                DimensionRegions = 0;
2976                for (int i = 0 ; i < 8 ; i++) {
2977                    pDimensionDefinitions[i].dimension  = dimension_none;
2978                    pDimensionDefinitions[i].bits       = 0;
2979                    pDimensionDefinitions[i].zones      = 0;
2980              }              }
2981            }
2982    
2983            // make sure there is at least one dimension region
2984            if (!DimensionRegions) {
2985                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2986                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2987                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2988                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2989                DimensionRegions = 1;
2990            }
2991        }
2992    
2993        /**
2994         * Apply Region settings and all its DimensionRegions to the respective
2995         * RIFF chunks. You have to call File::Save() to make changes persistent.
2996         *
2997         * Usually there is absolutely no need to call this method explicitly.
2998         * It will be called automatically when File::Save() was called.
2999         *
3000         * @param pProgress - callback function for progress notification
3001         * @throws gig::Exception if samples cannot be dereferenced
3002         */
3003        void Region::UpdateChunks(progress_t* pProgress) {
3004            // in the gig format we don't care about the Region's sample reference
3005            // but we still have to provide some existing one to not corrupt the
3006            // file, so to avoid the latter we simply always assign the sample of
3007            // the first dimension region of this region
3008            pSample = pDimensionRegions[0]->pSample;
3009    
3010            // first update base class's chunks
3011            DLS::Region::UpdateChunks(pProgress);
3012    
3013            // update dimension region's chunks
3014            for (int i = 0; i < DimensionRegions; i++) {
3015                pDimensionRegions[i]->UpdateChunks(pProgress);
3016            }
3017    
3018            File* pFile = (File*) GetParent()->GetParent();
3019            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3020            const int iMaxDimensions =  version3 ? 8 : 5;
3021            const int iMaxDimensionRegions = version3 ? 256 : 32;
3022    
3023            // make sure '3lnk' chunk exists
3024            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3025            if (!_3lnk) {
3026                const int _3lnkChunkSize = version3 ? 1092 : 172;
3027                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3028                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3029    
3030                // move 3prg to last position
3031                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3032            }
3033    
3034              // load sample references          // update dimension definitions in '3lnk' chunk
3035              _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3036              for (uint i = 0; i < DimensionRegions; i++) {          store32(&pData[0], DimensionRegions);
3037                  uint32_t wavepoolindex = _3lnk->ReadUint32();          int shift = 0;
3038                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);          for (int i = 0; i < iMaxDimensions; i++) {
3039                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3040                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3041                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3042                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3043                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3044                // next 3 bytes unknown, always zero?
3045    
3046                shift += pDimensionDefinitions[i].bits;
3047            }
3048    
3049            // update wave pool table in '3lnk' chunk
3050            const int iWavePoolOffset = version3 ? 68 : 44;
3051            for (uint i = 0; i < iMaxDimensionRegions; i++) {
3052                int iWaveIndex = -1;
3053                if (i < DimensionRegions) {
3054                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3055                    File::SampleList::iterator iter = pFile->pSamples->begin();
3056                    File::SampleList::iterator end  = pFile->pSamples->end();
3057                    for (int index = 0; iter != end; ++iter, ++index) {
3058                        if (*iter == pDimensionRegions[i]->pSample) {
3059                            iWaveIndex = index;
3060                            break;
3061                        }
3062                    }
3063              }              }
3064                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3065          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
3066      }      }
3067    
3068      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1111  namespace gig { Line 3072  namespace gig {
3072              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3073              while (_3ewl) {              while (_3ewl) {
3074                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3075                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3076                      dimensionRegionNr++;                      dimensionRegionNr++;
3077                  }                  }
3078                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 1120  namespace gig { Line 3081  namespace gig {
3081          }          }
3082      }      }
3083    
3084      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3085          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
3086              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
3087            // update Region key table for fast lookup
3088            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3089        }
3090    
3091        void Region::UpdateVelocityTable() {
3092            // get velocity dimension's index
3093            int veldim = -1;
3094            for (int i = 0 ; i < Dimensions ; i++) {
3095                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3096                    veldim = i;
3097                    break;
3098                }
3099            }
3100            if (veldim == -1) return;
3101    
3102            int step = 1;
3103            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3104            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3105            int end = step * pDimensionDefinitions[veldim].zones;
3106    
3107            // loop through all dimension regions for all dimensions except the velocity dimension
3108            int dim[8] = { 0 };
3109            for (int i = 0 ; i < DimensionRegions ; i++) {
3110    
3111                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3112                    pDimensionRegions[i]->VelocityUpperLimit) {
3113                    // create the velocity table
3114                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
3115                    if (!table) {
3116                        table = new uint8_t[128];
3117                        pDimensionRegions[i]->VelocityTable = table;
3118                    }
3119                    int tableidx = 0;
3120                    int velocityZone = 0;
3121                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3122                        for (int k = i ; k < end ; k += step) {
3123                            DimensionRegion *d = pDimensionRegions[k];
3124                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3125                            velocityZone++;
3126                        }
3127                    } else { // gig2
3128                        for (int k = i ; k < end ; k += step) {
3129                            DimensionRegion *d = pDimensionRegions[k];
3130                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3131                            velocityZone++;
3132                        }
3133                    }
3134                } else {
3135                    if (pDimensionRegions[i]->VelocityTable) {
3136                        delete[] pDimensionRegions[i]->VelocityTable;
3137                        pDimensionRegions[i]->VelocityTable = 0;
3138                    }
3139                }
3140    
3141                int j;
3142                int shift = 0;
3143                for (j = 0 ; j < Dimensions ; j++) {
3144                    if (j == veldim) i += skipveldim; // skip velocity dimension
3145                    else {
3146                        dim[j]++;
3147                        if (dim[j] < pDimensionDefinitions[j].zones) break;
3148                        else {
3149                            // skip unused dimension regions
3150                            dim[j] = 0;
3151                            i += ((1 << pDimensionDefinitions[j].bits) -
3152                                  pDimensionDefinitions[j].zones) << shift;
3153                        }
3154                    }
3155                    shift += pDimensionDefinitions[j].bits;
3156                }
3157                if (j == Dimensions) break;
3158            }
3159        }
3160    
3161        /** @brief Einstein would have dreamed of it - create a new dimension.
3162         *
3163         * Creates a new dimension with the dimension definition given by
3164         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
3165         * There is a hard limit of dimensions and total amount of "bits" all
3166         * dimensions can have. This limit is dependant to what gig file format
3167         * version this file refers to. The gig v2 (and lower) format has a
3168         * dimension limit and total amount of bits limit of 5, whereas the gig v3
3169         * format has a limit of 8.
3170         *
3171         * @param pDimDef - defintion of the new dimension
3172         * @throws gig::Exception if dimension of the same type exists already
3173         * @throws gig::Exception if amount of dimensions or total amount of
3174         *                        dimension bits limit is violated
3175         */
3176        void Region::AddDimension(dimension_def_t* pDimDef) {
3177            // some initial sanity checks of the given dimension definition
3178            if (pDimDef->zones < 2)
3179                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3180            if (pDimDef->bits < 1)
3181                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3182            if (pDimDef->dimension == dimension_samplechannel) {
3183                if (pDimDef->zones != 2)
3184                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3185                if (pDimDef->bits != 1)
3186                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3187            }
3188    
3189            // check if max. amount of dimensions reached
3190            File* file = (File*) GetParent()->GetParent();
3191            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3192            if (Dimensions >= iMaxDimensions)
3193                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3194            // check if max. amount of dimension bits reached
3195            int iCurrentBits = 0;
3196            for (int i = 0; i < Dimensions; i++)
3197                iCurrentBits += pDimensionDefinitions[i].bits;
3198            if (iCurrentBits >= iMaxDimensions)
3199                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3200            const int iNewBits = iCurrentBits + pDimDef->bits;
3201            if (iNewBits > iMaxDimensions)
3202                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3203            // check if there's already a dimensions of the same type
3204            for (int i = 0; i < Dimensions; i++)
3205                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3206                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3207    
3208            // pos is where the new dimension should be placed, normally
3209            // last in list, except for the samplechannel dimension which
3210            // has to be first in list
3211            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3212            int bitpos = 0;
3213            for (int i = 0 ; i < pos ; i++)
3214                bitpos += pDimensionDefinitions[i].bits;
3215    
3216            // make room for the new dimension
3217            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3218            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3219                for (int j = Dimensions ; j > pos ; j--) {
3220                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3221                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3222                }
3223            }
3224    
3225            // assign definition of new dimension
3226            pDimensionDefinitions[pos] = *pDimDef;
3227    
3228            // auto correct certain dimension definition fields (where possible)
3229            pDimensionDefinitions[pos].split_type  =
3230                __resolveSplitType(pDimensionDefinitions[pos].dimension);
3231            pDimensionDefinitions[pos].zone_size =
3232                __resolveZoneSize(pDimensionDefinitions[pos]);
3233    
3234            // create new dimension region(s) for this new dimension, and make
3235            // sure that the dimension regions are placed correctly in both the
3236            // RIFF list and the pDimensionRegions array
3237            RIFF::Chunk* moveTo = NULL;
3238            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3239            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3240                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3241                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3242                }
3243                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3244                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3245                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3246                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3247                        // create a new dimension region and copy all parameter values from
3248                        // an existing dimension region
3249                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3250                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3251    
3252                        DimensionRegions++;
3253                    }
3254                }
3255                moveTo = pDimensionRegions[i]->pParentList;
3256            }
3257    
3258            // initialize the upper limits for this dimension
3259            int mask = (1 << bitpos) - 1;
3260            for (int z = 0 ; z < pDimDef->zones ; z++) {
3261                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3262                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3263                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3264                                      (z << bitpos) |
3265                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3266                }
3267            }
3268    
3269            Dimensions++;
3270    
3271            // if this is a layer dimension, update 'Layers' attribute
3272            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3273    
3274            UpdateVelocityTable();
3275        }
3276    
3277        /** @brief Delete an existing dimension.
3278         *
3279         * Deletes the dimension given by \a pDimDef and deletes all respective
3280         * dimension regions, that is all dimension regions where the dimension's
3281         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
3282         * for example this would delete all dimension regions for the case(s)
3283         * where the sustain pedal is pressed down.
3284         *
3285         * @param pDimDef - dimension to delete
3286         * @throws gig::Exception if given dimension cannot be found
3287         */
3288        void Region::DeleteDimension(dimension_def_t* pDimDef) {
3289            // get dimension's index
3290            int iDimensionNr = -1;
3291            for (int i = 0; i < Dimensions; i++) {
3292                if (&pDimensionDefinitions[i] == pDimDef) {
3293                    iDimensionNr = i;
3294                    break;
3295                }
3296            }
3297            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3298    
3299            // get amount of bits below the dimension to delete
3300            int iLowerBits = 0;
3301            for (int i = 0; i < iDimensionNr; i++)
3302                iLowerBits += pDimensionDefinitions[i].bits;
3303    
3304            // get amount ot bits above the dimension to delete
3305            int iUpperBits = 0;
3306            for (int i = iDimensionNr + 1; i < Dimensions; i++)
3307                iUpperBits += pDimensionDefinitions[i].bits;
3308    
3309            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3310    
3311            // delete dimension regions which belong to the given dimension
3312            // (that is where the dimension's bit > 0)
3313            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3314                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3315                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3316                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3317                                        iObsoleteBit << iLowerBits |
3318                                        iLowerBit;
3319    
3320                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3321                        delete pDimensionRegions[iToDelete];
3322                        pDimensionRegions[iToDelete] = NULL;
3323                        DimensionRegions--;
3324                    }
3325                }
3326            }
3327    
3328            // defrag pDimensionRegions array
3329            // (that is remove the NULL spaces within the pDimensionRegions array)
3330            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3331                if (!pDimensionRegions[iTo]) {
3332                    if (iFrom <= iTo) iFrom = iTo + 1;
3333                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3334                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
3335                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
3336                        pDimensionRegions[iFrom] = NULL;
3337                    }
3338                }
3339            }
3340    
3341            // remove the this dimension from the upper limits arrays
3342            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3343                DimensionRegion* d = pDimensionRegions[j];
3344                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3345                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3346                }
3347                d->DimensionUpperLimits[Dimensions - 1] = 127;
3348            }
3349    
3350            // 'remove' dimension definition
3351            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3352                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
3353            }
3354            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3355            pDimensionDefinitions[Dimensions - 1].bits      = 0;
3356            pDimensionDefinitions[Dimensions - 1].zones     = 0;
3357    
3358            Dimensions--;
3359    
3360            // if this was a layer dimension, update 'Layers' attribute
3361            if (pDimDef->dimension == dimension_layer) Layers = 1;
3362        }
3363    
3364        /** @brief Delete one split zone of a dimension (decrement zone amount).
3365         *
3366         * Instead of deleting an entire dimensions, this method will only delete
3367         * one particular split zone given by @a zone of the Region's dimension
3368         * given by @a type. So this method will simply decrement the amount of
3369         * zones by one of the dimension in question. To be able to do that, the
3370         * respective dimension must exist on this Region and it must have at least
3371         * 3 zones. All DimensionRegion objects associated with the zone will be
3372         * deleted.
3373         *
3374         * @param type - identifies the dimension where a zone shall be deleted
3375         * @param zone - index of the dimension split zone that shall be deleted
3376         * @throws gig::Exception if requested zone could not be deleted
3377         */
3378        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3379            dimension_def_t* oldDef = GetDimensionDefinition(type);
3380            if (!oldDef)
3381                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3382            if (oldDef->zones <= 2)
3383                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3384            if (zone < 0 || zone >= oldDef->zones)
3385                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3386    
3387            const int newZoneSize = oldDef->zones - 1;
3388    
3389            // create a temporary Region which just acts as a temporary copy
3390            // container and will be deleted at the end of this function and will
3391            // also not be visible through the API during this process
3392            gig::Region* tempRgn = NULL;
3393            {
3394                // adding these temporary chunks is probably not even necessary
3395                Instrument* instr = static_cast<Instrument*>(GetParent());
3396                RIFF::List* pCkInstrument = instr->pCkInstrument;
3397                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3398                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3399                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3400                tempRgn = new Region(instr, rgn);
3401            }
3402    
3403            // copy this region's dimensions (with already the dimension split size
3404            // requested by the arguments of this method call) to the temporary
3405            // region, and don't use Region::CopyAssign() here for this task, since
3406            // it would also alter fast lookup helper variables here and there
3407            dimension_def_t newDef;
3408            for (int i = 0; i < Dimensions; ++i) {
3409                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3410                // is this the dimension requested by the method arguments? ...
3411                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3412                    def.zones = newZoneSize;
3413                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3414                    newDef = def;
3415                }
3416                tempRgn->AddDimension(&def);
3417            }
3418    
3419            // find the dimension index in the tempRegion which is the dimension
3420            // type passed to this method (paranoidly expecting different order)
3421            int tempReducedDimensionIndex = -1;
3422            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3423                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3424                    tempReducedDimensionIndex = d;
3425                    break;
3426                }
3427          }          }
3428          for (int i = 0; i < 32; i++) {  
3429            // copy dimension regions from this region to the temporary region
3430            for (int iDst = 0; iDst < 256; ++iDst) {
3431                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3432                if (!dstDimRgn) continue;
3433                std::map<dimension_t,int> dimCase;
3434                bool isValidZone = true;
3435                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3436                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3437                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3438                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3439                    baseBits += dstBits;
3440                    // there are also DimensionRegion objects of unused zones, skip them
3441                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3442                        isValidZone = false;
3443                        break;
3444                    }
3445                }
3446                if (!isValidZone) continue;
3447                // a bit paranoid: cope with the chance that the dimensions would
3448                // have different order in source and destination regions
3449                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3450                if (dimCase[type] >= zone) dimCase[type]++;
3451                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3452                dstDimRgn->CopyAssign(srcDimRgn);
3453                // if this is the upper most zone of the dimension passed to this
3454                // method, then correct (raise) its upper limit to 127
3455                if (newDef.split_type == split_type_normal && isLastZone)
3456                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3457            }
3458    
3459            // now tempRegion's dimensions and DimensionRegions basically reflect
3460            // what we wanted to get for this actual Region here, so we now just
3461            // delete and recreate the dimension in question with the new amount
3462            // zones and then copy back from tempRegion      
3463            DeleteDimension(oldDef);
3464            AddDimension(&newDef);
3465            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3466                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3467                if (!srcDimRgn) continue;
3468                std::map<dimension_t,int> dimCase;
3469                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3470                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3471                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3472                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3473                    baseBits += srcBits;
3474                }
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3478                if (!dstDimRgn) continue;
3479                dstDimRgn->CopyAssign(srcDimRgn);
3480            }
3481    
3482            // delete temporary region
3483            delete tempRgn;
3484    
3485            UpdateVelocityTable();
3486        }
3487    
3488        /** @brief Divide split zone of a dimension in two (increment zone amount).
3489         *
3490         * This will increment the amount of zones for the dimension (given by
3491         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3492         * in the middle of its zone range in two. So the two zones resulting from
3493         * the zone being splitted, will be an equivalent copy regarding all their
3494         * articulation informations and sample reference. The two zones will only
3495         * differ in their zone's upper limit
3496         * (DimensionRegion::DimensionUpperLimits).
3497         *
3498         * @param type - identifies the dimension where a zone shall be splitted
3499         * @param zone - index of the dimension split zone that shall be splitted
3500         * @throws gig::Exception if requested zone could not be splitted
3501         */
3502        void Region::SplitDimensionZone(dimension_t type, int zone) {
3503            dimension_def_t* oldDef = GetDimensionDefinition(type);
3504            if (!oldDef)
3505                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3506            if (zone < 0 || zone >= oldDef->zones)
3507                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3508    
3509            const int newZoneSize = oldDef->zones + 1;
3510    
3511            // create a temporary Region which just acts as a temporary copy
3512            // container and will be deleted at the end of this function and will
3513            // also not be visible through the API during this process
3514            gig::Region* tempRgn = NULL;
3515            {
3516                // adding these temporary chunks is probably not even necessary
3517                Instrument* instr = static_cast<Instrument*>(GetParent());
3518                RIFF::List* pCkInstrument = instr->pCkInstrument;
3519                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3520                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3521                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3522                tempRgn = new Region(instr, rgn);
3523            }
3524    
3525            // copy this region's dimensions (with already the dimension split size
3526            // requested by the arguments of this method call) to the temporary
3527            // region, and don't use Region::CopyAssign() here for this task, since
3528            // it would also alter fast lookup helper variables here and there
3529            dimension_def_t newDef;
3530            for (int i = 0; i < Dimensions; ++i) {
3531                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3532                // is this the dimension requested by the method arguments? ...
3533                if (def.dimension == type) { // ... if yes, increment zone amount by one
3534                    def.zones = newZoneSize;
3535                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3536                    newDef = def;
3537                }
3538                tempRgn->AddDimension(&def);
3539            }
3540    
3541            // find the dimension index in the tempRegion which is the dimension
3542            // type passed to this method (paranoidly expecting different order)
3543            int tempIncreasedDimensionIndex = -1;
3544            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3545                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3546                    tempIncreasedDimensionIndex = d;
3547                    break;
3548                }
3549            }
3550    
3551            // copy dimension regions from this region to the temporary region
3552            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3553                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3554                if (!srcDimRgn) continue;
3555                std::map<dimension_t,int> dimCase;
3556                bool isValidZone = true;
3557                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3558                    const int srcBits = pDimensionDefinitions[d].bits;
3559                    dimCase[pDimensionDefinitions[d].dimension] =
3560                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3561                    // there are also DimensionRegion objects for unused zones, skip them
3562                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3563                        isValidZone = false;
3564                        break;
3565                    }
3566                    baseBits += srcBits;
3567                }
3568                if (!isValidZone) continue;
3569                // a bit paranoid: cope with the chance that the dimensions would
3570                // have different order in source and destination regions            
3571                if (dimCase[type] > zone) dimCase[type]++;
3572                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3573                dstDimRgn->CopyAssign(srcDimRgn);
3574                // if this is the requested zone to be splitted, then also copy
3575                // the source DimensionRegion to the newly created target zone
3576                // and set the old zones upper limit lower
3577                if (dimCase[type] == zone) {
3578                    // lower old zones upper limit
3579                    if (newDef.split_type == split_type_normal) {
3580                        const int high =
3581                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3582                        int low = 0;
3583                        if (zone > 0) {
3584                            std::map<dimension_t,int> lowerCase = dimCase;
3585                            lowerCase[type]--;
3586                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3587                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3588                        }
3589                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3590                    }
3591                    // fill the newly created zone of the divided zone as well
3592                    dimCase[type]++;
3593                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3594                    dstDimRgn->CopyAssign(srcDimRgn);
3595                }
3596            }
3597    
3598            // now tempRegion's dimensions and DimensionRegions basically reflect
3599            // what we wanted to get for this actual Region here, so we now just
3600            // delete and recreate the dimension in question with the new amount
3601            // zones and then copy back from tempRegion      
3602            DeleteDimension(oldDef);
3603            AddDimension(&newDef);
3604            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3605                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3606                if (!srcDimRgn) continue;
3607                std::map<dimension_t,int> dimCase;
3608                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3609                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3610                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3611                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3612                    baseBits += srcBits;
3613                }
3614                // a bit paranoid: cope with the chance that the dimensions would
3615                // have different order in source and destination regions
3616                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3617                if (!dstDimRgn) continue;
3618                dstDimRgn->CopyAssign(srcDimRgn);
3619            }
3620    
3621            // delete temporary region
3622            delete tempRgn;
3623    
3624            UpdateVelocityTable();
3625        }
3626    
3627        /** @brief Change type of an existing dimension.
3628         *
3629         * Alters the dimension type of a dimension already existing on this
3630         * region. If there is currently no dimension on this Region with type
3631         * @a oldType, then this call with throw an Exception. Likewise there are
3632         * cases where the requested dimension type cannot be performed. For example
3633         * if the new dimension type shall be gig::dimension_samplechannel, and the
3634         * current dimension has more than 2 zones. In such cases an Exception is
3635         * thrown as well.
3636         *
3637         * @param oldType - identifies the existing dimension to be changed
3638         * @param newType - to which dimension type it should be changed to
3639         * @throws gig::Exception if requested change cannot be performed
3640         */
3641        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3642            if (oldType == newType) return;
3643            dimension_def_t* def = GetDimensionDefinition(oldType);
3644            if (!def)
3645                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3646            if (newType == dimension_samplechannel && def->zones != 2)
3647                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3648            if (GetDimensionDefinition(newType))
3649                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3650            def->dimension  = newType;
3651            def->split_type = __resolveSplitType(newType);
3652        }
3653    
3654        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3655            uint8_t bits[8] = {};
3656            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3657                 it != DimCase.end(); ++it)
3658            {
3659                for (int d = 0; d < Dimensions; ++d) {
3660                    if (pDimensionDefinitions[d].dimension == it->first) {
3661                        bits[d] = it->second;
3662                        goto nextDimCaseSlice;
3663                    }
3664                }
3665                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3666                nextDimCaseSlice:
3667                ; // noop
3668            }
3669            return GetDimensionRegionByBit(bits);
3670        }
3671    
3672        /**
3673         * Searches in the current Region for a dimension of the given dimension
3674         * type and returns the precise configuration of that dimension in this
3675         * Region.
3676         *
3677         * @param type - dimension type of the sought dimension
3678         * @returns dimension definition or NULL if there is no dimension with
3679         *          sought type in this Region.
3680         */
3681        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3682            for (int i = 0; i < Dimensions; ++i)
3683                if (pDimensionDefinitions[i].dimension == type)
3684                    return &pDimensionDefinitions[i];
3685            return NULL;
3686        }
3687    
3688        Region::~Region() {
3689            for (int i = 0; i < 256; i++) {
3690              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
3691          }          }
3692      }      }
# Line 1142  namespace gig { Line 3704  namespace gig {
3704       * 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,
3705       * etc.).       * etc.).
3706       *       *
3707       * @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  
3708       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
3709       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
3710       * @see             Dimensions       * @see             Dimensions
3711       */       */
3712      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3713          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits;
3714            int veldim = -1;
3715            int velbitpos;
3716            int bitpos = 0;
3717            int dimregidx = 0;
3718          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
3719              switch (pDimensionDefinitions[i].split_type) {              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3720                  case split_type_normal:                  // the velocity dimension must be handled after the other dimensions
3721                      bits[i] /= pDimensionDefinitions[i].zone_size;                  veldim = i;
3722                      break;                  velbitpos = bitpos;
3723                  case split_type_customvelocity:              } else {
3724                      bits[i] = VelocityTable[bits[i]];                  switch (pDimensionDefinitions[i].split_type) {
3725                      break;                      case split_type_normal:
3726                  // else the value is already the sought dimension bit number                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3727                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3728                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3729                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3730                                }
3731                            } else {
3732                                // gig2: evenly sized zones
3733                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3734                            }
3735                            break;
3736                        case split_type_bit: // the value is already the sought dimension bit number
3737                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3738                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3739                            break;
3740                    }
3741                    dimregidx |= bits << bitpos;
3742                }
3743                bitpos += pDimensionDefinitions[i].bits;
3744            }
3745            DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3746            if (!dimreg) return NULL;
3747            if (veldim != -1) {
3748                // (dimreg is now the dimension region for the lowest velocity)
3749                if (dimreg->VelocityTable) // custom defined zone ranges
3750                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3751                else // normal split type
3752                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3753    
3754                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3755                dimregidx |= (bits & limiter_mask) << velbitpos;
3756                dimreg = pDimensionRegions[dimregidx & 255];
3757            }
3758            return dimreg;
3759        }
3760    
3761        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3762            uint8_t bits;
3763            int veldim = -1;
3764            int velbitpos;
3765            int bitpos = 0;
3766            int dimregidx = 0;
3767            for (uint i = 0; i < Dimensions; i++) {
3768                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3769                    // the velocity dimension must be handled after the other dimensions
3770                    veldim = i;
3771                    velbitpos = bitpos;
3772                } else {
3773                    switch (pDimensionDefinitions[i].split_type) {
3774                        case split_type_normal:
3775                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3776                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3777                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3778                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3779                                }
3780                            } else {
3781                                // gig2: evenly sized zones
3782                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3783                            }
3784                            break;
3785                        case split_type_bit: // the value is already the sought dimension bit number
3786                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3787                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3788                            break;
3789                    }
3790                    dimregidx |= bits << bitpos;
3791              }              }
3792                bitpos += pDimensionDefinitions[i].bits;
3793          }          }
3794          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          dimregidx &= 255;
3795            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3796            if (!dimreg) return -1;
3797            if (veldim != -1) {
3798                // (dimreg is now the dimension region for the lowest velocity)
3799                if (dimreg->VelocityTable) // custom defined zone ranges
3800                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3801                else // normal split type
3802                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3803    
3804                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3805                dimregidx |= (bits & limiter_mask) << velbitpos;
3806                dimregidx &= 255;
3807            }
3808            return dimregidx;
3809      }      }
3810    
3811      /**      /**
# Line 1172  namespace gig { Line 3813  namespace gig {
3813       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
3814       * instead of calling this method directly!       * instead of calling this method directly!
3815       *       *
3816       * @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  
3817       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
3818       *                 bit numbers       *                 bit numbers
3819       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
3820       */       */
3821      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]) {
3822          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3823                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
3824                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
3825                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
3826                                                      << pDimensionDefinitions[2].bits | DimBits[2])
3827                                                      << pDimensionDefinitions[1].bits | DimBits[1])
3828                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
3829      }      }
3830    
3831      /**      /**
# Line 1202  namespace gig { Line 3842  namespace gig {
3842          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3843      }      }
3844    
3845      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3846            if ((int32_t)WavePoolTableIndex == -1) return NULL;
3847          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3848            if (!file->pWavePoolTable) return NULL;
3849          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3850          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3851            Sample* sample = file->GetFirstSample(pProgress);
3852          while (sample) {          while (sample) {
3853              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
3854                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3855              sample = file->GetNextSample();              sample = file->GetNextSample();
3856          }          }
3857          return NULL;          return NULL;
3858      }      }
3859        
3860        /**
3861         * Make a (semi) deep copy of the Region object given by @a orig
3862         * and assign it to this object.
3863         *
3864         * Note that all sample pointers referenced by @a orig are simply copied as
3865         * memory address. Thus the respective samples are shared, not duplicated!
3866         *
3867         * @param orig - original Region object to be copied from
3868         */
3869        void Region::CopyAssign(const Region* orig) {
3870            CopyAssign(orig, NULL);
3871        }
3872        
3873        /**
3874         * Make a (semi) deep copy of the Region object given by @a orig and
3875         * assign it to this object
3876         *
3877         * @param mSamples - crosslink map between the foreign file's samples and
3878         *                   this file's samples
3879         */
3880        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3881            // handle base classes
3882            DLS::Region::CopyAssign(orig);
3883            
3884            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3885                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3886            }
3887            
3888            // handle own member variables
3889            for (int i = Dimensions - 1; i >= 0; --i) {
3890                DeleteDimension(&pDimensionDefinitions[i]);
3891            }
3892            Layers = 0; // just to be sure
3893            for (int i = 0; i < orig->Dimensions; i++) {
3894                // we need to copy the dim definition here, to avoid the compiler
3895                // complaining about const-ness issue
3896                dimension_def_t def = orig->pDimensionDefinitions[i];
3897                AddDimension(&def);
3898            }
3899            for (int i = 0; i < 256; i++) {
3900                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3901                    pDimensionRegions[i]->CopyAssign(
3902                        orig->pDimensionRegions[i],
3903                        mSamples
3904                    );
3905                }
3906            }
3907            Layers = orig->Layers;
3908        }
3909    
3910    
3911    // *************** MidiRule ***************
3912    // *
3913    
3914        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3915            _3ewg->SetPos(36);
3916            Triggers = _3ewg->ReadUint8();
3917            _3ewg->SetPos(40);
3918            ControllerNumber = _3ewg->ReadUint8();
3919            _3ewg->SetPos(46);
3920            for (int i = 0 ; i < Triggers ; i++) {
3921                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3922                pTriggers[i].Descending = _3ewg->ReadUint8();
3923                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3924                pTriggers[i].Key = _3ewg->ReadUint8();
3925                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3926                pTriggers[i].Velocity = _3ewg->ReadUint8();
3927                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3928                _3ewg->ReadUint8();
3929            }
3930        }
3931    
3932        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3933            ControllerNumber(0),
3934            Triggers(0) {
3935        }
3936    
3937        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3938            pData[32] = 4;
3939            pData[33] = 16;
3940            pData[36] = Triggers;
3941            pData[40] = ControllerNumber;
3942            for (int i = 0 ; i < Triggers ; i++) {
3943                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3944                pData[47 + i * 8] = pTriggers[i].Descending;
3945                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3946                pData[49 + i * 8] = pTriggers[i].Key;
3947                pData[50 + i * 8] = pTriggers[i].NoteOff;
3948                pData[51 + i * 8] = pTriggers[i].Velocity;
3949                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3950            }
3951        }
3952    
3953        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3954            _3ewg->SetPos(36);
3955            LegatoSamples = _3ewg->ReadUint8(); // always 12
3956            _3ewg->SetPos(40);
3957            BypassUseController = _3ewg->ReadUint8();
3958            BypassKey = _3ewg->ReadUint8();
3959            BypassController = _3ewg->ReadUint8();
3960            ThresholdTime = _3ewg->ReadUint16();
3961            _3ewg->ReadInt16();
3962            ReleaseTime = _3ewg->ReadUint16();
3963            _3ewg->ReadInt16();
3964            KeyRange.low = _3ewg->ReadUint8();
3965            KeyRange.high = _3ewg->ReadUint8();
3966            _3ewg->SetPos(64);
3967            ReleaseTriggerKey = _3ewg->ReadUint8();
3968            AltSustain1Key = _3ewg->ReadUint8();
3969            AltSustain2Key = _3ewg->ReadUint8();
3970        }
3971    
3972        MidiRuleLegato::MidiRuleLegato() :
3973            LegatoSamples(12),
3974            BypassUseController(false),
3975            BypassKey(0),
3976            BypassController(1),
3977            ThresholdTime(20),
3978            ReleaseTime(20),
3979            ReleaseTriggerKey(0),
3980            AltSustain1Key(0),
3981            AltSustain2Key(0)
3982        {
3983            KeyRange.low = KeyRange.high = 0;
3984        }
3985    
3986        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3987            pData[32] = 0;
3988            pData[33] = 16;
3989            pData[36] = LegatoSamples;
3990            pData[40] = BypassUseController;
3991            pData[41] = BypassKey;
3992            pData[42] = BypassController;
3993            store16(&pData[43], ThresholdTime);
3994            store16(&pData[47], ReleaseTime);
3995            pData[51] = KeyRange.low;
3996            pData[52] = KeyRange.high;
3997            pData[64] = ReleaseTriggerKey;
3998            pData[65] = AltSustain1Key;
3999            pData[66] = AltSustain2Key;
4000        }
4001    
4002        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4003            _3ewg->SetPos(36);
4004            Articulations = _3ewg->ReadUint8();
4005            int flags = _3ewg->ReadUint8();
4006            Polyphonic = flags & 8;
4007            Chained = flags & 4;
4008            Selector = (flags & 2) ? selector_controller :
4009                (flags & 1) ? selector_key_switch : selector_none;
4010            Patterns = _3ewg->ReadUint8();
4011            _3ewg->ReadUint8(); // chosen row
4012            _3ewg->ReadUint8(); // unknown
4013            _3ewg->ReadUint8(); // unknown
4014            _3ewg->ReadUint8(); // unknown
4015            KeySwitchRange.low = _3ewg->ReadUint8();
4016            KeySwitchRange.high = _3ewg->ReadUint8();
4017            Controller = _3ewg->ReadUint8();
4018            PlayRange.low = _3ewg->ReadUint8();
4019            PlayRange.high = _3ewg->ReadUint8();
4020    
4021            int n = std::min(int(Articulations), 32);
4022            for (int i = 0 ; i < n ; i++) {
4023                _3ewg->ReadString(pArticulations[i], 32);
4024            }
4025            _3ewg->SetPos(1072);
4026            n = std::min(int(Patterns), 32);
4027            for (int i = 0 ; i < n ; i++) {
4028                _3ewg->ReadString(pPatterns[i].Name, 16);
4029                pPatterns[i].Size = _3ewg->ReadUint8();
4030                _3ewg->Read(&pPatterns[i][0], 1, 32);
4031            }
4032        }
4033    
4034        MidiRuleAlternator::MidiRuleAlternator() :
4035            Articulations(0),
4036            Patterns(0),
4037            Selector(selector_none),
4038            Controller(0),
4039            Polyphonic(false),
4040            Chained(false)
4041        {
4042            PlayRange.low = PlayRange.high = 0;
4043            KeySwitchRange.low = KeySwitchRange.high = 0;
4044        }
4045    
4046        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4047            pData[32] = 3;
4048            pData[33] = 16;
4049            pData[36] = Articulations;
4050            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4051                (Selector == selector_controller ? 2 :
4052                 (Selector == selector_key_switch ? 1 : 0));
4053            pData[38] = Patterns;
4054    
4055            pData[43] = KeySwitchRange.low;
4056            pData[44] = KeySwitchRange.high;
4057            pData[45] = Controller;
4058            pData[46] = PlayRange.low;
4059            pData[47] = PlayRange.high;
4060    
4061            char* str = reinterpret_cast<char*>(pData);
4062            int pos = 48;
4063            int n = std::min(int(Articulations), 32);
4064            for (int i = 0 ; i < n ; i++, pos += 32) {
4065                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4066            }
4067    
4068            pos = 1072;
4069            n = std::min(int(Patterns), 32);
4070            for (int i = 0 ; i < n ; i++, pos += 49) {
4071                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4072                pData[pos + 16] = pPatterns[i].Size;
4073                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4074            }
4075        }
4076    
4077    // *************** Script ***************
4078    // *
4079    
4080        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4081            pGroup = group;
4082            pChunk = ckScri;
4083            if (ckScri) { // object is loaded from file ...
4084                // read header
4085                uint32_t headerSize = ckScri->ReadUint32();
4086                Compression = (Compression_t) ckScri->ReadUint32();
4087                Encoding    = (Encoding_t) ckScri->ReadUint32();
4088                Language    = (Language_t) ckScri->ReadUint32();
4089                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4090                crc         = ckScri->ReadUint32();
4091                uint32_t nameSize = ckScri->ReadUint32();
4092                Name.resize(nameSize, ' ');
4093                for (int i = 0; i < nameSize; ++i)
4094                    Name[i] = ckScri->ReadUint8();
4095                // to handle potential future extensions of the header
4096                ckScri->SetPos(sizeof(int32_t) + headerSize);
4097                // read actual script data
4098                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4099                data.resize(scriptSize);
4100                for (int i = 0; i < scriptSize; ++i)
4101                    data[i] = ckScri->ReadUint8();
4102            } else { // this is a new script object, so just initialize it as such ...
4103                Compression = COMPRESSION_NONE;
4104                Encoding = ENCODING_ASCII;
4105                Language = LANGUAGE_NKSP;
4106                Bypass   = false;
4107                crc      = 0;
4108                Name     = "Unnamed Script";
4109            }
4110        }
4111    
4112        Script::~Script() {
4113        }
4114    
4115        /**
4116         * Returns the current script (i.e. as source code) in text format.
4117         */
4118        String Script::GetScriptAsText() {
4119            String s;
4120            s.resize(data.size(), ' ');
4121            memcpy(&s[0], &data[0], data.size());
4122            return s;
4123        }
4124    
4125        /**
4126         * Replaces the current script with the new script source code text given
4127         * by @a text.
4128         *
4129         * @param text - new script source code
4130         */
4131        void Script::SetScriptAsText(const String& text) {
4132            data.resize(text.size());
4133            memcpy(&data[0], &text[0], text.size());
4134        }
4135    
4136        /**
4137         * Apply this script to the respective RIFF chunks. You have to call
4138         * File::Save() to make changes persistent.
4139         *
4140         * Usually there is absolutely no need to call this method explicitly.
4141         * It will be called automatically when File::Save() was called.
4142         *
4143         * @param pProgress - callback function for progress notification
4144         */
4145        void Script::UpdateChunks(progress_t* pProgress) {
4146            // recalculate CRC32 check sum
4147            __resetCRC(crc);
4148            __calculateCRC(&data[0], data.size(), crc);
4149            __encodeCRC(crc);
4150            // make sure chunk exists and has the required size
4151            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4152            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4153            else pChunk->Resize(chunkSize);
4154            // fill the chunk data to be written to disk
4155            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4156            int pos = 0;
4157            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4158            pos += sizeof(int32_t);
4159            store32(&pData[pos], Compression);
4160            pos += sizeof(int32_t);
4161            store32(&pData[pos], Encoding);
4162            pos += sizeof(int32_t);
4163            store32(&pData[pos], Language);
4164            pos += sizeof(int32_t);
4165            store32(&pData[pos], Bypass ? 1 : 0);
4166            pos += sizeof(int32_t);
4167            store32(&pData[pos], crc);
4168            pos += sizeof(int32_t);
4169            store32(&pData[pos], Name.size());
4170            pos += sizeof(int32_t);
4171            for (int i = 0; i < Name.size(); ++i, ++pos)
4172                pData[pos] = Name[i];
4173            for (int i = 0; i < data.size(); ++i, ++pos)
4174                pData[pos] = data[i];
4175        }
4176    
4177        /**
4178         * Move this script from its current ScriptGroup to another ScriptGroup
4179         * given by @a pGroup.
4180         *
4181         * @param pGroup - script's new group
4182         */
4183        void Script::SetGroup(ScriptGroup* pGroup) {
4184            if (this->pGroup = pGroup) return;
4185            if (pChunk)
4186                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4187            this->pGroup = pGroup;
4188        }
4189    
4190        /**
4191         * Returns the script group this script currently belongs to. Each script
4192         * is a member of exactly one ScriptGroup.
4193         *
4194         * @returns current script group
4195         */
4196        ScriptGroup* Script::GetGroup() const {
4197            return pGroup;
4198        }
4199    
4200        void Script::RemoveAllScriptReferences() {
4201            File* pFile = pGroup->pFile;
4202            for (int i = 0; pFile->GetInstrument(i); ++i) {
4203                Instrument* instr = pFile->GetInstrument(i);
4204                instr->RemoveScript(this);
4205            }
4206        }
4207    
4208    // *************** ScriptGroup ***************
4209    // *
4210    
4211        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4212            pFile = file;
4213            pList = lstRTIS;
4214            pScripts = NULL;
4215            if (lstRTIS) {
4216                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4217                ::LoadString(ckName, Name);
4218            } else {
4219                Name = "Default Group";
4220            }
4221        }
4222    
4223        ScriptGroup::~ScriptGroup() {
4224            if (pScripts) {
4225                std::list<Script*>::iterator iter = pScripts->begin();
4226                std::list<Script*>::iterator end  = pScripts->end();
4227                while (iter != end) {
4228                    delete *iter;
4229                    ++iter;
4230                }
4231                delete pScripts;
4232            }
4233        }
4234    
4235        /**
4236         * Apply this script group to the respective RIFF chunks. You have to call
4237         * File::Save() to make changes persistent.
4238         *
4239         * Usually there is absolutely no need to call this method explicitly.
4240         * It will be called automatically when File::Save() was called.
4241         *
4242         * @param pProgress - callback function for progress notification
4243         */
4244        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4245            if (pScripts) {
4246                if (!pList)
4247                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4248    
4249                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4250                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4251    
4252                for (std::list<Script*>::iterator it = pScripts->begin();
4253                     it != pScripts->end(); ++it)
4254                {
4255                    (*it)->UpdateChunks(pProgress);
4256                }
4257            }
4258        }
4259    
4260        /** @brief Get instrument script.
4261         *
4262         * Returns the real-time instrument script with the given index.
4263         *
4264         * @param index - number of the sought script (0..n)
4265         * @returns sought script or NULL if there's no such script
4266         */
4267        Script* ScriptGroup::GetScript(uint index) {
4268            if (!pScripts) LoadScripts();
4269            std::list<Script*>::iterator it = pScripts->begin();
4270            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4271                if (i == index) return *it;
4272            return NULL;
4273        }
4274    
4275        /** @brief Add new instrument script.
4276         *
4277         * Adds a new real-time instrument script to the file. The script is not
4278         * actually used / executed unless it is referenced by an instrument to be
4279         * used. This is similar to samples, which you can add to a file, without
4280         * an instrument necessarily actually using it.
4281         *
4282         * You have to call Save() to make this persistent to the file.
4283         *
4284         * @return new empty script object
4285         */
4286        Script* ScriptGroup::AddScript() {
4287            if (!pScripts) LoadScripts();
4288            Script* pScript = new Script(this, NULL);
4289            pScripts->push_back(pScript);
4290            return pScript;
4291        }
4292    
4293        /** @brief Delete an instrument script.
4294         *
4295         * This will delete the given real-time instrument script. References of
4296         * instruments that are using that script will be removed accordingly.
4297         *
4298         * You have to call Save() to make this persistent to the file.
4299         *
4300         * @param pScript - script to delete
4301         * @throws gig::Exception if given script could not be found
4302         */
4303        void ScriptGroup::DeleteScript(Script* pScript) {
4304            if (!pScripts) LoadScripts();
4305            std::list<Script*>::iterator iter =
4306                find(pScripts->begin(), pScripts->end(), pScript);
4307            if (iter == pScripts->end())
4308                throw gig::Exception("Could not delete script, could not find given script");
4309            pScripts->erase(iter);
4310            pScript->RemoveAllScriptReferences();
4311            if (pScript->pChunk)
4312                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4313            delete pScript;
4314        }
4315    
4316        void ScriptGroup::LoadScripts() {
4317            if (pScripts) return;
4318            pScripts = new std::list<Script*>;
4319            if (!pList) return;
4320    
4321            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4322                 ck = pList->GetNextSubChunk())
4323            {
4324                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4325                    pScripts->push_back(new Script(this, ck));
4326                }
4327            }
4328        }
4329    
4330  // *************** Instrument ***************  // *************** Instrument ***************
4331  // *  // *
4332    
4333      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) {
4334            static const DLS::Info::string_length_t fixedStringLengths[] = {
4335                { CHUNK_ID_INAM, 64 },
4336                { CHUNK_ID_ISFT, 12 },
4337                { 0, 0 }
4338            };
4339            pInfo->SetFixedStringLengths(fixedStringLengths);
4340    
4341          // Initialization          // Initialization
4342          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4343          RegionIndex = -1;          EffectSend = 0;
4344            Attenuation = 0;
4345            FineTune = 0;
4346            PitchbendRange = 0;
4347            PianoReleaseMode = false;
4348            DimensionKeyRange.low = 0;
4349            DimensionKeyRange.high = 0;
4350            pMidiRules = new MidiRule*[3];
4351            pMidiRules[0] = NULL;
4352            pScriptRefs = NULL;
4353    
4354          // Loading          // Loading
4355          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1236  namespace gig { Line 4364  namespace gig {
4364                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4365                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4366                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4367    
4368                    if (_3ewg->GetSize() > 32) {
4369                        // read MIDI rules
4370                        int i = 0;
4371                        _3ewg->SetPos(32);
4372                        uint8_t id1 = _3ewg->ReadUint8();
4373                        uint8_t id2 = _3ewg->ReadUint8();
4374    
4375                        if (id2 == 16) {
4376                            if (id1 == 4) {
4377                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4378                            } else if (id1 == 0) {
4379                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4380                            } else if (id1 == 3) {
4381                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4382                            } else {
4383                                pMidiRules[i++] = new MidiRuleUnknown;
4384                            }
4385                        }
4386                        else if (id1 != 0 || id2 != 0) {
4387                            pMidiRules[i++] = new MidiRuleUnknown;
4388                        }
4389                        //TODO: all the other types of rules
4390    
4391                        pMidiRules[i] = NULL;
4392                    }
4393              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
4394          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
4395    
4396          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          if (pFile->GetAutoLoad()) {
4397          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");              if (!pRegions) pRegions = new RegionList;
4398          pRegions = new Region*[Regions];              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4399          RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4400          unsigned int iRegion = 0;                  RIFF::List* rgn = lrgn->GetFirstSubList();
4401          while (rgn) {                  while (rgn) {
4402              if (rgn->GetListType() == LIST_TYPE_RGN) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4403                  pRegions[iRegion] = new Region(this, rgn);                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4404                  iRegion++;                          pRegions->push_back(new Region(this, rgn));
4405              }                      }
4406              rgn = lrgn->GetNextSubList();                      rgn = lrgn->GetNextSubList();
4407          }                  }
4408                    // Creating Region Key Table for fast lookup
4409          // Creating Region Key Table for fast lookup                  UpdateRegionKeyTable();
4410          for (uint iReg = 0; iReg < Regions; iReg++) {              }
4411              for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {          }
4412                  RegionKeyTable[iKey] = pRegions[iReg];  
4413            // own gig format extensions
4414            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4415            if (lst3LS) {
4416                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4417                if (ckSCSL) {
4418                    int headerSize = ckSCSL->ReadUint32();
4419                    int slotCount  = ckSCSL->ReadUint32();
4420                    if (slotCount) {
4421                        int slotSize  = ckSCSL->ReadUint32();
4422                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4423                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4424                        for (int i = 0; i < slotCount; ++i) {
4425                            _ScriptPooolEntry e;
4426                            e.fileOffset = ckSCSL->ReadUint32();
4427                            e.bypass     = ckSCSL->ReadUint32() & 1;
4428                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4429                            scriptPoolFileOffsets.push_back(e);
4430                        }
4431                    }
4432                }
4433            }
4434    
4435            __notify_progress(pProgress, 1.0f); // notify done
4436        }
4437    
4438        void Instrument::UpdateRegionKeyTable() {
4439            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4440            RegionList::iterator iter = pRegions->begin();
4441            RegionList::iterator end  = pRegions->end();
4442            for (; iter != end; ++iter) {
4443                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4444                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
4445                    RegionKeyTable[iKey] = pRegion;
4446              }              }
4447          }          }
4448      }      }
4449    
4450      Instrument::~Instrument() {      Instrument::~Instrument() {
4451          for (uint i = 0; i < Regions; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
4452              if (pRegions) {              delete pMidiRules[i];
4453                  if (pRegions[i]) delete (pRegions[i]);          }
4454            delete[] pMidiRules;
4455            if (pScriptRefs) delete pScriptRefs;
4456        }
4457    
4458        /**
4459         * Apply Instrument with all its Regions to the respective RIFF chunks.
4460         * You have to call File::Save() to make changes persistent.
4461         *
4462         * Usually there is absolutely no need to call this method explicitly.
4463         * It will be called automatically when File::Save() was called.
4464         *
4465         * @param pProgress - callback function for progress notification
4466         * @throws gig::Exception if samples cannot be dereferenced
4467         */
4468        void Instrument::UpdateChunks(progress_t* pProgress) {
4469            // first update base classes' chunks
4470            DLS::Instrument::UpdateChunks(pProgress);
4471    
4472            // update Regions' chunks
4473            {
4474                RegionList::iterator iter = pRegions->begin();
4475                RegionList::iterator end  = pRegions->end();
4476                for (; iter != end; ++iter)
4477                    (*iter)->UpdateChunks(pProgress);
4478            }
4479    
4480            // make sure 'lart' RIFF list chunk exists
4481            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
4482            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4483            // make sure '3ewg' RIFF chunk exists
4484            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4485            if (!_3ewg)  {
4486                File* pFile = (File*) GetParent();
4487    
4488                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4489                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4490                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4491                memset(_3ewg->LoadChunkData(), 0, size);
4492            }
4493            // update '3ewg' RIFF chunk
4494            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4495            store16(&pData[0], EffectSend);
4496            store32(&pData[2], Attenuation);
4497            store16(&pData[6], FineTune);
4498            store16(&pData[8], PitchbendRange);
4499            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4500                                        DimensionKeyRange.low << 1;
4501            pData[10] = dimkeystart;
4502            pData[11] = DimensionKeyRange.high;
4503    
4504            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4505                pData[32] = 0;
4506                pData[33] = 0;
4507            } else {
4508                for (int i = 0 ; pMidiRules[i] ; i++) {
4509                    pMidiRules[i]->UpdateChunks(pData);
4510              }              }
             delete[] pRegions;  
4511          }          }
4512    
4513            // own gig format extensions
4514           if (ScriptSlotCount()) {
4515               // make sure we have converted the original loaded script file
4516               // offsets into valid Script object pointers
4517               LoadScripts();
4518    
4519               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4520               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4521               const int slotCount = pScriptRefs->size();
4522               const int headerSize = 3 * sizeof(uint32_t);
4523               const int slotSize  = 2 * sizeof(uint32_t);
4524               const int totalChunkSize = headerSize + slotCount * slotSize;
4525               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4526               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4527               else ckSCSL->Resize(totalChunkSize);
4528               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4529               int pos = 0;
4530               store32(&pData[pos], headerSize);
4531               pos += sizeof(uint32_t);
4532               store32(&pData[pos], slotCount);
4533               pos += sizeof(uint32_t);
4534               store32(&pData[pos], slotSize);
4535               pos += sizeof(uint32_t);
4536               for (int i = 0; i < slotCount; ++i) {
4537                   // arbitrary value, the actual file offset will be updated in
4538                   // UpdateScriptFileOffsets() after the file has been resized
4539                   int bogusFileOffset = 0;
4540                   store32(&pData[pos], bogusFileOffset);
4541                   pos += sizeof(uint32_t);
4542                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4543                   pos += sizeof(uint32_t);
4544               }
4545           } else {
4546               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4547               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4548               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4549           }
4550        }
4551    
4552        void Instrument::UpdateScriptFileOffsets() {
4553           // own gig format extensions
4554           if (pScriptRefs && pScriptRefs->size() > 0) {
4555               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4556               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4557               const int slotCount = pScriptRefs->size();
4558               const int headerSize = 3 * sizeof(uint32_t);
4559               ckSCSL->SetPos(headerSize);
4560               for (int i = 0; i < slotCount; ++i) {
4561                   uint32_t fileOffset =
4562                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4563                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4564                        CHUNK_HEADER_SIZE;
4565                   ckSCSL->WriteUint32(&fileOffset);
4566                   // jump over flags entry (containing the bypass flag)
4567                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4568               }
4569           }        
4570      }      }
4571    
4572      /**      /**
# Line 1279  namespace gig { Line 4577  namespace gig {
4577       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4578       */       */
4579      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4580          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4581          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4582    
4583          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
4584              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
4585                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1296  namespace gig { Line 4595  namespace gig {
4595       * @see      GetNextRegion()       * @see      GetNextRegion()
4596       */       */
4597      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
4598          if (!Regions) return NULL;          if (!pRegions) return NULL;
4599          RegionIndex = 1;          RegionsIterator = pRegions->begin();
4600          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4601      }      }
4602    
4603      /**      /**
# Line 1310  namespace gig { Line 4609  namespace gig {
4609       * @see      GetFirstRegion()       * @see      GetFirstRegion()
4610       */       */
4611      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
4612          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (!pRegions) return NULL;
4613          return pRegions[RegionIndex++];          RegionsIterator++;
4614            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4615        }
4616    
4617        Region* Instrument::AddRegion() {
4618            // create new Region object (and its RIFF chunks)
4619            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
4620            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4621            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4622            Region* pNewRegion = new Region(this, rgn);
4623            pRegions->push_back(pNewRegion);
4624            Regions = pRegions->size();
4625            // update Region key table for fast lookup
4626            UpdateRegionKeyTable();
4627            // done
4628            return pNewRegion;
4629        }
4630    
4631        void Instrument::DeleteRegion(Region* pRegion) {
4632            if (!pRegions) return;
4633            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
4634            // update Region key table for fast lookup
4635            UpdateRegionKeyTable();
4636        }
4637    
4638        /**
4639         * Returns a MIDI rule of the instrument.
4640         *
4641         * The list of MIDI rules, at least in gig v3, always contains at
4642         * most two rules. The second rule can only be the DEF filter
4643         * (which currently isn't supported by libgig).
4644         *
4645         * @param i - MIDI rule number
4646         * @returns   pointer address to MIDI rule number i or NULL if there is none
4647         */
4648        MidiRule* Instrument::GetMidiRule(int i) {
4649            return pMidiRules[i];
4650        }
4651    
4652        /**
4653         * Adds the "controller trigger" MIDI rule to the instrument.
4654         *
4655         * @returns the new MIDI rule
4656         */
4657        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4658            delete pMidiRules[0];
4659            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4660            pMidiRules[0] = r;
4661            pMidiRules[1] = 0;
4662            return r;
4663        }
4664    
4665        /**
4666         * Adds the legato MIDI rule to the instrument.
4667         *
4668         * @returns the new MIDI rule
4669         */
4670        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4671            delete pMidiRules[0];
4672            MidiRuleLegato* r = new MidiRuleLegato;
4673            pMidiRules[0] = r;
4674            pMidiRules[1] = 0;
4675            return r;
4676        }
4677    
4678        /**
4679         * Adds the alternator MIDI rule to the instrument.
4680         *
4681         * @returns the new MIDI rule
4682         */
4683        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4684            delete pMidiRules[0];
4685            MidiRuleAlternator* r = new MidiRuleAlternator;
4686            pMidiRules[0] = r;
4687            pMidiRules[1] = 0;
4688            return r;
4689        }
4690    
4691        /**
4692         * Deletes a MIDI rule from the instrument.
4693         *
4694         * @param i - MIDI rule number
4695         */
4696        void Instrument::DeleteMidiRule(int i) {
4697            delete pMidiRules[i];
4698            pMidiRules[i] = 0;
4699        }
4700    
4701        void Instrument::LoadScripts() {
4702            if (pScriptRefs) return;
4703            pScriptRefs = new std::vector<_ScriptPooolRef>;
4704            if (scriptPoolFileOffsets.empty()) return;
4705            File* pFile = (File*) GetParent();
4706            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4707                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4708                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4709                    ScriptGroup* group = pFile->GetScriptGroup(i);
4710                    for (uint s = 0; group->GetScript(s); ++s) {
4711                        Script* script = group->GetScript(s);
4712                        if (script->pChunk) {
4713                            uint32_t offset = script->pChunk->GetFilePos() -
4714                                              script->pChunk->GetPos() -
4715                                              CHUNK_HEADER_SIZE;
4716                            if (offset == soughtOffset)
4717                            {
4718                                _ScriptPooolRef ref;
4719                                ref.script = script;
4720                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4721                                pScriptRefs->push_back(ref);
4722                                break;
4723                            }
4724                        }
4725                    }
4726                }
4727            }
4728            // we don't need that anymore
4729            scriptPoolFileOffsets.clear();
4730        }
4731    
4732        /** @brief Get instrument script (gig format extension).
4733         *
4734         * Returns the real-time instrument script of instrument script slot
4735         * @a index.
4736         *
4737         * @note This is an own format extension which did not exist i.e. in the
4738         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4739         * gigedit.
4740         *
4741         * @param index - instrument script slot index
4742         * @returns script or NULL if index is out of bounds
4743         */
4744        Script* Instrument::GetScriptOfSlot(uint index) {
4745            LoadScripts();
4746            if (index >= pScriptRefs->size()) return NULL;
4747            return pScriptRefs->at(index).script;
4748        }
4749    
4750        /** @brief Add new instrument script slot (gig format extension).
4751         *
4752         * Add the given real-time instrument script reference to this instrument,
4753         * which shall be executed by the sampler for for this instrument. The
4754         * script will be added to the end of the script list of this instrument.
4755         * The positions of the scripts in the Instrument's Script list are
4756         * relevant, because they define in which order they shall be executed by
4757         * the sampler. For this reason it is also legal to add the same script
4758         * twice to an instrument, for example you might have a script called
4759         * "MyFilter" which performs an event filter task, and you might have
4760         * another script called "MyNoteTrigger" which triggers new notes, then you
4761         * might for example have the following list of scripts on the instrument:
4762         *
4763         * 1. Script "MyFilter"
4764         * 2. Script "MyNoteTrigger"
4765         * 3. Script "MyFilter"
4766         *
4767         * Which would make sense, because the 2nd script launched new events, which
4768         * you might need to filter as well.
4769         *
4770         * There are two ways to disable / "bypass" scripts. You can either disable
4771         * a script locally for the respective script slot on an instrument (i.e. by
4772         * passing @c false to the 2nd argument of this method, or by calling
4773         * SetScriptBypassed()). Or you can disable a script globally for all slots
4774         * and all instruments by setting Script::Bypass.
4775         *
4776         * @note This is an own format extension which did not exist i.e. in the
4777         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4778         * gigedit.
4779         *
4780         * @param pScript - script that shall be executed for this instrument
4781         * @param bypass  - if enabled, the sampler shall skip executing this
4782         *                  script (in the respective list position)
4783         * @see SetScriptBypassed()
4784         */
4785        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4786            LoadScripts();
4787            _ScriptPooolRef ref = { pScript, bypass };
4788            pScriptRefs->push_back(ref);
4789        }
4790    
4791        /** @brief Flip two script slots with each other (gig format extension).
4792         *
4793         * Swaps the position of the two given scripts in the Instrument's Script
4794         * list. The positions of the scripts in the Instrument's Script list are
4795         * relevant, because they define in which order they shall be executed by
4796         * the sampler.
4797         *
4798         * @note This is an own format extension which did not exist i.e. in the
4799         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4800         * gigedit.
4801         *
4802         * @param index1 - index of the first script slot to swap
4803         * @param index2 - index of the second script slot to swap
4804         */
4805        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4806            LoadScripts();
4807            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4808                return;
4809            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4810            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4811            (*pScriptRefs)[index2] = tmp;
4812        }
4813    
4814        /** @brief Remove script slot.
4815         *
4816         * Removes the script slot with the given slot index.
4817         *
4818         * @param index - index of script slot to remove
4819         */
4820        void Instrument::RemoveScriptSlot(uint index) {
4821            LoadScripts();
4822            if (index >= pScriptRefs->size()) return;
4823            pScriptRefs->erase( pScriptRefs->begin() + index );
4824        }
4825    
4826        /** @brief Remove reference to given Script (gig format extension).
4827         *
4828         * This will remove all script slots on the instrument which are referencing
4829         * the given script.
4830         *
4831         * @note This is an own format extension which did not exist i.e. in the
4832         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4833         * gigedit.
4834         *
4835         * @param pScript - script reference to remove from this instrument
4836         * @see RemoveScriptSlot()
4837         */
4838        void Instrument::RemoveScript(Script* pScript) {
4839            LoadScripts();
4840            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4841                if ((*pScriptRefs)[i].script == pScript) {
4842                    pScriptRefs->erase( pScriptRefs->begin() + i );
4843                }
4844            }
4845        }
4846    
4847        /** @brief Instrument's amount of script slots.
4848         *
4849         * This method returns the amount of script slots this instrument currently
4850         * uses.
4851         *
4852         * A script slot is a reference of a real-time instrument script to be
4853         * executed by the sampler. The scripts will be executed by the sampler in
4854         * sequence of the slots. One (same) script may be referenced multiple
4855         * times in different slots.
4856         *
4857         * @note This is an own format extension which did not exist i.e. in the
4858         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4859         * gigedit.
4860         */
4861        uint Instrument::ScriptSlotCount() const {
4862            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4863        }
4864    
4865        /** @brief Whether script execution shall be skipped.
4866         *
4867         * Defines locally for the Script reference slot in the Instrument's Script
4868         * list, whether the script shall be skipped by the sampler regarding
4869         * execution.
4870         *
4871         * It is also possible to ignore exeuction of the script globally, for all
4872         * slots and for all instruments by setting Script::Bypass.
4873         *
4874         * @note This is an own format extension which did not exist i.e. in the
4875         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4876         * gigedit.
4877         *
4878         * @param index - index of the script slot on this instrument
4879         * @see Script::Bypass
4880         */
4881        bool Instrument::IsScriptSlotBypassed(uint index) {
4882            if (index >= ScriptSlotCount()) return false;
4883            return pScriptRefs ? pScriptRefs->at(index).bypass
4884                               : scriptPoolFileOffsets.at(index).bypass;
4885            
4886        }
4887    
4888        /** @brief Defines whether execution shall be skipped.
4889         *
4890         * You can call this method to define locally whether or whether not the
4891         * given script slot shall be executed by the sampler.
4892         *
4893         * @note This is an own format extension which did not exist i.e. in the
4894         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4895         * gigedit.
4896         *
4897         * @param index - script slot index on this instrument
4898         * @param bBypass - if true, the script slot will be skipped by the sampler
4899         * @see Script::Bypass
4900         */
4901        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4902            if (index >= ScriptSlotCount()) return;
4903            if (pScriptRefs)
4904                pScriptRefs->at(index).bypass = bBypass;
4905            else
4906                scriptPoolFileOffsets.at(index).bypass = bBypass;
4907        }
4908    
4909        /**
4910         * Make a (semi) deep copy of the Instrument object given by @a orig
4911         * and assign it to this object.
4912         *
4913         * Note that all sample pointers referenced by @a orig are simply copied as
4914         * memory address. Thus the respective samples are shared, not duplicated!
4915         *
4916         * @param orig - original Instrument object to be copied from
4917         */
4918        void Instrument::CopyAssign(const Instrument* orig) {
4919            CopyAssign(orig, NULL);
4920        }
4921            
4922        /**
4923         * Make a (semi) deep copy of the Instrument object given by @a orig
4924         * and assign it to this object.
4925         *
4926         * @param orig - original Instrument object to be copied from
4927         * @param mSamples - crosslink map between the foreign file's samples and
4928         *                   this file's samples
4929         */
4930        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4931            // handle base class
4932            // (without copying DLS region stuff)
4933            DLS::Instrument::CopyAssignCore(orig);
4934            
4935            // handle own member variables
4936            Attenuation = orig->Attenuation;
4937            EffectSend = orig->EffectSend;
4938            FineTune = orig->FineTune;
4939            PitchbendRange = orig->PitchbendRange;
4940            PianoReleaseMode = orig->PianoReleaseMode;
4941            DimensionKeyRange = orig->DimensionKeyRange;
4942            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
4943            pScriptRefs = orig->pScriptRefs;
4944            
4945            // free old midi rules
4946            for (int i = 0 ; pMidiRules[i] ; i++) {
4947                delete pMidiRules[i];
4948            }
4949            //TODO: MIDI rule copying
4950            pMidiRules[0] = NULL;
4951            
4952            // delete all old regions
4953            while (Regions) DeleteRegion(GetFirstRegion());
4954            // create new regions and copy them from original
4955            {
4956                RegionList::const_iterator it = orig->pRegions->begin();
4957                for (int i = 0; i < orig->Regions; ++i, ++it) {
4958                    Region* dstRgn = AddRegion();
4959                    //NOTE: Region does semi-deep copy !
4960                    dstRgn->CopyAssign(
4961                        static_cast<gig::Region*>(*it),
4962                        mSamples
4963                    );
4964                }
4965            }
4966    
4967            UpdateRegionKeyTable();
4968        }
4969    
4970    
4971    // *************** Group ***************
4972    // *
4973    
4974        /** @brief Constructor.
4975         *
4976         * @param file   - pointer to the gig::File object
4977         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
4978         *                 NULL if this is a new Group
4979         */
4980        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
4981            pFile      = file;
4982            pNameChunk = ck3gnm;
4983            ::LoadString(pNameChunk, Name);
4984        }
4985    
4986        Group::~Group() {
4987            // remove the chunk associated with this group (if any)
4988            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4989        }
4990    
4991        /** @brief Update chunks with current group settings.
4992         *
4993         * Apply current Group field values to the respective chunks. You have
4994         * to call File::Save() to make changes persistent.
4995         *
4996         * Usually there is absolutely no need to call this method explicitly.
4997         * It will be called automatically when File::Save() was called.
4998         *
4999         * @param pProgress - callback function for progress notification
5000         */
5001        void Group::UpdateChunks(progress_t* pProgress) {
5002            // make sure <3gri> and <3gnl> list chunks exist
5003            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5004            if (!_3gri) {
5005                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5006                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5007            }
5008            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5009            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5010    
5011            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5012                // v3 has a fixed list of 128 strings, find a free one
5013                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5014                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5015                        pNameChunk = ck;
5016                        break;
5017                    }
5018                }
5019            }
5020    
5021            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5022            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5023        }
5024    
5025        /**
5026         * Returns the first Sample of this Group. You have to call this method
5027         * once before you use GetNextSample().
5028         *
5029         * <b>Notice:</b> this method might block for a long time, in case the
5030         * samples of this .gig file were not scanned yet
5031         *
5032         * @returns  pointer address to first Sample or NULL if there is none
5033         *           applied to this Group
5034         * @see      GetNextSample()
5035         */
5036        Sample* Group::GetFirstSample() {
5037            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5038            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5039                if (pSample->GetGroup() == this) return pSample;
5040            }
5041            return NULL;
5042        }
5043    
5044        /**
5045         * Returns the next Sample of the Group. You have to call
5046         * GetFirstSample() once before you can use this method. By calling this
5047         * method multiple times it iterates through the Samples assigned to
5048         * this Group.
5049         *
5050         * @returns  pointer address to the next Sample of this Group or NULL if
5051         *           end reached
5052         * @see      GetFirstSample()
5053         */
5054        Sample* Group::GetNextSample() {
5055            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5056            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5057                if (pSample->GetGroup() == this) return pSample;
5058            }
5059            return NULL;
5060        }
5061    
5062        /**
5063         * Move Sample given by \a pSample from another Group to this Group.
5064         */
5065        void Group::AddSample(Sample* pSample) {
5066            pSample->pGroup = this;
5067        }
5068    
5069        /**
5070         * Move all members of this group to another group (preferably the 1st
5071         * one except this). This method is called explicitly by
5072         * File::DeleteGroup() thus when a Group was deleted. This code was
5073         * intentionally not placed in the destructor!
5074         */
5075        void Group::MoveAll() {
5076            // get "that" other group first
5077            Group* pOtherGroup = NULL;
5078            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5079                if (pOtherGroup != this) break;
5080            }
5081            if (!pOtherGroup) throw Exception(
5082                "Could not move samples to another group, since there is no "
5083                "other Group. This is a bug, report it!"
5084            );
5085            // now move all samples of this group to the other group
5086            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5087                pOtherGroup->AddSample(pSample);
5088            }
5089      }      }
5090    
5091    
# Line 1319  namespace gig { Line 5093  namespace gig {
5093  // *************** File ***************  // *************** File ***************
5094  // *  // *
5095    
5096        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5097        const DLS::version_t File::VERSION_2 = {
5098            0, 2, 19980628 & 0xffff, 19980628 >> 16
5099        };
5100    
5101        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5102        const DLS::version_t File::VERSION_3 = {
5103            0, 3, 20030331 & 0xffff, 20030331 >> 16
5104        };
5105    
5106        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5107            { CHUNK_ID_IARL, 256 },
5108            { CHUNK_ID_IART, 128 },
5109            { CHUNK_ID_ICMS, 128 },
5110            { CHUNK_ID_ICMT, 1024 },
5111            { CHUNK_ID_ICOP, 128 },
5112            { CHUNK_ID_ICRD, 128 },
5113            { CHUNK_ID_IENG, 128 },
5114            { CHUNK_ID_IGNR, 128 },
5115            { CHUNK_ID_IKEY, 128 },
5116            { CHUNK_ID_IMED, 128 },
5117            { CHUNK_ID_INAM, 128 },
5118            { CHUNK_ID_IPRD, 128 },
5119            { CHUNK_ID_ISBJ, 128 },
5120            { CHUNK_ID_ISFT, 128 },
5121            { CHUNK_ID_ISRC, 128 },
5122            { CHUNK_ID_ISRF, 128 },
5123            { CHUNK_ID_ITCH, 128 },
5124            { 0, 0 }
5125        };
5126    
5127        File::File() : DLS::File() {
5128            bAutoLoad = true;
5129            *pVersion = VERSION_3;
5130            pGroups = NULL;
5131            pScriptGroups = NULL;
5132            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5133            pInfo->ArchivalLocation = String(256, ' ');
5134    
5135            // add some mandatory chunks to get the file chunks in right
5136            // order (INFO chunk will be moved to first position later)
5137            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5138            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5139            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5140    
5141            GenerateDLSID();
5142        }
5143    
5144      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5145          pSamples     = NULL;          bAutoLoad = true;
5146          pInstruments = NULL;          pGroups = NULL;
5147            pScriptGroups = NULL;
5148            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5149      }      }
5150    
5151      Sample* File::GetFirstSample() {      File::~File() {
5152          if (!pSamples) LoadSamples();          if (pGroups) {
5153                std::list<Group*>::iterator iter = pGroups->begin();
5154                std::list<Group*>::iterator end  = pGroups->end();
5155                while (iter != end) {
5156                    delete *iter;
5157                    ++iter;
5158                }
5159                delete pGroups;
5160            }
5161            if (pScriptGroups) {
5162                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5163                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5164                while (iter != end) {
5165                    delete *iter;
5166                    ++iter;
5167                }
5168                delete pScriptGroups;
5169            }
5170        }
5171    
5172        Sample* File::GetFirstSample(progress_t* pProgress) {
5173            if (!pSamples) LoadSamples(pProgress);
5174          if (!pSamples) return NULL;          if (!pSamples) return NULL;
5175          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
5176          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1336  namespace gig { Line 5181  namespace gig {
5181          SamplesIterator++;          SamplesIterator++;
5182          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5183      }      }
5184        
5185        /**
5186         * Returns Sample object of @a index.
5187         *
5188         * @returns sample object or NULL if index is out of bounds
5189         */
5190        Sample* File::GetSample(uint index) {
5191            if (!pSamples) LoadSamples();
5192            if (!pSamples) return NULL;
5193            DLS::File::SampleList::iterator it = pSamples->begin();
5194            for (int i = 0; i < index; ++i) {
5195                ++it;
5196                if (it == pSamples->end()) return NULL;
5197            }
5198            if (it == pSamples->end()) return NULL;
5199            return static_cast<gig::Sample*>( *it );
5200        }
5201    
5202      void File::LoadSamples() {      /** @brief Add a new sample.
5203          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);       *
5204          if (wvpl) {       * This will create a new Sample object for the gig file. You have to
5205              unsigned long wvplFileOffset = wvpl->GetFilePos();       * call Save() to make this persistent to the file.
5206              RIFF::List* wave = wvpl->GetFirstSubList();       *
5207              while (wave) {       * @returns pointer to new Sample object
5208                  if (wave->GetListType() == LIST_TYPE_WAVE) {       */
5209                      if (!pSamples) pSamples = new SampleList;      Sample* File::AddSample() {
5210                      unsigned long waveFileOffset = wave->GetFilePos();         if (!pSamples) LoadSamples();
5211                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));         __ensureMandatoryChunksExist();
5212           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
5213           // create new Sample object and its respective 'wave' list chunk
5214           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5215           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5216    
5217           // add mandatory chunks to get the chunks in right order
5218           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5219           wave->AddSubList(LIST_TYPE_INFO);
5220    
5221           pSamples->push_back(pSample);
5222           return pSample;
5223        }
5224    
5225        /** @brief Delete a sample.
5226         *
5227         * This will delete the given Sample object from the gig file. Any
5228         * references to this sample from Regions and DimensionRegions will be
5229         * removed. You have to call Save() to make this persistent to the file.
5230         *
5231         * @param pSample - sample to delete
5232         * @throws gig::Exception if given sample could not be found
5233         */
5234        void File::DeleteSample(Sample* pSample) {
5235            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5236            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5237            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5238            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5239            pSamples->erase(iter);
5240            delete pSample;
5241    
5242            SampleList::iterator tmp = SamplesIterator;
5243            // remove all references to the sample
5244            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5245                 instrument = GetNextInstrument()) {
5246                for (Region* region = instrument->GetFirstRegion() ; region ;
5247                     region = instrument->GetNextRegion()) {
5248    
5249                    if (region->GetSample() == pSample) region->SetSample(NULL);
5250    
5251                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5252                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5253                        if (d->pSample == pSample) d->pSample = NULL;
5254                  }                  }
                 wave = wvpl->GetNextSubList();  
5255              }              }
5256          }          }
5257          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          SamplesIterator = tmp; // restore iterator
5258        }
5259    
5260        void File::LoadSamples() {
5261            LoadSamples(NULL);
5262        }
5263    
5264        void File::LoadSamples(progress_t* pProgress) {
5265            // Groups must be loaded before samples, because samples will try
5266            // to resolve the group they belong to
5267            if (!pGroups) LoadGroups();
5268    
5269            if (!pSamples) pSamples = new SampleList;
5270    
5271            RIFF::File* file = pRIFF;
5272    
5273            // just for progress calculation
5274            int iSampleIndex  = 0;
5275            int iTotalSamples = WavePoolCount;
5276    
5277            // check if samples should be loaded from extension files
5278            int lastFileNo = 0;
5279            for (int i = 0 ; i < WavePoolCount ; i++) {
5280                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5281            }
5282            String name(pRIFF->GetFileName());
5283            int nameLen = name.length();
5284            char suffix[6];
5285            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5286    
5287            for (int fileNo = 0 ; ; ) {
5288                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5289                if (wvpl) {
5290                    unsigned long wvplFileOffset = wvpl->GetFilePos();
5291                    RIFF::List* wave = wvpl->GetFirstSubList();
5292                    while (wave) {
5293                        if (wave->GetListType() == LIST_TYPE_WAVE) {
5294                            // notify current progress
5295                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5296                            __notify_progress(pProgress, subprogress);
5297    
5298                            unsigned long waveFileOffset = wave->GetFilePos();
5299                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5300    
5301                            iSampleIndex++;
5302                        }
5303                        wave = wvpl->GetNextSubList();
5304                    }
5305    
5306                    if (fileNo == lastFileNo) break;
5307    
5308                    // open extension file (*.gx01, *.gx02, ...)
5309                    fileNo++;
5310                    sprintf(suffix, ".gx%02d", fileNo);
5311                    name.replace(nameLen, 5, suffix);
5312                    file = new RIFF::File(name);
5313                    ExtensionFiles.push_back(file);
5314                } else break;
5315            }
5316    
5317            __notify_progress(pProgress, 1.0); // notify done
5318      }      }
5319    
5320      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
5321          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
5322          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5323          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
5324          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5325      }      }
5326    
5327      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
5328          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5329          InstrumentsIterator++;          InstrumentsIterator++;
5330          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5331      }      }
5332    
5333      /**      /**
5334       * Returns the instrument with the given index.       * Returns the instrument with the given index.
5335       *       *
5336         * @param index     - number of the sought instrument (0..n)
5337         * @param pProgress - optional: callback function for progress notification
5338       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
5339       */       */
5340      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
5341          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
5342                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
5343    
5344                // sample loading subtask
5345                progress_t subprogress;
5346                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5347                __notify_progress(&subprogress, 0.0f);
5348                if (GetAutoLoad())
5349                    GetFirstSample(&subprogress); // now force all samples to be loaded
5350                __notify_progress(&subprogress, 1.0f);
5351    
5352                // instrument loading subtask
5353                if (pProgress && pProgress->callback) {
5354                    subprogress.__range_min = subprogress.__range_max;
5355                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
5356                }
5357                __notify_progress(&subprogress, 0.0f);
5358                LoadInstruments(&subprogress);
5359                __notify_progress(&subprogress, 1.0f);
5360            }
5361          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
5362          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
5363          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5364              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5365              InstrumentsIterator++;              InstrumentsIterator++;
5366          }          }
5367          return NULL;          return NULL;
5368      }      }
5369    
5370        /** @brief Add a new instrument definition.
5371         *
5372         * This will create a new Instrument object for the gig file. You have
5373         * to call Save() to make this persistent to the file.
5374         *
5375         * @returns pointer to new Instrument object
5376         */
5377        Instrument* File::AddInstrument() {
5378           if (!pInstruments) LoadInstruments();
5379           __ensureMandatoryChunksExist();
5380           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5381           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5382    
5383           // add mandatory chunks to get the chunks in right order
5384           lstInstr->AddSubList(LIST_TYPE_INFO);
5385           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5386    
5387           Instrument* pInstrument = new Instrument(this, lstInstr);
5388           pInstrument->GenerateDLSID();
5389    
5390           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5391    
5392           // this string is needed for the gig to be loadable in GSt:
5393           pInstrument->pInfo->Software = "Endless Wave";
5394    
5395           pInstruments->push_back(pInstrument);
5396           return pInstrument;
5397        }
5398        
5399        /** @brief Add a duplicate of an existing instrument.
5400         *
5401         * Duplicates the instrument definition given by @a orig and adds it
5402         * to this file. This allows in an instrument editor application to
5403         * easily create variations of an instrument, which will be stored in
5404         * the same .gig file, sharing i.e. the same samples.
5405         *
5406         * Note that all sample pointers referenced by @a orig are simply copied as
5407         * memory address. Thus the respective samples are shared, not duplicated!
5408         *
5409         * You have to call Save() to make this persistent to the file.
5410         *
5411         * @param orig - original instrument to be copied
5412         * @returns duplicated copy of the given instrument
5413         */
5414        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5415            Instrument* instr = AddInstrument();
5416            instr->CopyAssign(orig);
5417            return instr;
5418        }
5419        
5420        /** @brief Add content of another existing file.
5421         *
5422         * Duplicates the samples, groups and instruments of the original file
5423         * given by @a pFile and adds them to @c this File. In case @c this File is
5424         * a new one that you haven't saved before, then you have to call
5425         * SetFileName() before calling AddContentOf(), because this method will
5426         * automatically save this file during operation, which is required for
5427         * writing the sample waveform data by disk streaming.
5428         *
5429         * @param pFile - original file whose's content shall be copied from
5430         */
5431        void File::AddContentOf(File* pFile) {
5432            static int iCallCount = -1;
5433            iCallCount++;
5434            std::map<Group*,Group*> mGroups;
5435            std::map<Sample*,Sample*> mSamples;
5436            
5437            // clone sample groups
5438            for (int i = 0; pFile->GetGroup(i); ++i) {
5439                Group* g = AddGroup();
5440                g->Name =
5441                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5442                mGroups[pFile->GetGroup(i)] = g;
5443            }
5444            
5445            // clone samples (not waveform data here yet)
5446            for (int i = 0; pFile->GetSample(i); ++i) {
5447                Sample* s = AddSample();
5448                s->CopyAssignMeta(pFile->GetSample(i));
5449                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5450                mSamples[pFile->GetSample(i)] = s;
5451            }
5452            
5453            //BUG: For some reason this method only works with this additional
5454            //     Save() call in between here.
5455            //
5456            // Important: The correct one of the 2 Save() methods has to be called
5457            // here, depending on whether the file is completely new or has been
5458            // saved to disk already, otherwise it will result in data corruption.
5459            if (pRIFF->IsNew())
5460                Save(GetFileName());
5461            else
5462                Save();
5463            
5464            // clone instruments
5465            // (passing the crosslink table here for the cloned samples)
5466            for (int i = 0; pFile->GetInstrument(i); ++i) {
5467                Instrument* instr = AddInstrument();
5468                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5469            }
5470            
5471            // Mandatory: file needs to be saved to disk at this point, so this
5472            // file has the correct size and data layout for writing the samples'
5473            // waveform data to disk.
5474            Save();
5475            
5476            // clone samples' waveform data
5477            // (using direct read & write disk streaming)
5478            for (int i = 0; pFile->GetSample(i); ++i) {
5479                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5480            }
5481        }
5482    
5483        /** @brief Delete an instrument.
5484         *
5485         * This will delete the given Instrument object from the gig file. You
5486         * have to call Save() to make this persistent to the file.
5487         *
5488         * @param pInstrument - instrument to delete
5489         * @throws gig::Exception if given instrument could not be found
5490         */
5491        void File::DeleteInstrument(Instrument* pInstrument) {
5492            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5493            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5494            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5495            pInstruments->erase(iter);
5496            delete pInstrument;
5497        }
5498    
5499      void File::LoadInstruments() {      void File::LoadInstruments() {
5500            LoadInstruments(NULL);
5501        }
5502    
5503        void File::LoadInstruments(progress_t* pProgress) {
5504            if (!pInstruments) pInstruments = new InstrumentList;
5505          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5506          if (lstInstruments) {          if (lstInstruments) {
5507                int iInstrumentIndex = 0;
5508              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
5509              while (lstInstr) {              while (lstInstr) {
5510                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
5511                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
5512                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
5513                        __notify_progress(pProgress, localProgress);
5514    
5515                        // divide local progress into subprogress for loading current Instrument
5516                        progress_t subprogress;
5517                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5518    
5519                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5520    
5521                        iInstrumentIndex++;
5522                  }                  }
5523                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
5524              }              }
5525                __notify_progress(pProgress, 1.0); // notify done
5526          }          }
5527          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
5528    
5529        /// Updates the 3crc chunk with the checksum of a sample. The
5530        /// update is done directly to disk, as this method is called
5531        /// after File::Save()
5532        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5533            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5534            if (!_3crc) return;
5535    
5536            // get the index of the sample
5537            int iWaveIndex = -1;
5538            File::SampleList::iterator iter = pSamples->begin();
5539            File::SampleList::iterator end  = pSamples->end();
5540            for (int index = 0; iter != end; ++iter, ++index) {
5541                if (*iter == pSample) {
5542                    iWaveIndex = index;
5543                    break;
5544                }
5545            }
5546            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5547    
5548            // write the CRC-32 checksum to disk
5549            _3crc->SetPos(iWaveIndex * 8);
5550            uint32_t tmp = 1;
5551            _3crc->WriteUint32(&tmp); // unknown, always 1?
5552            _3crc->WriteUint32(&crc);
5553        }
5554    
5555        Group* File::GetFirstGroup() {
5556            if (!pGroups) LoadGroups();
5557            // there must always be at least one group
5558            GroupsIterator = pGroups->begin();
5559            return *GroupsIterator;
5560        }
5561    
5562        Group* File::GetNextGroup() {
5563            if (!pGroups) return NULL;
5564            ++GroupsIterator;
5565            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5566        }
5567    
5568        /**
5569         * Returns the group with the given index.
5570         *
5571         * @param index - number of the sought group (0..n)
5572         * @returns sought group or NULL if there's no such group
5573         */
5574        Group* File::GetGroup(uint index) {
5575            if (!pGroups) LoadGroups();
5576            GroupsIterator = pGroups->begin();
5577            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5578                if (i == index) return *GroupsIterator;
5579                ++GroupsIterator;
5580            }
5581            return NULL;
5582        }
5583    
5584        /**
5585         * Returns the group with the given group name.
5586         *
5587         * Note: group names don't have to be unique in the gig format! So there
5588         * can be multiple groups with the same name. This method will simply
5589         * return the first group found with the given name.
5590         *
5591         * @param name - name of the sought group
5592         * @returns sought group or NULL if there's no group with that name
5593         */
5594        Group* File::GetGroup(String name) {
5595            if (!pGroups) LoadGroups();
5596            GroupsIterator = pGroups->begin();
5597            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5598                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5599            return NULL;
5600        }
5601    
5602        Group* File::AddGroup() {
5603            if (!pGroups) LoadGroups();
5604            // there must always be at least one group
5605            __ensureMandatoryChunksExist();
5606            Group* pGroup = new Group(this, NULL);
5607            pGroups->push_back(pGroup);
5608            return pGroup;
5609        }
5610    
5611        /** @brief Delete a group and its samples.
5612         *
5613         * This will delete the given Group object and all the samples that
5614         * belong to this group from the gig file. You have to call Save() to
5615         * make this persistent to the file.
5616         *
5617         * @param pGroup - group to delete
5618         * @throws gig::Exception if given group could not be found
5619         */
5620        void File::DeleteGroup(Group* pGroup) {
5621            if (!pGroups) LoadGroups();
5622            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5623            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5624            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5625            // delete all members of this group
5626            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5627                DeleteSample(pSample);
5628            }
5629            // now delete this group object
5630            pGroups->erase(iter);
5631            delete pGroup;
5632        }
5633    
5634        /** @brief Delete a group.
5635         *
5636         * This will delete the given Group object from the gig file. All the
5637         * samples that belong to this group will not be deleted, but instead
5638         * be moved to another group. You have to call Save() to make this
5639         * persistent to the file.
5640         *
5641         * @param pGroup - group to delete
5642         * @throws gig::Exception if given group could not be found
5643         */
5644        void File::DeleteGroupOnly(Group* pGroup) {
5645            if (!pGroups) LoadGroups();
5646            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5647            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5648            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5649            // move all members of this group to another group
5650            pGroup->MoveAll();
5651            pGroups->erase(iter);
5652            delete pGroup;
5653        }
5654    
5655        void File::LoadGroups() {
5656            if (!pGroups) pGroups = new std::list<Group*>;
5657            // try to read defined groups from file
5658            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5659            if (lst3gri) {
5660                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5661                if (lst3gnl) {
5662                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5663                    while (ck) {
5664                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5665                            if (pVersion && pVersion->major == 3 &&
5666                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5667    
5668                            pGroups->push_back(new Group(this, ck));
5669                        }
5670                        ck = lst3gnl->GetNextSubChunk();
5671                    }
5672                }
5673            }
5674            // if there were no group(s), create at least the mandatory default group
5675            if (!pGroups->size()) {
5676                Group* pGroup = new Group(this, NULL);
5677                pGroup->Name = "Default Group";
5678                pGroups->push_back(pGroup);
5679            }
5680        }
5681    
5682        /** @brief Get instrument script group (by index).
5683         *
5684         * Returns the real-time instrument script group with the given index.
5685         *
5686         * @param index - number of the sought group (0..n)
5687         * @returns sought script group or NULL if there's no such group
5688         */
5689        ScriptGroup* File::GetScriptGroup(uint index) {
5690            if (!pScriptGroups) LoadScriptGroups();
5691            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5692            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5693                if (i == index) return *it;
5694            return NULL;
5695        }
5696    
5697        /** @brief Get instrument script group (by name).
5698         *
5699         * Returns the first real-time instrument script group found with the given
5700         * group name. Note that group names may not necessarily be unique.
5701         *
5702         * @param name - name of the sought script group
5703         * @returns sought script group or NULL if there's no such group
5704         */
5705        ScriptGroup* File::GetScriptGroup(const String& name) {
5706            if (!pScriptGroups) LoadScriptGroups();
5707            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5708            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5709                if ((*it)->Name == name) return *it;
5710            return NULL;
5711        }
5712    
5713        /** @brief Add new instrument script group.
5714         *
5715         * Adds a new, empty real-time instrument script group to the file.
5716         *
5717         * You have to call Save() to make this persistent to the file.
5718         *
5719         * @return new empty script group
5720         */
5721        ScriptGroup* File::AddScriptGroup() {
5722            if (!pScriptGroups) LoadScriptGroups();
5723            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5724            pScriptGroups->push_back(pScriptGroup);
5725            return pScriptGroup;
5726        }
5727    
5728        /** @brief Delete an instrument script group.
5729         *
5730         * This will delete the given real-time instrument script group and all its
5731         * instrument scripts it contains. References inside instruments that are
5732         * using the deleted scripts will be removed from the respective instruments
5733         * accordingly.
5734         *
5735         * You have to call Save() to make this persistent to the file.
5736         *
5737         * @param pScriptGroup - script group to delete
5738         * @throws gig::Exception if given script group could not be found
5739         */
5740        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5741            if (!pScriptGroups) LoadScriptGroups();
5742            std::list<ScriptGroup*>::iterator iter =
5743                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5744            if (iter == pScriptGroups->end())
5745                throw gig::Exception("Could not delete script group, could not find given script group");
5746            pScriptGroups->erase(iter);
5747            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5748                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5749            if (pScriptGroup->pList)
5750                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5751            delete pScriptGroup;
5752        }
5753    
5754        void File::LoadScriptGroups() {
5755            if (pScriptGroups) return;
5756            pScriptGroups = new std::list<ScriptGroup*>;
5757            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5758            if (lstLS) {
5759                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5760                     lst = lstLS->GetNextSubList())
5761                {
5762                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5763                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5764                    }
5765                }
5766            }
5767        }
5768    
5769        /**
5770         * Apply all the gig file's current instruments, samples, groups and settings
5771         * to the respective RIFF chunks. You have to call Save() to make changes
5772         * persistent.
5773         *
5774         * Usually there is absolutely no need to call this method explicitly.
5775         * It will be called automatically when File::Save() was called.
5776         *
5777         * @param pProgress - callback function for progress notification
5778         * @throws Exception - on errors
5779         */
5780        void File::UpdateChunks(progress_t* pProgress) {
5781            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5782    
5783            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5784    
5785            // update own gig format extension chunks
5786            // (not part of the GigaStudio 4 format)
5787            //
5788            // This must be performed before writing the chunks for instruments,
5789            // because the instruments' script slots will write the file offsets
5790            // of the respective instrument script chunk as reference.
5791            if (pScriptGroups) {
5792                RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5793                if (pScriptGroups->empty()) {
5794                    if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5795                } else {
5796                    if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5797    
5798                    // Update instrument script (group) chunks.
5799    
5800                    for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5801                         it != pScriptGroups->end(); ++it)
5802                    {
5803                        (*it)->UpdateChunks(pProgress);
5804                    }
5805                }
5806            }
5807    
5808            // first update base class's chunks
5809            DLS::File::UpdateChunks(pProgress);
5810    
5811            if (newFile) {
5812                // INFO was added by Resource::UpdateChunks - make sure it
5813                // is placed first in file
5814                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
5815                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5816                if (first != info) {
5817                    pRIFF->MoveSubChunk(info, first);
5818                }
5819            }
5820    
5821            // update group's chunks
5822            if (pGroups) {
5823                // make sure '3gri' and '3gnl' list chunks exist
5824                // (before updating the Group chunks)
5825                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5826                if (!_3gri) {
5827                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5828                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5829                }
5830                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5831                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5832    
5833                // v3: make sure the file has 128 3gnm chunks
5834                // (before updating the Group chunks)
5835                if (pVersion && pVersion->major == 3) {
5836                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5837                    for (int i = 0 ; i < 128 ; i++) {
5838                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5839                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5840                    }
5841                }
5842    
5843                std::list<Group*>::iterator iter = pGroups->begin();
5844                std::list<Group*>::iterator end  = pGroups->end();
5845                for (; iter != end; ++iter) {
5846                    (*iter)->UpdateChunks(pProgress);
5847                }
5848            }
5849    
5850            // update einf chunk
5851    
5852            // The einf chunk contains statistics about the gig file, such
5853            // as the number of regions and samples used by each
5854            // instrument. It is divided in equally sized parts, where the
5855            // first part contains information about the whole gig file,
5856            // and the rest of the parts map to each instrument in the
5857            // file.
5858            //
5859            // At the end of each part there is a bit map of each sample
5860            // in the file, where a set bit means that the sample is used
5861            // by the file/instrument.
5862            //
5863            // Note that there are several fields with unknown use. These
5864            // are set to zero.
5865    
5866            int sublen = pSamples->size() / 8 + 49;
5867            int einfSize = (Instruments + 1) * sublen;
5868    
5869            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5870            if (einf) {
5871                if (einf->GetSize() != einfSize) {
5872                    einf->Resize(einfSize);
5873                    memset(einf->LoadChunkData(), 0, einfSize);
5874                }
5875            } else if (newFile) {
5876                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5877            }
5878            if (einf) {
5879                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5880    
5881                std::map<gig::Sample*,int> sampleMap;
5882                int sampleIdx = 0;
5883                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5884                    sampleMap[pSample] = sampleIdx++;
5885                }
5886    
5887                int totnbusedsamples = 0;
5888                int totnbusedchannels = 0;
5889                int totnbregions = 0;
5890                int totnbdimregions = 0;
5891                int totnbloops = 0;
5892                int instrumentIdx = 0;
5893    
5894                memset(&pData[48], 0, sublen - 48);
5895    
5896                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5897                     instrument = GetNextInstrument()) {
5898                    int nbusedsamples = 0;
5899                    int nbusedchannels = 0;
5900                    int nbdimregions = 0;
5901                    int nbloops = 0;
5902    
5903                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5904    
5905                    for (Region* region = instrument->GetFirstRegion() ; region ;
5906                         region = instrument->GetNextRegion()) {
5907                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
5908                            gig::DimensionRegion *d = region->pDimensionRegions[i];
5909                            if (d->pSample) {
5910                                int sampleIdx = sampleMap[d->pSample];
5911                                int byte = 48 + sampleIdx / 8;
5912                                int bit = 1 << (sampleIdx & 7);
5913                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5914                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5915                                    nbusedsamples++;
5916                                    nbusedchannels += d->pSample->Channels;
5917    
5918                                    if ((pData[byte] & bit) == 0) {
5919                                        pData[byte] |= bit;
5920                                        totnbusedsamples++;
5921                                        totnbusedchannels += d->pSample->Channels;
5922                                    }
5923                                }
5924                            }
5925                            if (d->SampleLoops) nbloops++;
5926                        }
5927                        nbdimregions += region->DimensionRegions;
5928                    }
5929                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5930                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5931                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5932                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5933                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5934                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5935                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5936                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5937                    // next 8 bytes unknown
5938                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5939                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5940                    // next 4 bytes unknown
5941    
5942                    totnbregions += instrument->Regions;
5943                    totnbdimregions += nbdimregions;
5944                    totnbloops += nbloops;
5945                    instrumentIdx++;
5946                }
5947                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5948                // store32(&pData[0], sublen);
5949                store32(&pData[4], totnbusedchannels);
5950                store32(&pData[8], totnbusedsamples);
5951                store32(&pData[12], Instruments);
5952                store32(&pData[16], totnbregions);
5953                store32(&pData[20], totnbdimregions);
5954                store32(&pData[24], totnbloops);
5955                // next 8 bytes unknown
5956                // next 4 bytes unknown, not always 0
5957                store32(&pData[40], pSamples->size());
5958                // next 4 bytes unknown
5959            }
5960    
5961            // update 3crc chunk
5962    
5963            // The 3crc chunk contains CRC-32 checksums for the
5964            // samples. The actual checksum values will be filled in
5965            // later, by Sample::Write.
5966    
5967            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5968            if (_3crc) {
5969                _3crc->Resize(pSamples->size() * 8);
5970            } else if (newFile) {
5971                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5972                _3crc->LoadChunkData();
5973    
5974                // the order of einf and 3crc is not the same in v2 and v3
5975                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5976            }
5977        }
5978        
5979        void File::UpdateFileOffsets() {
5980            DLS::File::UpdateFileOffsets();
5981    
5982            for (Instrument* instrument = GetFirstInstrument(); instrument;
5983                 instrument = GetNextInstrument())
5984            {
5985                instrument->UpdateScriptFileOffsets();
5986            }
5987        }
5988    
5989        /**
5990         * Enable / disable automatic loading. By default this properyt is
5991         * enabled and all informations are loaded automatically. However
5992         * loading all Regions, DimensionRegions and especially samples might
5993         * take a long time for large .gig files, and sometimes one might only
5994         * be interested in retrieving very superficial informations like the
5995         * amount of instruments and their names. In this case one might disable
5996         * automatic loading to avoid very slow response times.
5997         *
5998         * @e CAUTION: by disabling this property many pointers (i.e. sample
5999         * references) and informations will have invalid or even undefined
6000         * data! This feature is currently only intended for retrieving very
6001         * superficial informations in a very fast way. Don't use it to retrieve
6002         * details like synthesis informations or even to modify .gig files!
6003         */
6004        void File::SetAutoLoad(bool b) {
6005            bAutoLoad = b;
6006        }
6007    
6008        /**
6009         * Returns whether automatic loading is enabled.
6010         * @see SetAutoLoad()
6011         */
6012        bool File::GetAutoLoad() {
6013            return bAutoLoad;
6014      }      }
6015    
6016    
# Line 1410  namespace gig { Line 6025  namespace gig {
6025          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
6026      }      }
6027    
6028    
6029    // *************** functions ***************
6030    // *
6031    
6032        /**
6033         * Returns the name of this C++ library. This is usually "libgig" of
6034         * course. This call is equivalent to RIFF::libraryName() and
6035         * DLS::libraryName().
6036         */
6037        String libraryName() {
6038            return PACKAGE;
6039        }
6040    
6041        /**
6042         * Returns version of this C++ library. This call is equivalent to
6043         * RIFF::libraryVersion() and DLS::libraryVersion().
6044         */
6045        String libraryVersion() {
6046            return VERSION;
6047        }
6048    
6049  } // namespace gig  } // namespace gig

Legend:
Removed from v.36  
changed lines
  Added in v.2682

  ViewVC Help
Powered by ViewVC