/[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 55 by schoenebeck, Tue Apr 27 09:06:07 2004 UTC revision 695 by persson, Sat Jul 16 19:36:23 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, 2004 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 <iostream>
27    
28  namespace gig {  namespace gig {
29    
30    // *************** progress_t ***************
31    // *
32    
33        progress_t::progress_t() {
34            callback    = NULL;
35            custom      = NULL;
36            __range_min = 0.0f;
37            __range_max = 1.0f;
38        }
39    
40        // private helper function to convert progress of a subprocess into the global progress
41        static void __notify_progress(progress_t* pProgress, float subprogress) {
42            if (pProgress && pProgress->callback) {
43                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
44                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
45                pProgress->factor         = totalprogress;
46                pProgress->callback(pProgress); // now actually notify about the progress
47            }
48        }
49    
50        // private helper function to divide a progress into subprogresses
51        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
52            if (pParentProgress && pParentProgress->callback) {
53                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
54                pSubProgress->callback    = pParentProgress->callback;
55                pSubProgress->custom      = pParentProgress->custom;
56                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
57                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
58            }
59        }
60    
61    
62    // *************** Internal functions for sample decopmression ***************
63    // *
64    
65    namespace {
66    
67        inline int get12lo(const unsigned char* pSrc)
68        {
69            const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
70            return x & 0x800 ? x - 0x1000 : x;
71        }
72    
73        inline int get12hi(const unsigned char* pSrc)
74        {
75            const int x = pSrc[1] >> 4 | pSrc[2] << 4;
76            return x & 0x800 ? x - 0x1000 : x;
77        }
78    
79        inline int16_t get16(const unsigned char* pSrc)
80        {
81            return int16_t(pSrc[0] | pSrc[1] << 8);
82        }
83    
84        inline int get24(const unsigned char* pSrc)
85        {
86            const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
87            return x & 0x800000 ? x - 0x1000000 : x;
88        }
89    
90        void Decompress16(int compressionmode, const unsigned char* params,
91                          int srcStep, int dstStep,
92                          const unsigned char* pSrc, int16_t* pDst,
93                          unsigned long currentframeoffset,
94                          unsigned long copysamples)
95        {
96            switch (compressionmode) {
97                case 0: // 16 bit uncompressed
98                    pSrc += currentframeoffset * srcStep;
99                    while (copysamples) {
100                        *pDst = get16(pSrc);
101                        pDst += dstStep;
102                        pSrc += srcStep;
103                        copysamples--;
104                    }
105                    break;
106    
107                case 1: // 16 bit compressed to 8 bit
108                    int y  = get16(params);
109                    int dy = get16(params + 2);
110                    while (currentframeoffset) {
111                        dy -= int8_t(*pSrc);
112                        y  -= dy;
113                        pSrc += srcStep;
114                        currentframeoffset--;
115                    }
116                    while (copysamples) {
117                        dy -= int8_t(*pSrc);
118                        y  -= dy;
119                        *pDst = y;
120                        pDst += dstStep;
121                        pSrc += srcStep;
122                        copysamples--;
123                    }
124                    break;
125            }
126        }
127    
128        void Decompress24(int compressionmode, const unsigned char* params,
129                          int dstStep, const unsigned char* pSrc, int16_t* pDst,
130                          unsigned long currentframeoffset,
131                          unsigned long copysamples, int truncatedBits)
132        {
133            // Note: The 24 bits are truncated to 16 bits for now.
134    
135            int y, dy, ddy, dddy;
136            const int shift = 8 - truncatedBits;
137    
138    #define GET_PARAMS(params)                      \
139            y    = get24(params);                   \
140            dy   = y - get24((params) + 3);         \
141            ddy  = get24((params) + 6);             \
142            dddy = get24((params) + 9)
143    
144    #define SKIP_ONE(x)                             \
145            dddy -= (x);                            \
146            ddy  -= dddy;                           \
147            dy   =  -dy - ddy;                      \
148            y    += dy
149    
150    #define COPY_ONE(x)                             \
151            SKIP_ONE(x);                            \
152            *pDst = y >> shift;                     \
153            pDst += dstStep
154    
155            switch (compressionmode) {
156                case 2: // 24 bit uncompressed
157                    pSrc += currentframeoffset * 3;
158                    while (copysamples) {
159                        *pDst = get24(pSrc) >> shift;
160                        pDst += dstStep;
161                        pSrc += 3;
162                        copysamples--;
163                    }
164                    break;
165    
166                case 3: // 24 bit compressed to 16 bit
167                    GET_PARAMS(params);
168                    while (currentframeoffset) {
169                        SKIP_ONE(get16(pSrc));
170                        pSrc += 2;
171                        currentframeoffset--;
172                    }
173                    while (copysamples) {
174                        COPY_ONE(get16(pSrc));
175                        pSrc += 2;
176                        copysamples--;
177                    }
178                    break;
179    
180                case 4: // 24 bit compressed to 12 bit
181                    GET_PARAMS(params);
182                    while (currentframeoffset > 1) {
183                        SKIP_ONE(get12lo(pSrc));
184                        SKIP_ONE(get12hi(pSrc));
185                        pSrc += 3;
186                        currentframeoffset -= 2;
187                    }
188                    if (currentframeoffset) {
189                        SKIP_ONE(get12lo(pSrc));
190                        currentframeoffset--;
191                        if (copysamples) {
192                            COPY_ONE(get12hi(pSrc));
193                            pSrc += 3;
194                            copysamples--;
195                        }
196                    }
197                    while (copysamples > 1) {
198                        COPY_ONE(get12lo(pSrc));
199                        COPY_ONE(get12hi(pSrc));
200                        pSrc += 3;
201                        copysamples -= 2;
202                    }
203                    if (copysamples) {
204                        COPY_ONE(get12lo(pSrc));
205                    }
206                    break;
207    
208                case 5: // 24 bit compressed to 8 bit
209                    GET_PARAMS(params);
210                    while (currentframeoffset) {
211                        SKIP_ONE(int8_t(*pSrc++));
212                        currentframeoffset--;
213                    }
214                    while (copysamples) {
215                        COPY_ONE(int8_t(*pSrc++));
216                        copysamples--;
217                    }
218                    break;
219            }
220        }
221    
222        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
223        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
224        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
225        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
226    }
227    
228    
229  // *************** Sample ***************  // *************** Sample ***************
230  // *  // *
231    
232      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
233      void*         Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
234    
235      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
236          Instances++;          Instances++;
237            FileNo = fileNo;
238    
239          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
240          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
# Line 49  namespace gig { Line 250  namespace gig {
250          smpl->Read(&SMPTEFormat, 1, 4);          smpl->Read(&SMPTEFormat, 1, 4);
251          SMPTEOffset       = smpl->ReadInt32();          SMPTEOffset       = smpl->ReadInt32();
252          Loops             = smpl->ReadInt32();          Loops             = smpl->ReadInt32();
253          uint32_t manufByt = smpl->ReadInt32();          smpl->ReadInt32(); // manufByt
254          LoopID            = smpl->ReadInt32();          LoopID            = smpl->ReadInt32();
255          smpl->Read(&LoopType, 1, 4);          smpl->Read(&LoopType, 1, 4);
256          LoopStart         = smpl->ReadInt32();          LoopStart         = smpl->ReadInt32();
# Line 63  namespace gig { Line 264  namespace gig {
264          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
265          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
266    
267          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
268    
269            RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
270            Compressed        = ewav;
271            Dithered          = false;
272            TruncatedBits     = 0;
273          if (Compressed) {          if (Compressed) {
274              ScanCompressedSample();              uint32_t version = ewav->ReadInt32();
275              if (!pDecompressionBuffer) {              if (version == 3 && BitDepth == 24) {
276                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];                  Dithered = ewav->ReadInt32();
277                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;                  ewav->SetPos(Channels == 2 ? 84 : 64);
278                    TruncatedBits = ewav->ReadInt32();
279              }              }
280                ScanCompressedSample();
281            }
282    
283            // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
284            if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
285                InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
286                InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
287          }          }
288          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
289    
290          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
291      }      }
# Line 82  namespace gig { Line 296  namespace gig {
296          this->SamplesTotal = 0;          this->SamplesTotal = 0;
297          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
298    
299            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
300            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
301    
302          // Scanning          // Scanning
303          pCkData->SetPos(0);          pCkData->SetPos(0);
304          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
305              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
306              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
307              this->SamplesTotal += 2048;                  // stored, to save some memory
308              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
309                  case 1:   // left channel compressed  
310                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
311                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
312                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
313                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
314    
315                    if (pCkData->RemainingBytes() <= frameSize) {
316                        SamplesInLastFrame =
317                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
318                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
319                        SamplesTotal += SamplesInLastFrame;
320                      break;                      break;
321                  case 257: // both channels compressed                  }
322                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
323                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
324                }
325            }
326            else { // Mono
327                for (int i = 0 ; ; i++) {
328                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
329    
330                    const int mode = pCkData->ReadUint8();
331                    if (mode > 5) throw gig::Exception("Unknown compression mode");
332                    const unsigned long frameSize = bytesPerFrame[mode];
333    
334                    if (pCkData->RemainingBytes() <= frameSize) {
335                        SamplesInLastFrame =
336                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
337                        SamplesTotal += SamplesInLastFrame;
338                      break;                      break;
339                  default: // both channels uncompressed                  }
340                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
341                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
342              }              }
343          }          }
344          pCkData->SetPos(0);          pCkData->SetPos(0);
345    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
346          // 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)
347          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
348          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 141  namespace gig { Line 378  namespace gig {
378       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
379       * 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
380       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
381       *       * @code
382       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
383       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
384         * @endcode
385       *       *
386       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
387       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 189  namespace gig { Line 427  namespace gig {
427       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
428       * 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
429       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
430       *       * @code
431       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
432       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
433       *       * @endcode
434       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
435       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
436       * 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 323  namespace gig { Line 561  namespace gig {
561       * for the next time you call this method is stored in \a pPlaybackState.       * for the next time you call this method is stored in \a pPlaybackState.
562       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
563       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
564       *       * @code
565       * <i>       * gig::playback_state_t playbackstate;
566       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
567       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
568       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
569       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
570       * You don't have to take care of things like if there is actually a loop       * You don't have to take care of things like if there is actually a loop
571       * defined or if the current read position is located within a loop area.       * defined or if the current read position is located within a loop area.
572       * The method already handles such cases by itself.       * The method already handles such cases by itself.
573       *       *
574         * <b>Caution:</b> If you are using more than one streaming thread, you
575         * have to use an external decompression buffer for <b>EACH</b>
576         * streaming thread to avoid race conditions and crashes!
577         *
578       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
579       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
580       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
581       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
582         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
583       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
584         * @see                    CreateDecompressionBuffer()
585       */       */
586      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {
587          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
588          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
589    
# Line 359  namespace gig { Line 601  namespace gig {
601                          if (!pPlaybackState->reverse) { // forward playback                          if (!pPlaybackState->reverse) { // forward playback
602                              do {                              do {
603                                  samplestoloopend  = this->LoopEnd - GetPos();                                  samplestoloopend  = this->LoopEnd - GetPos();
604                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
605                                  samplestoread    -= readsamples;                                  samplestoread    -= readsamples;
606                                  totalreadsamples += readsamples;                                  totalreadsamples += readsamples;
607                                  if (readsamples == samplestoloopend) {                                  if (readsamples == samplestoloopend) {
# Line 385  namespace gig { Line 627  namespace gig {
627    
628                              // read samples for backward playback                              // read samples for backward playback
629                              do {                              do {
630                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
631                                  samplestoreadinloop -= readsamples;                                  samplestoreadinloop -= readsamples;
632                                  samplestoread       -= readsamples;                                  samplestoread       -= readsamples;
633                                  totalreadsamples    += readsamples;                                  totalreadsamples    += readsamples;
# Line 409  namespace gig { Line 651  namespace gig {
651                      // forward playback (not entered the loop yet)                      // forward playback (not entered the loop yet)
652                      if (!pPlaybackState->reverse) do {                      if (!pPlaybackState->reverse) do {
653                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
654                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
655                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
656                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
657                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 439  namespace gig { Line 681  namespace gig {
681                          // if not endless loop check if max. number of loop cycles have been passed                          // if not endless loop check if max. number of loop cycles have been passed
682                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
683                          samplestoloopend     = this->LoopEnd - GetPos();                          samplestoloopend     = this->LoopEnd - GetPos();
684                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
685                          samplestoreadinloop -= readsamples;                          samplestoreadinloop -= readsamples;
686                          samplestoread       -= readsamples;                          samplestoread       -= readsamples;
687                          totalreadsamples    += readsamples;                          totalreadsamples    += readsamples;
# Line 461  namespace gig { Line 703  namespace gig {
703                          // if not endless loop check if max. number of loop cycles have been passed                          // if not endless loop check if max. number of loop cycles have been passed
704                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
705                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
706                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
707                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
708                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
709                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 476  namespace gig { Line 718  namespace gig {
718    
719          // read on without looping          // read on without looping
720          if (samplestoread) do {          if (samplestoread) do {
721              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
722              samplestoread    -= readsamples;              samplestoread    -= readsamples;
723              totalreadsamples += readsamples;              totalreadsamples += readsamples;
724          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 495  namespace gig { Line 737  namespace gig {
737       * 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,
738       * thus for disk streaming.       * thus for disk streaming.
739       *       *
740         * <b>Caution:</b> If you are using more than one streaming thread, you
741         * have to use an external decompression buffer for <b>EACH</b>
742         * streaming thread to avoid race conditions and crashes!
743         *
744       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
745       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
746         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
747       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
748       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
749       */       */
750      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
751          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
752          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?          if (!Compressed) {
753          else { //FIXME: no support for mono compressed samples yet, are there any?              if (BitDepth == 24) {
754                    // 24 bit sample. For now just truncate to 16 bit.
755                    unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
756                    int16_t* pDst = static_cast<int16_t*>(pBuffer);
757                    if (Channels == 2) { // Stereo
758                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
759                        pSrc++;
760                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
761                            *pDst++ = get16(pSrc);
762                            pSrc += 3;
763                        }
764                        return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
765                    }
766                    else { // Mono
767                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
768                        pSrc++;
769                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
770                            *pDst++ = get16(pSrc);
771                            pSrc += 3;
772                        }
773                        return pDst - static_cast<int16_t*>(pBuffer);
774                    }
775                }
776                else { // 16 bit
777                    // (pCkData->Read does endian correction)
778                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
779                                         : pCkData->Read(pBuffer, SampleCount, 2);
780                }
781            }
782            else {
783              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
784              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
785              // best case needed buffer size (all frames compressed)              unsigned long assumedsize      = GuessSize(SampleCount),
             unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                              (SampleCount >> 10) + // 10 bytes header per 2048 sample points  
                                              8194,                 // at least one worst case sample frame  
786                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
787                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
788                            copysamples;                            copysamples, skipsamples,
789              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
790              this->FrameOffset = 0;              this->FrameOffset = 0;
791    
792              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
793                  // local buffer reallocation - hope this won't happen  
794                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
795                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
796                  this->DecompressionBufferSize = assumedsize;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
797                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
798                    remainingsamples = SampleCount;
799                    assumedsize      = GuessSize(SampleCount);
800              }              }
801    
802              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
803              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
             int16_t* pDst = (int16_t*) pBuffer;  
804              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
805    
806              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
807                    unsigned long framesamples = SamplesPerFrame;
808                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
809                  if (remainingbytes < 8194) {  
810                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
811                          this->SamplePos = this->SamplesTotal;  
812                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
813                        mode_r = *pSrc++;
814                        framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
815                        rightChannelOffset = bytesPerFrameNoHdr[mode_l];
816                        nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
817                        if (remainingbytes < framebytes) { // last frame in sample
818                            framesamples = SamplesInLastFrame;
819                            if (mode_l == 4 && (framesamples & 1)) {
820                                rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
821                            }
822                            else {
823                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
824                            }
825                        }
826                    }
827                    else {
828                        framebytes = bytesPerFrame[mode_l] + 1;
829                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
830                        if (remainingbytes < framebytes) {
831                            framesamples = SamplesInLastFrame;
832                      }                      }
                     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;  
833                  }                  }
834    
835                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
836                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
837                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
838                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
839                            skipsamples = currentframeoffset;
840                        }
841                        else {
842                            copysamples = 0;
843                            skipsamples = framesamples;
844                        }
845                  }                  }
846                  else {                  else {
847                        // This frame has enough data for pBuffer, but not
848                        // all of the frame is needed. Set file position
849                        // to start of this frame for next call to Read.
850                      copysamples = remainingsamples;                      copysamples = remainingsamples;
851                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
852                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
853                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
854                      }                  }
855                      else {                  remainingsamples -= copysamples;
856    
857                    if (remainingbytes > framebytes) {
858                        remainingbytes -= framebytes;
859                        if (remainingsamples == 0 &&
860                            currentframeoffset + copysamples == framesamples) {
861                            // This frame has enough data for pBuffer, and
862                            // all of the frame is needed. Set file
863                            // position to start of next frame for next
864                            // call to Read. FrameOffset is 0.
865                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
866                      }                      }
867                  }                  }
868                    else remainingbytes = 0;
869    
870                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
871                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
872                  switch (compressionmode) {                  if (copysamples == 0) {
873                      case 1: // left channel compressed                      // skip this frame
874                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
875                          if (!remainingsamples && copysamples == 2048)                  }
876                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
877                        const unsigned char* const param_l = pSrc;
878                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
879                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
880                          while (currentframeoffset) {  
881                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
882                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
883                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
884                              currentframeoffset--;  
885                          }                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
886                          while (copysamples) {                                           skipsamples, copysamples, TruncatedBits);
887                              dleft -= *pSrc; pSrc++;                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
888                              left  -= dleft;                                           skipsamples, copysamples, TruncatedBits);
889                              *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  
890                          }                          }
891                          while (copysamples) {                          else { // Mono
892                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
893                              dright -= *pSrc; pSrc++;                                           skipsamples, copysamples, TruncatedBits);
894                              right  -= dright;                              pDst += copysamples;
                             *pDst = right; pDst++;  
                             copysamples--;  
895                          }                          }
896                          break;                      }
897                      case 257: // both channels compressed                      else { // 16 bit
898                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
899                          if (!remainingsamples && copysamples == 2048)  
900                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
901                            if (Channels == 2) { // Stereo
902                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
903                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
904                          right  = *(int16_t*)pSrc; pSrc+=2;  
905                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
906                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
907                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
908                              left   -= dleft;                                           skipsamples, copysamples);
909                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
910                          }                          }
911                          while (copysamples) {                          else { // Mono
912                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
913                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
914                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
915                          }                          }
916                          break;                      }
917                      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;  
918                  }                  }
919              }  
920                    // reload from disk to local buffer if needed
921                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
922                        assumedsize    = GuessSize(remainingsamples);
923                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
924                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
925                        remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
926                        pSrc = (unsigned char*) pDecompressionBuffer->pStart;
927                    }
928                } // while
929    
930              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
931              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
932              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
933          }          }
934      }      }
935    
936        /**
937         * Allocates a decompression buffer for streaming (compressed) samples
938         * with Sample::Read(). If you are using more than one streaming thread
939         * in your application you <b>HAVE</b> to create a decompression buffer
940         * for <b>EACH</b> of your streaming threads and provide it with the
941         * Sample::Read() call in order to avoid race conditions and crashes.
942         *
943         * You should free the memory occupied by the allocated buffer(s) once
944         * you don't need one of your streaming threads anymore by calling
945         * DestroyDecompressionBuffer().
946         *
947         * @param MaxReadSize - the maximum size (in sample points) you ever
948         *                      expect to read with one Read() call
949         * @returns allocated decompression buffer
950         * @see DestroyDecompressionBuffer()
951         */
952        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
953            buffer_t result;
954            const double worstCaseHeaderOverhead =
955                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
956            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
957            result.pStart            = new int8_t[result.Size];
958            result.NullExtensionSize = 0;
959            return result;
960        }
961    
962        /**
963         * Free decompression buffer, previously created with
964         * CreateDecompressionBuffer().
965         *
966         * @param DecompressionBuffer - previously allocated decompression
967         *                              buffer to free
968         */
969        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
970            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
971                delete[] (int8_t*) DecompressionBuffer.pStart;
972                DecompressionBuffer.pStart = NULL;
973                DecompressionBuffer.Size   = 0;
974                DecompressionBuffer.NullExtensionSize = 0;
975            }
976        }
977    
978      Sample::~Sample() {      Sample::~Sample() {
979          Instances--;          Instances--;
980          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && InternalDecompressionBuffer.Size) {
981                delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
982                InternalDecompressionBuffer.pStart = NULL;
983                InternalDecompressionBuffer.Size   = 0;
984            }
985          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
986          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
987      }      }
# Line 680  namespace gig { Line 1001  namespace gig {
1001          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1002    
1003          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1004          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1005          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1006          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1007          _3ewa->ReadInt16(); // unknown          _3ewa->ReadInt16(); // unknown
# Line 774  namespace gig { Line 1095  namespace gig {
1095          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1096          else                                       DimensionBypass = dim_bypass_ctrl_none;          else                                       DimensionBypass = dim_bypass_ctrl_none;
1097          uint8_t pan = _3ewa->ReadUint8();          uint8_t pan = _3ewa->ReadUint8();
1098          Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1099          SelfMask = _3ewa->ReadInt8() & 0x01;          SelfMask = _3ewa->ReadInt8() & 0x01;
1100          _3ewa->ReadInt8(); // unknown          _3ewa->ReadInt8(); // unknown
1101          uint8_t lfo3ctrl = _3ewa->ReadUint8();          uint8_t lfo3ctrl = _3ewa->ReadUint8();
1102          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1103          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1104          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
1105          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1106          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1107          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
# Line 829  namespace gig { Line 1146  namespace gig {
1146          VCFVelocityDynamicRange = vcfvelocity % 5;          VCFVelocityDynamicRange = vcfvelocity % 5;
1147          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1148          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1149            if (VCFType == vcf_type_lowpass) {
1150                if (lfo3ctrl & 0x40) // bit 6
1151                    VCFType = vcf_type_lowpassturbo;
1152            }
1153    
1154            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1155                                                         VelocityResponseDepth,
1156                                                         VelocityResponseCurveScaling);
1157    
1158            curve_type_t curveType = ReleaseVelocityResponseCurve;
1159            uint8_t depth = ReleaseVelocityResponseDepth;
1160    
1161            // this models a strange behaviour or bug in GSt: two of the
1162            // velocity response curves for release time are not used even
1163            // if specified, instead another curve is chosen.
1164    
1165          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          if ((curveType == curve_type_nonlinear && depth == 0) ||
1166          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;              (curveType == curve_type_special   && depth == 4)) {
1167                curveType = curve_type_nonlinear;
1168                depth = 3;
1169            }
1170            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1171    
1172            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1173        }
1174    
1175        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1176        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1177        {
1178            double* table;
1179            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1180          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1181              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1182          }          }
1183          else {          else {
1184              pVelocityAttenuationTable = new double[128];              table = CreateVelocityTable(curveType, depth, scaling);
1185              switch (VelocityResponseCurve) { // calculate the new table              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
                 case curve_type_nonlinear:  
                     for (int velocity = 0; velocity < 128; velocity++) {  
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_NONLINEAR((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                      }  
                      break;  
                 case curve_type_linear:  
                     for (int velocity = 0; velocity < 128; velocity++) {  
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_LINEAR((double)velocity,(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
                     break;  
                 case curve_type_special:  
                     for (int velocity = 0; velocity < 128; velocity++) {  
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_SPECIAL((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
                     break;  
                 case curve_type_unknown:  
                 default:  
                     throw gig::Exception("Unknown transform curve type.");  
             }  
             (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map  
1186          }          }
1187            return table;
1188      }      }
1189    
1190      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1018  namespace gig { Line 1335  namespace gig {
1335          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1336      }      }
1337    
1338        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1339            return pVelocityReleaseTable[MIDIKeyVelocity];
1340        }
1341    
1342        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1343    
1344            // line-segment approximations of the 15 velocity curves
1345    
1346            // linear
1347            const int lin0[] = { 1, 1, 127, 127 };
1348            const int lin1[] = { 1, 21, 127, 127 };
1349            const int lin2[] = { 1, 45, 127, 127 };
1350            const int lin3[] = { 1, 74, 127, 127 };
1351            const int lin4[] = { 1, 127, 127, 127 };
1352    
1353            // non-linear
1354            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1355            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1356                                 127, 127 };
1357            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1358                                 127, 127 };
1359            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1360                                 127, 127 };
1361            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1362    
1363            // special
1364            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1365                                 113, 127, 127, 127 };
1366            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1367                                 118, 127, 127, 127 };
1368            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
1369                                 85, 90, 91, 127, 127, 127 };
1370            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
1371                                 117, 127, 127, 127 };
1372            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
1373                                 127, 127 };
1374    
1375            const int* const curves[] = { non0, non1, non2, non3, non4,
1376                                          lin0, lin1, lin2, lin3, lin4,
1377                                          spe0, spe1, spe2, spe3, spe4 };
1378    
1379            double* const table = new double[128];
1380    
1381            const int* curve = curves[curveType * 5 + depth];
1382            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
1383    
1384            table[0] = 0;
1385            for (int x = 1 ; x < 128 ; x++) {
1386    
1387                if (x > curve[2]) curve += 2;
1388                double y = curve[1] + (x - curve[0]) *
1389                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
1390                y = y / 127;
1391    
1392                // Scale up for s > 20, down for s < 20. When
1393                // down-scaling, the curve still ends at 1.0.
1394                if (s < 20 && y >= 0.5)
1395                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
1396                else
1397                    y = y * (s / 20.0);
1398                if (y > 1) y = 1;
1399    
1400                table[x] = y;
1401            }
1402            return table;
1403        }
1404    
1405    
1406  // *************** Region ***************  // *************** Region ***************
# Line 1026  namespace gig { Line 1409  namespace gig {
1409      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) {
1410          // Initialization          // Initialization
1411          Dimensions = 0;          Dimensions = 0;
1412          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1413              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
1414          }          }
1415            Layers = 1;
1416            File* file = (File*) GetParent()->GetParent();
1417            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
1418    
1419          // Actual Loading          // Actual Loading
1420    
# Line 1037  namespace gig { Line 1423  namespace gig {
1423          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1424          if (_3lnk) {          if (_3lnk) {
1425              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
1426              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
1427                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1428                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
1429                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
# Line 1053  namespace gig { Line 1439  namespace gig {
1439                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
1440                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1441                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1442                                                             dimension == dimension_samplechannel) ? split_type_bit                                                             dimension == dimension_samplechannel ||
1443                                                                                                   : split_type_normal;                                                             dimension == dimension_releasetrigger ||
1444                                                               dimension == dimension_roundrobin ||
1445                                                               dimension == dimension_random) ? split_type_bit
1446                                                                                              : split_type_normal;
1447                      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
1448                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1449                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1450                                                                                     : 0;                                                                                     : 0;
1451                      Dimensions++;                      Dimensions++;
1452    
1453                        // if this is a layer dimension, remember the amount of layers
1454                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
1455                  }                  }
1456                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1457              }              }
# Line 1076  namespace gig { Line 1468  namespace gig {
1468                      else { // custom defined ranges                      else { // custom defined ranges
1469                          pDimDef->split_type = split_type_customvelocity;                          pDimDef->split_type = split_type_customvelocity;
1470                          pDimDef->ranges     = new range_t[pDimDef->zones];                          pDimDef->ranges     = new range_t[pDimDef->zones];
1471                          unsigned int bits[5] = {0,0,0,0,0};                          uint8_t bits[8] = { 0 };
1472                          int previousUpperLimit = -1;                          int previousUpperLimit = -1;
1473                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1474                              bits[i] = velocityZone;                              bits[i] = velocityZone;
1475                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
1476    
1477                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;
1478                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
# Line 1094  namespace gig { Line 1486  namespace gig {
1486                  }                  }
1487              }              }
1488    
1489                // jump to start of the wave pool indices (if not already there)
1490                File* file = (File*) GetParent()->GetParent();
1491                if (file->pVersion && file->pVersion->major == 3)
1492                    _3lnk->SetPos(68); // version 3 has a different 3lnk structure
1493                else
1494                    _3lnk->SetPos(44);
1495    
1496              // load sample references              // load sample references
             _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)  
1497              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
1498                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
1499                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
# Line 1124  namespace gig { Line 1522  namespace gig {
1522          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1523              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1524          }          }
1525          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1526              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
1527          }          }
1528      }      }
# Line 1142  namespace gig { Line 1540  namespace gig {
1540       * 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,
1541       * etc.).       * etc.).
1542       *       *
1543       * @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  
1544       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
1545       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
1546       * @see             Dimensions       * @see             Dimensions
1547       */       */
1548      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
1549          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits[8] = { 0 };
1550          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1551                bits[i] = DimValues[i];
1552              switch (pDimensionDefinitions[i].split_type) {              switch (pDimensionDefinitions[i].split_type) {
1553                  case split_type_normal:                  case split_type_normal:
1554                      bits[i] /= pDimensionDefinitions[i].zone_size;                      bits[i] /= pDimensionDefinitions[i].zone_size;
# Line 1161  namespace gig { Line 1556  namespace gig {
1556                  case split_type_customvelocity:                  case split_type_customvelocity:
1557                      bits[i] = VelocityTable[bits[i]];                      bits[i] = VelocityTable[bits[i]];
1558                      break;                      break;
1559                  // else the value is already the sought dimension bit number                  case split_type_bit: // the value is already the sought dimension bit number
1560                        const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
1561                        bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
1562                        break;
1563              }              }
1564          }          }
1565          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          return GetDimensionRegionByBit(bits);
1566      }      }
1567    
1568      /**      /**
# Line 1172  namespace gig { Line 1570  namespace gig {
1570       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1571       * instead of calling this method directly!       * instead of calling this method directly!
1572       *       *
1573       * @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  
1574       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
1575       *                 bit numbers       *                 bit numbers
1576       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
1577       */       */
1578      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]) {
1579          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
1580                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
1581                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
1582                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
1583                                                      << pDimensionDefinitions[2].bits | DimBits[2])
1584                                                      << pDimensionDefinitions[1].bits | DimBits[1])
1585                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
1586      }      }
1587    
1588      /**      /**
# Line 1202  namespace gig { Line 1599  namespace gig {
1599          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1600      }      }
1601    
1602      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
1603            if ((int32_t)WavePoolTableIndex == -1) return NULL;
1604          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1605          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1606          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
1607            Sample* sample = file->GetFirstSample(pProgress);
1608          while (sample) {          while (sample) {
1609              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
1610                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
1611              sample = file->GetNextSample();              sample = file->GetNextSample();
1612          }          }
1613          return NULL;          return NULL;
# Line 1218  namespace gig { Line 1618  namespace gig {
1618  // *************** Instrument ***************  // *************** Instrument ***************
1619  // *  // *
1620    
1621      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) {
1622          // Initialization          // Initialization
1623          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1624          RegionIndex = -1;          RegionIndex = -1;
# Line 1244  namespace gig { Line 1644  namespace gig {
1644          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1645          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1646          pRegions = new Region*[Regions];          pRegions = new Region*[Regions];
1647            for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;
1648          RIFF::List* rgn = lrgn->GetFirstSubList();          RIFF::List* rgn = lrgn->GetFirstSubList();
1649          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1650          while (rgn) {          while (rgn) {
1651              if (rgn->GetListType() == LIST_TYPE_RGN) {              if (rgn->GetListType() == LIST_TYPE_RGN) {
1652                    __notify_progress(pProgress, (float) iRegion / (float) Regions);
1653                  pRegions[iRegion] = new Region(this, rgn);                  pRegions[iRegion] = new Region(this, rgn);
1654                  iRegion++;                  iRegion++;
1655              }              }
# Line 1260  namespace gig { Line 1662  namespace gig {
1662                  RegionKeyTable[iKey] = pRegions[iReg];                  RegionKeyTable[iKey] = pRegions[iReg];
1663              }              }
1664          }          }
1665    
1666            __notify_progress(pProgress, 1.0f); // notify done
1667      }      }
1668    
1669      Instrument::~Instrument() {      Instrument::~Instrument() {
# Line 1267  namespace gig { Line 1671  namespace gig {
1671              if (pRegions) {              if (pRegions) {
1672                  if (pRegions[i]) delete (pRegions[i]);                  if (pRegions[i]) delete (pRegions[i]);
1673              }              }
             delete[] pRegions;  
1674          }          }
1675            if (pRegions) delete[] pRegions;
1676      }      }
1677    
1678      /**      /**
# Line 1310  namespace gig { Line 1714  namespace gig {
1714       * @see      GetFirstRegion()       * @see      GetFirstRegion()
1715       */       */
1716      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
1717          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;
1718          return pRegions[RegionIndex++];          return pRegions[RegionIndex++];
1719      }      }
1720    
# Line 1324  namespace gig { Line 1728  namespace gig {
1728          pInstruments = NULL;          pInstruments = NULL;
1729      }      }
1730    
1731      Sample* File::GetFirstSample() {      File::~File() {
1732          if (!pSamples) LoadSamples();          // free samples
1733            if (pSamples) {
1734                SamplesIterator = pSamples->begin();
1735                while (SamplesIterator != pSamples->end() ) {
1736                    delete (*SamplesIterator);
1737                    SamplesIterator++;
1738                }
1739                pSamples->clear();
1740                delete pSamples;
1741    
1742            }
1743            // free instruments
1744            if (pInstruments) {
1745                InstrumentsIterator = pInstruments->begin();
1746                while (InstrumentsIterator != pInstruments->end() ) {
1747                    delete (*InstrumentsIterator);
1748                    InstrumentsIterator++;
1749                }
1750                pInstruments->clear();
1751                delete pInstruments;
1752            }
1753            // free extension files
1754            for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1755                delete *i;
1756        }
1757    
1758        Sample* File::GetFirstSample(progress_t* pProgress) {
1759            if (!pSamples) LoadSamples(pProgress);
1760          if (!pSamples) return NULL;          if (!pSamples) return NULL;
1761          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
1762          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1337  namespace gig { Line 1768  namespace gig {
1768          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1769      }      }
1770    
1771      void File::LoadSamples() {      void File::LoadSamples(progress_t* pProgress) {
1772          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::File* file = pRIFF;
1773          if (wvpl) {  
1774              unsigned long wvplFileOffset = wvpl->GetFilePos();          // just for progress calculation
1775              RIFF::List* wave = wvpl->GetFirstSubList();          int iSampleIndex  = 0;
1776              while (wave) {          int iTotalSamples = WavePoolCount;
1777                  if (wave->GetListType() == LIST_TYPE_WAVE) {  
1778                      if (!pSamples) pSamples = new SampleList;          // check if samples should be loaded from extension files
1779                      unsigned long waveFileOffset = wave->GetFilePos();          int lastFileNo = 0;
1780                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          for (int i = 0 ; i < WavePoolCount ; i++) {
1781                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
1782            }
1783            String name(pRIFF->Filename);
1784            int nameLen = pRIFF->Filename.length();
1785            char suffix[6];
1786            if (nameLen > 4 && pRIFF->Filename.substr(nameLen - 4) == ".gig") nameLen -= 4;
1787    
1788            for (int fileNo = 0 ; ; ) {
1789                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
1790                if (wvpl) {
1791                    unsigned long wvplFileOffset = wvpl->GetFilePos();
1792                    RIFF::List* wave = wvpl->GetFirstSubList();
1793                    while (wave) {
1794                        if (wave->GetListType() == LIST_TYPE_WAVE) {
1795                            // notify current progress
1796                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
1797                            __notify_progress(pProgress, subprogress);
1798    
1799                            if (!pSamples) pSamples = new SampleList;
1800                            unsigned long waveFileOffset = wave->GetFilePos();
1801                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
1802    
1803                            iSampleIndex++;
1804                        }
1805                        wave = wvpl->GetNextSubList();
1806                  }                  }
1807                  wave = wvpl->GetNextSubList();  
1808                    if (fileNo == lastFileNo) break;
1809    
1810                    // open extension file (*.gx01, *.gx02, ...)
1811                    fileNo++;
1812                    sprintf(suffix, ".gx%02d", fileNo);
1813                    name.replace(nameLen, 5, suffix);
1814                    file = new RIFF::File(name);
1815                    ExtensionFiles.push_back(file);
1816              }              }
1817                else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1818          }          }
1819          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
1820            __notify_progress(pProgress, 1.0); // notify done
1821      }      }
1822    
1823      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
# Line 1370  namespace gig { Line 1836  namespace gig {
1836      /**      /**
1837       * Returns the instrument with the given index.       * Returns the instrument with the given index.
1838       *       *
1839         * @param index     - number of the sought instrument (0..n)
1840         * @param pProgress - optional: callback function for progress notification
1841       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
1842       */       */
1843      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
1844          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
1845                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
1846    
1847                // sample loading subtask
1848                progress_t subprogress;
1849                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
1850                __notify_progress(&subprogress, 0.0f);
1851                GetFirstSample(&subprogress); // now force all samples to be loaded
1852                __notify_progress(&subprogress, 1.0f);
1853    
1854                // instrument loading subtask
1855                if (pProgress && pProgress->callback) {
1856                    subprogress.__range_min = subprogress.__range_max;
1857                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
1858                }
1859                __notify_progress(&subprogress, 0.0f);
1860                LoadInstruments(&subprogress);
1861                __notify_progress(&subprogress, 1.0f);
1862            }
1863          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
1864          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
1865          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
# Line 1383  namespace gig { Line 1869  namespace gig {
1869          return NULL;          return NULL;
1870      }      }
1871    
1872      void File::LoadInstruments() {      void File::LoadInstruments(progress_t* pProgress) {
1873          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1874          if (lstInstruments) {          if (lstInstruments) {
1875                int iInstrumentIndex = 0;
1876              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1877              while (lstInstr) {              while (lstInstr) {
1878                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1879                        // notify current progress
1880                        const float localProgress = (float) iInstrumentIndex / (float) Instruments;
1881                        __notify_progress(pProgress, localProgress);
1882    
1883                        // divide local progress into subprogress for loading current Instrument
1884                        progress_t subprogress;
1885                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
1886    
1887                      if (!pInstruments) pInstruments = new InstrumentList;                      if (!pInstruments) pInstruments = new InstrumentList;
1888                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
1889    
1890                        iInstrumentIndex++;
1891                  }                  }
1892                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
1893              }              }
1894                __notify_progress(pProgress, 1.0); // notify done
1895          }          }
1896          else throw gig::Exception("Mandatory <lins> list chunk not found.");          else throw gig::Exception("Mandatory <lins> list chunk not found.");
1897      }      }
# Line 1410  namespace gig { Line 1908  namespace gig {
1908          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
1909      }      }
1910    
1911    
1912    // *************** functions ***************
1913    // *
1914    
1915        /**
1916         * Returns the name of this C++ library. This is usually "libgig" of
1917         * course. This call is equivalent to RIFF::libraryName() and
1918         * DLS::libraryName().
1919         */
1920        String libraryName() {
1921            return PACKAGE;
1922        }
1923    
1924        /**
1925         * Returns version of this C++ library. This call is equivalent to
1926         * RIFF::libraryVersion() and DLS::libraryVersion().
1927         */
1928        String libraryVersion() {
1929            return VERSION;
1930        }
1931    
1932  } // namespace gig  } // namespace gig

Legend:
Removed from v.55  
changed lines
  Added in v.695

  ViewVC Help
Powered by ViewVC