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

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

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

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

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

  ViewVC Help
Powered by ViewVC