/[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 515 by schoenebeck, Sat May 7 20:19:10 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            __range_min = 0.0f;
36            __range_max = 1.0f;
37        }
38    
39        // private helper function to convert progress of a subprocess into the global progress
40        static void __notify_progress(progress_t* pProgress, float subprogress) {
41            if (pProgress && pProgress->callback) {
42                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
43                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
44                pProgress->callback(totalprogress); // now actually notify about the progress
45            }
46        }
47    
48        // private helper function to divide a progress into subprogresses
49        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
50            if (pParentProgress && pParentProgress->callback) {
51                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
52                pSubProgress->callback    = pParentProgress->callback;
53                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
54                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
55            }
56        }
57    
58    
59  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decopmression ***************
60  // *  // *
61    
62    namespace {
63    
64      inline int get12lo(const unsigned char* pSrc)      inline int get12lo(const unsigned char* pSrc)
65      {      {
66          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
# Line 52  namespace gig { namespace { Line 85  namespace gig { namespace {
85      }      }
86    
87      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
88                        int srcStep, const unsigned char* pSrc, int16_t* pDst,                        int srcStep, int dstStep,
89                          const unsigned char* pSrc, int16_t* pDst,
90                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
91                        unsigned long copysamples)                        unsigned long copysamples)
92      {      {
# Line 61  namespace gig { namespace { Line 95  namespace gig { namespace {
95                  pSrc += currentframeoffset * srcStep;                  pSrc += currentframeoffset * srcStep;
96                  while (copysamples) {                  while (copysamples) {
97                      *pDst = get16(pSrc);                      *pDst = get16(pSrc);
98                      pDst += 2;                      pDst += dstStep;
99                      pSrc += srcStep;                      pSrc += srcStep;
100                      copysamples--;                      copysamples--;
101                  }                  }
# Line 80  namespace gig { namespace { Line 114  namespace gig { namespace {
114                      dy -= int8_t(*pSrc);                      dy -= int8_t(*pSrc);
115                      y  -= dy;                      y  -= dy;
116                      *pDst = y;                      *pDst = y;
117                      pDst += 2;                      pDst += dstStep;
118                      pSrc += srcStep;                      pSrc += srcStep;
119                      copysamples--;                      copysamples--;
120                  }                  }
# Line 89  namespace gig { namespace { Line 123  namespace gig { namespace {
123      }      }
124    
125      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
126                        const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, int16_t* pDst,
127                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
128                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
129      {      {
130          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
131    
# Line 103  namespace gig { namespace { Line 137  namespace gig { namespace {
137          //          //
138          // Strange thing #2: The formula in SKIP_ONE gives values for          // Strange thing #2: The formula in SKIP_ONE gives values for
139          // y that are twice as high as they should be. That's why          // y that are twice as high as they should be. That's why
140          // COPY_ONE shifts 9 steps instead of 8, and also why y is          // COPY_ONE shifts an extra step, and also why y is
141          // initialized with a sum instead of a mean value.          // initialized with a sum instead of a mean value.
142    
143          int y, dy, ddy;          int y, dy, ddy;
144    
145            const int shift = 8 - truncatedBits;
146            const int shift1 = shift + 1;
147    
148  #define GET_PARAMS(params)                              \  #define GET_PARAMS(params)                              \
149          y = (get24(params) + get24((params) + 3));      \          y = (get24(params) + get24((params) + 3));      \
150          dy  = get24((params) + 6);                      \          dy  = get24((params) + 6);                      \
# Line 120  namespace gig { namespace { Line 157  namespace gig { namespace {
157    
158  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
159          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
160          *pDst = y >> 9;                         \          *pDst = y >> shift1;                    \
161          pDst += 2          pDst += dstStep
162    
163          switch (compressionmode) {          switch (compressionmode) {
164              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
165                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
166                  while (copysamples) {                  while (copysamples) {
167                      *pDst = get24(pSrc) >> 8;                      *pDst = get24(pSrc) >> shift;
168                      pDst += 2;                      pDst += dstStep;
169                      pSrc += 3;                      pSrc += 3;
170                      copysamples--;                      copysamples--;
171                  }                  }
# Line 200  namespace gig { namespace { Line 237  namespace gig { namespace {
237  // *************** Sample ***************  // *************** Sample ***************
238  // *  // *
239    
240      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
241      unsigned char* Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
242    
243      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) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
244          Instances++;          Instances++;
# Line 237  namespace gig { namespace { Line 273  namespace gig { namespace {
273    
274          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");
275    
276          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
277            Compressed        = ewav;
278            Dithered          = false;
279            TruncatedBits     = 0;
280          if (Compressed) {          if (Compressed) {
281                uint32_t version = ewav->ReadInt32();
282                if (version == 3 && BitDepth == 24) {
283                    Dithered = ewav->ReadInt32();
284                    ewav->SetPos(Channels == 2 ? 84 : 64);
285                    TruncatedBits = ewav->ReadInt32();
286                }
287              ScanCompressedSample();              ScanCompressedSample();
288          }          }
289    
290          // 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
291          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
292              pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
293              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
294          }          }
295          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
296    
297          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
298      }      }
# Line 259  namespace gig { namespace { Line 304  namespace gig { namespace {
304          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
305    
306          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
307          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
308    
309          // Scanning          // Scanning
310          pCkData->SetPos(0);          pCkData->SetPos(0);
# Line 340  namespace gig { namespace { Line 385  namespace gig { namespace {
385       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
386       * 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
387       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
388       *       * @code
389       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
390       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
391         * @endcode
392       *       *
393       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
394       * @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 434  namespace gig { namespace {
434       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
435       * 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
436       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
437       *       * @code
438       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
439       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
440       *       * @endcode
441       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
442       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
443       * 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 568  namespace gig { namespace {
568       * 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.
569       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
570       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
571       *       * @code
572       * <i>       * gig::playback_state_t playbackstate;
573       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
574       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
575       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
576       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
577       * 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
578       * 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.
579       * The method already handles such cases by itself.       * The method already handles such cases by itself.
580       *       *
581         * <b>Caution:</b> If you are using more than one streaming thread, you
582         * have to use an external decompression buffer for <b>EACH</b>
583         * streaming thread to avoid race conditions and crashes!
584         *
585       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
586       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
587       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
588       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
589         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
590       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
591         * @see                    CreateDecompressionBuffer()
592       */       */
593      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) {
594          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
595          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
596    
# Line 558  namespace gig { namespace { Line 608  namespace gig { namespace {
608                          if (!pPlaybackState->reverse) { // forward playback                          if (!pPlaybackState->reverse) { // forward playback
609                              do {                              do {
610                                  samplestoloopend  = this->LoopEnd - GetPos();                                  samplestoloopend  = this->LoopEnd - GetPos();
611                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
612                                  samplestoread    -= readsamples;                                  samplestoread    -= readsamples;
613                                  totalreadsamples += readsamples;                                  totalreadsamples += readsamples;
614                                  if (readsamples == samplestoloopend) {                                  if (readsamples == samplestoloopend) {
# Line 584  namespace gig { namespace { Line 634  namespace gig { namespace {
634    
635                              // read samples for backward playback                              // read samples for backward playback
636                              do {                              do {
637                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
638                                  samplestoreadinloop -= readsamples;                                  samplestoreadinloop -= readsamples;
639                                  samplestoread       -= readsamples;                                  samplestoread       -= readsamples;
640                                  totalreadsamples    += readsamples;                                  totalreadsamples    += readsamples;
# Line 608  namespace gig { namespace { Line 658  namespace gig { namespace {
658                      // forward playback (not entered the loop yet)                      // forward playback (not entered the loop yet)
659                      if (!pPlaybackState->reverse) do {                      if (!pPlaybackState->reverse) do {
660                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
661                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
662                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
663                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
664                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 638  namespace gig { namespace { Line 688  namespace gig { namespace {
688                          // 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
689                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
690                          samplestoloopend     = this->LoopEnd - GetPos();                          samplestoloopend     = this->LoopEnd - GetPos();
691                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
692                          samplestoreadinloop -= readsamples;                          samplestoreadinloop -= readsamples;
693                          samplestoread       -= readsamples;                          samplestoread       -= readsamples;
694                          totalreadsamples    += readsamples;                          totalreadsamples    += readsamples;
# Line 660  namespace gig { namespace { Line 710  namespace gig { namespace {
710                          // 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
711                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
712                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
713                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
714                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
715                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
716                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 675  namespace gig { namespace { Line 725  namespace gig { namespace {
725    
726          // read on without looping          // read on without looping
727          if (samplestoread) do {          if (samplestoread) do {
728              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
729              samplestoread    -= readsamples;              samplestoread    -= readsamples;
730              totalreadsamples += readsamples;              totalreadsamples += readsamples;
731          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 694  namespace gig { namespace { Line 744  namespace gig { namespace {
744       * 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,
745       * thus for disk streaming.       * thus for disk streaming.
746       *       *
747         * <b>Caution:</b> If you are using more than one streaming thread, you
748         * have to use an external decompression buffer for <b>EACH</b>
749         * streaming thread to avoid race conditions and crashes!
750         *
751       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
752       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
753         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
754       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
755       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
756       */       */
757      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
758          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
759          if (!Compressed) {          if (!Compressed) {
760              if (BitDepth == 24) {              if (BitDepth == 24) {
761                  // 24 bit sample. For now just truncate to 16 bit.                  // 24 bit sample. For now just truncate to 16 bit.
762                  unsigned char* pSrc = this->pDecompressionBuffer;                  unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
763                  int16_t* pDst = static_cast<int16_t*>(pBuffer);                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
764                  if (Channels == 2) { // Stereo                  if (Channels == 2) { // Stereo
765                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
# Line 741  namespace gig { namespace { Line 796  namespace gig { namespace {
796                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
797              this->FrameOffset = 0;              this->FrameOffset = 0;
798    
799              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
800                  // local buffer reallocation - hope this won't happen  
801                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
802                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
803                  this->DecompressionBufferSize = assumedsize << 1;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
804                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
805                    remainingsamples = SampleCount;
806                    assumedsize      = GuessSize(SampleCount);
807              }              }
808    
809              unsigned char* pSrc = this->pDecompressionBuffer;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
810              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
811              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
812    
# Line 831  namespace gig { namespace { Line 889  namespace gig { namespace {
889                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
890                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
891    
892                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
893                              Decompress24(mode_r, param_r, pSrc + rightChannelOffset, pDst + 1,                                           skipsamples, copysamples, TruncatedBits);
894                                           skipsamples, copysamples);                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
895                                             skipsamples, copysamples, TruncatedBits);
896                              pDst += copysamples << 1;                              pDst += copysamples << 1;
897                          }                          }
898                          else { // Mono                          else { // Mono
899                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
900                                             skipsamples, copysamples, TruncatedBits);
901                              pDst += copysamples;                              pDst += copysamples;
902                          }                          }
903                      }                      }
# Line 850  namespace gig { namespace { Line 910  namespace gig { namespace {
910                              if (mode_r) pSrc += 4;                              if (mode_r) pSrc += 4;
911    
912                              step = (2 - mode_l) + (2 - mode_r);                              step = (2 - mode_l) + (2 - mode_r);
913                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
914                              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,
915                                           skipsamples, copysamples);                                           skipsamples, copysamples);
916                              pDst += copysamples << 1;                              pDst += copysamples << 1;
917                          }                          }
918                          else { // Mono                          else { // Mono
919                              step = 2 - mode_l;                              step = 2 - mode_l;
920                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
921                              pDst += copysamples;                              pDst += copysamples;
922                          }                          }
923                      }                      }
# Line 869  namespace gig { namespace { Line 929  namespace gig { namespace {
929                      assumedsize    = GuessSize(remainingsamples);                      assumedsize    = GuessSize(remainingsamples);
930                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
931                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
932                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                      remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
933                      pSrc = this->pDecompressionBuffer;                      pSrc = (unsigned char*) pDecompressionBuffer->pStart;
934                  }                  }
935              } // while              } // while
936    
# Line 880  namespace gig { namespace { Line 940  namespace gig { namespace {
940          }          }
941      }      }
942    
943        /**
944         * Allocates a decompression buffer for streaming (compressed) samples
945         * with Sample::Read(). If you are using more than one streaming thread
946         * in your application you <b>HAVE</b> to create a decompression buffer
947         * for <b>EACH</b> of your streaming threads and provide it with the
948         * Sample::Read() call in order to avoid race conditions and crashes.
949         *
950         * You should free the memory occupied by the allocated buffer(s) once
951         * you don't need one of your streaming threads anymore by calling
952         * DestroyDecompressionBuffer().
953         *
954         * @param MaxReadSize - the maximum size (in sample points) you ever
955         *                      expect to read with one Read() call
956         * @returns allocated decompression buffer
957         * @see DestroyDecompressionBuffer()
958         */
959        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
960            buffer_t result;
961            const double worstCaseHeaderOverhead =
962                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
963            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
964            result.pStart            = new int8_t[result.Size];
965            result.NullExtensionSize = 0;
966            return result;
967        }
968    
969        /**
970         * Free decompression buffer, previously created with
971         * CreateDecompressionBuffer().
972         *
973         * @param DecompressionBuffer - previously allocated decompression
974         *                              buffer to free
975         */
976        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
977            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
978                delete[] (int8_t*) DecompressionBuffer.pStart;
979                DecompressionBuffer.pStart = NULL;
980                DecompressionBuffer.Size   = 0;
981                DecompressionBuffer.NullExtensionSize = 0;
982            }
983        }
984    
985      Sample::~Sample() {      Sample::~Sample() {
986          Instances--;          Instances--;
987          if (!Instances && pDecompressionBuffer) {          if (!Instances && InternalDecompressionBuffer.Size) {
988              delete[] pDecompressionBuffer;              delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
989              pDecompressionBuffer = NULL;              InternalDecompressionBuffer.pStart = NULL;
990                InternalDecompressionBuffer.Size   = 0;
991          }          }
992          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
993          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
# Line 1067  namespace gig { namespace { Line 1170  namespace gig { namespace {
1170                                      VelocityResponseCurveScaling);                                      VelocityResponseCurveScaling);
1171              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
1172          }          }
1173    
1174            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1175      }      }
1176    
1177      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1318  namespace gig { namespace { Line 1423  namespace gig { namespace {
1423                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1424                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1425                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
1426                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
1427                                                                                                    : split_type_normal;                                                             dimension == dimension_roundrobin ||
1428                                                               dimension == dimension_random) ? split_type_bit
1429                                                                                              : split_type_normal;
1430                      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
1431                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1432                          (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 1582  namespace gig { namespace {
1582          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1583      }      }
1584    
1585      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
1586          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
1587          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1588          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1589          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample(pProgress);
1590          while (sample) {          while (sample) {
1591              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
1592              sample = file->GetNextSample();              sample = file->GetNextSample();
# Line 1492  namespace gig { namespace { Line 1599  namespace gig { namespace {
1599  // *************** Instrument ***************  // *************** Instrument ***************
1600  // *  // *
1601    
1602      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) {
1603          // Initialization          // Initialization
1604          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1605          RegionIndex = -1;          RegionIndex = -1;
# Line 1523  namespace gig { namespace { Line 1630  namespace gig { namespace {
1630          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1631          while (rgn) {          while (rgn) {
1632              if (rgn->GetListType() == LIST_TYPE_RGN) {              if (rgn->GetListType() == LIST_TYPE_RGN) {
1633                    __notify_progress(pProgress, (float) iRegion / (float) Regions);
1634                  pRegions[iRegion] = new Region(this, rgn);                  pRegions[iRegion] = new Region(this, rgn);
1635                  iRegion++;                  iRegion++;
1636              }              }
# Line 1535  namespace gig { namespace { Line 1643  namespace gig { namespace {
1643                  RegionKeyTable[iKey] = pRegions[iReg];                  RegionKeyTable[iKey] = pRegions[iReg];
1644              }              }
1645          }          }
1646    
1647            __notify_progress(pProgress, 1.0f); // notify done
1648      }      }
1649    
1650      Instrument::~Instrument() {      Instrument::~Instrument() {
# Line 1623  namespace gig { namespace { Line 1733  namespace gig { namespace {
1733          }          }
1734      }      }
1735    
1736      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
1737          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
1738          if (!pSamples) return NULL;          if (!pSamples) return NULL;
1739          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
1740          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 1746  namespace gig { namespace {
1746          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1747      }      }
1748    
1749      void File::LoadSamples() {      void File::LoadSamples(progress_t* pProgress) {
1750          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1751          if (wvpl) {          if (wvpl) {
1752                // just for progress calculation
1753                int iSampleIndex  = 0;
1754                int iTotalSamples = wvpl->CountSubLists(LIST_TYPE_WAVE);
1755    
1756              unsigned long wvplFileOffset = wvpl->GetFilePos();              unsigned long wvplFileOffset = wvpl->GetFilePos();
1757              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1758              while (wave) {              while (wave) {
1759                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1760                        // notify current progress
1761                        const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
1762                        __notify_progress(pProgress, subprogress);
1763    
1764                      if (!pSamples) pSamples = new SampleList;                      if (!pSamples) pSamples = new SampleList;
1765                      unsigned long waveFileOffset = wave->GetFilePos();                      unsigned long waveFileOffset = wave->GetFilePos();
1766                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1767    
1768                        iSampleIndex++;
1769                  }                  }
1770                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
1771              }              }
1772                __notify_progress(pProgress, 1.0); // notify done
1773          }          }
1774          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1775      }      }
# Line 1669  namespace gig { namespace { Line 1790  namespace gig { namespace {
1790      /**      /**
1791       * Returns the instrument with the given index.       * Returns the instrument with the given index.
1792       *       *
1793         * @param index     - number of the sought instrument (0..n)
1794         * @param pProgress - optional: callback function for progress notification
1795       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
1796       */       */
1797      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
1798          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
1799                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
1800    
1801                // sample loading subtask
1802                progress_t subprogress;
1803                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
1804                __notify_progress(&subprogress, 0.0f);
1805                GetFirstSample(&subprogress); // now force all samples to be loaded
1806                __notify_progress(&subprogress, 1.0f);
1807    
1808                // instrument loading subtask
1809                if (pProgress && pProgress->callback) {
1810                    subprogress.__range_min = subprogress.__range_max;
1811                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
1812                }
1813                __notify_progress(&subprogress, 0.0f);
1814                LoadInstruments(&subprogress);
1815                __notify_progress(&subprogress, 1.0f);
1816            }
1817          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
1818          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
1819          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
# Line 1682  namespace gig { namespace { Line 1823  namespace gig { namespace {
1823          return NULL;          return NULL;
1824      }      }
1825    
1826      void File::LoadInstruments() {      void File::LoadInstruments(progress_t* pProgress) {
1827          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1828          if (lstInstruments) {          if (lstInstruments) {
1829                int iInstrumentIndex = 0;
1830              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1831              while (lstInstr) {              while (lstInstr) {
1832                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1833                        // notify current progress
1834                        const float localProgress = (float) iInstrumentIndex / (float) Instruments;
1835                        __notify_progress(pProgress, localProgress);
1836    
1837                        // divide local progress into subprogress for loading current Instrument
1838                        progress_t subprogress;
1839                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
1840    
1841                      if (!pInstruments) pInstruments = new InstrumentList;                      if (!pInstruments) pInstruments = new InstrumentList;
1842                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
1843    
1844                        iInstrumentIndex++;
1845                  }                  }
1846                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
1847              }              }
1848                __notify_progress(pProgress, 1.0); // notify done
1849          }          }
1850          else throw gig::Exception("Mandatory <lins> list chunk not found.");          else throw gig::Exception("Mandatory <lins> list chunk not found.");
1851      }      }

Legend:
Removed from v.365  
changed lines
  Added in v.515

  ViewVC Help
Powered by ViewVC