/[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 365 by persson, Thu Feb 10 19:16:31 2005 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  namespace gig { namespace {  #include <iostream>
27    
28    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 ***************  // *************** Internal functions for sample decopmression ***************
63  // *  // *
64    
65    namespace {
66    
67      inline int get12lo(const unsigned char* pSrc)      inline int get12lo(const unsigned char* pSrc)
68      {      {
69          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
# Line 52  namespace gig { namespace { Line 88  namespace gig { namespace {
88      }      }
89    
90      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
91                        int srcStep, const unsigned char* pSrc, int16_t* pDst,                        int srcStep, int dstStep,
92                          const unsigned char* pSrc, int16_t* pDst,
93                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
94                        unsigned long copysamples)                        unsigned long copysamples)
95      {      {
# Line 61  namespace gig { namespace { Line 98  namespace gig { namespace {
98                  pSrc += currentframeoffset * srcStep;                  pSrc += currentframeoffset * srcStep;
99                  while (copysamples) {                  while (copysamples) {
100                      *pDst = get16(pSrc);                      *pDst = get16(pSrc);
101                      pDst += 2;                      pDst += dstStep;
102                      pSrc += srcStep;                      pSrc += srcStep;
103                      copysamples--;                      copysamples--;
104                  }                  }
# Line 80  namespace gig { namespace { Line 117  namespace gig { namespace {
117                      dy -= int8_t(*pSrc);                      dy -= int8_t(*pSrc);
118                      y  -= dy;                      y  -= dy;
119                      *pDst = y;                      *pDst = y;
120                      pDst += 2;                      pDst += dstStep;
121                      pSrc += srcStep;                      pSrc += srcStep;
122                      copysamples--;                      copysamples--;
123                  }                  }
# Line 89  namespace gig { namespace { Line 126  namespace gig { namespace {
126      }      }
127    
128      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
129                        const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, int16_t* pDst,
130                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
131                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
132      {      {
133          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
134    
135          // Note: The calculation of the initial value of y is strange          int y, dy, ddy, dddy;
136          // and not 100% correct. What should the first two parameters          const int shift = 8 - truncatedBits;
137          // really be used for? Why are they two? The correct value for  
138          // y seems to lie somewhere between the values of the first  #define GET_PARAMS(params)                      \
139          // two parameters.          y    = get24(params);                   \
140          //          dy   = y - get24((params) + 3);         \
141          // Strange thing #2: The formula in SKIP_ONE gives values for          ddy  = get24((params) + 6);             \
142          // y that are twice as high as they should be. That's why          dddy = get24((params) + 9)
         // COPY_ONE shifts 9 steps instead of 8, and also why y is  
         // initialized with a sum instead of a mean value.  
   
         int y, dy, ddy;  
   
 #define GET_PARAMS(params)                              \  
         y = (get24(params) + get24((params) + 3));      \  
         dy  = get24((params) + 6);                      \  
         ddy = get24((params) + 9)  
143    
144  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
145          ddy -= (x);                             \          dddy -= (x);                            \
146          dy -= ddy;                              \          ddy  -= dddy;                           \
147          y -= dy          dy   =  -dy - ddy;                      \
148            y    += dy
149    
150  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
151          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
152          *pDst = y >> 9;                         \          *pDst = y >> shift;                     \
153          pDst += 2          pDst += dstStep
154    
155          switch (compressionmode) {          switch (compressionmode) {
156              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
157                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
158                  while (copysamples) {                  while (copysamples) {
159                      *pDst = get24(pSrc) >> 8;                      *pDst = get24(pSrc) >> shift;
160                      pDst += 2;                      pDst += dstStep;
161                      pSrc += 3;                      pSrc += 3;
162                      copysamples--;                      copysamples--;
163                  }                  }
# Line 200  namespace gig { namespace { Line 229  namespace gig { namespace {
229  // *************** Sample ***************  // *************** Sample ***************
230  // *  // *
231    
232      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
233      unsigned char* 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 237  namespace gig { namespace { Line 266  namespace gig { namespace {
266    
267          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
268    
269          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
270            Compressed        = ewav;
271            Dithered          = false;
272            TruncatedBits     = 0;
273          if (Compressed) {          if (Compressed) {
274                uint32_t version = ewav->ReadInt32();
275                if (version == 3 && BitDepth == 24) {
276                    Dithered = ewav->ReadInt32();
277                    ewav->SetPos(Channels == 2 ? 84 : 64);
278                    TruncatedBits = ewav->ReadInt32();
279                }
280              ScanCompressedSample();              ScanCompressedSample();
281          }          }
282    
283          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
284          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
285              pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
286              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              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 259  namespace gig { namespace { Line 297  namespace gig { namespace {
297          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
298    
299          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
300          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
301    
302          // Scanning          // Scanning
303          pCkData->SetPos(0);          pCkData->SetPos(0);
# Line 340  namespace gig { namespace { Line 378  namespace gig { namespace {
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 388  namespace gig { namespace { Line 427  namespace gig { namespace {
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 522  namespace gig { namespace { Line 561  namespace gig { namespace {
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 558  namespace gig { namespace { Line 601  namespace gig { namespace {
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 584  namespace gig { namespace { Line 627  namespace gig { namespace {
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 608  namespace gig { namespace { Line 651  namespace gig { namespace {
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 638  namespace gig { namespace { Line 681  namespace gig { namespace {
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 660  namespace gig { namespace { Line 703  namespace gig { namespace {
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 675  namespace gig { namespace { Line 718  namespace gig { namespace {
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 694  namespace gig { namespace { Line 737  namespace gig { namespace {
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) {          if (!Compressed) {
753              if (BitDepth == 24) {              if (BitDepth == 24) {
754                  // 24 bit sample. For now just truncate to 16 bit.                  // 24 bit sample. For now just truncate to 16 bit.
755                  unsigned char* pSrc = this->pDecompressionBuffer;                  unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
756                  int16_t* pDst = static_cast<int16_t*>(pBuffer);                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
757                  if (Channels == 2) { // Stereo                  if (Channels == 2) { // Stereo
758                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
# Line 741  namespace gig { namespace { Line 789  namespace gig { namespace {
789                            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[] this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
795                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
796                  this->DecompressionBufferSize = assumedsize << 1;                  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              unsigned char* pSrc = this->pDecompressionBuffer;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
803              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
804              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
805    
# Line 831  namespace gig { namespace { Line 882  namespace gig { namespace {
882                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
883                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
884    
885                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
886                              Decompress24(mode_r, param_r, pSrc + rightChannelOffset, pDst + 1,                                           skipsamples, copysamples, TruncatedBits);
887                                           skipsamples, copysamples);                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
888                                             skipsamples, copysamples, TruncatedBits);
889                              pDst += copysamples << 1;                              pDst += copysamples << 1;
890                          }                          }
891                          else { // Mono                          else { // Mono
892                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
893                                             skipsamples, copysamples, TruncatedBits);
894                              pDst += copysamples;                              pDst += copysamples;
895                          }                          }
896                      }                      }
# Line 850  namespace gig { namespace { Line 903  namespace gig { namespace {
903                              if (mode_r) pSrc += 4;                              if (mode_r) pSrc += 4;
904    
905                              step = (2 - mode_l) + (2 - mode_r);                              step = (2 - mode_l) + (2 - mode_r);
906                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
907                              Decompress16(mode_r, param_r, step, pSrc + (2 - mode_l), pDst + 1,                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
908                                           skipsamples, copysamples);                                           skipsamples, copysamples);
909                              pDst += copysamples << 1;                              pDst += copysamples << 1;
910                          }                          }
911                          else { // Mono                          else { // Mono
912                              step = 2 - mode_l;                              step = 2 - mode_l;
913                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
914                              pDst += copysamples;                              pDst += copysamples;
915                          }                          }
916                      }                      }
# Line 869  namespace gig { namespace { Line 922  namespace gig { namespace {
922                      assumedsize    = GuessSize(remainingsamples);                      assumedsize    = GuessSize(remainingsamples);
923                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
924                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
925                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                      remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
926                      pSrc = this->pDecompressionBuffer;                      pSrc = (unsigned char*) pDecompressionBuffer->pStart;
927                  }                  }
928              } // while              } // while
929    
# Line 880  namespace gig { namespace { Line 933  namespace gig { namespace {
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) {          if (!Instances && InternalDecompressionBuffer.Size) {
981              delete[] pDecompressionBuffer;              delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
982              pDecompressionBuffer = NULL;              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;
# Line 1055  namespace gig { namespace { Line 1151  namespace gig { namespace {
1151                  VCFType = vcf_type_lowpassturbo;                  VCFType = vcf_type_lowpassturbo;
1152          }          }
1153    
1154          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1155          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;                                                       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            if ((curveType == curve_type_nonlinear && depth == 0) ||
1166                (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 =              table = CreateVelocityTable(curveType, depth, scaling);
1185                  CreateVelocityTable(VelocityResponseCurve,              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
                                     VelocityResponseDepth,  
                                     VelocityResponseCurveScaling);  
             (*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 1217  namespace gig { namespace { Line 1335  namespace gig { namespace {
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) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1343    
1344          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1318  namespace gig { namespace { Line 1440  namespace gig { namespace {
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 ||                                                             dimension == dimension_samplechannel ||
1443                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
1444                                                                                                    : split_type_normal;                                                             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
# Line 1475  namespace gig { namespace { Line 1599  namespace gig { namespace {
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;          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 1492  namespace gig { namespace { Line 1618  namespace gig { namespace {
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 1523  namespace gig { namespace { Line 1649  namespace gig { namespace {
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 1535  namespace gig { namespace { Line 1662  namespace gig { namespace {
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 1621  namespace gig { namespace { Line 1750  namespace gig { namespace {
1750              pInstruments->clear();              pInstruments->clear();
1751              delete pInstruments;              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() {      Sample* File::GetFirstSample(progress_t* pProgress) {
1759          if (!pSamples) LoadSamples();          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 1636  namespace gig { namespace { Line 1768  namespace gig { namespace {
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 1669  namespace gig { namespace { Line 1836  namespace gig { namespace {
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 1682  namespace gig { namespace { Line 1869  namespace gig { namespace {
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 1709  namespace gig { namespace { Line 1908  namespace gig { namespace {
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.365  
changed lines
  Added in v.695

  ViewVC Help
Powered by ViewVC