/[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 372 by persson, Fri Feb 11 18:58:07 2005 UTC revision 518 by schoenebeck, Sun May 8 16:19:34 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 92  namespace gig { namespace { Line 128  namespace gig { namespace {
128      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
129                        int dstStep, 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    
# Line 104  namespace gig { namespace { Line 140  namespace gig { namespace {
140          //          //
141          // Strange thing #2: The formula in SKIP_ONE gives values for          // Strange thing #2: The formula in SKIP_ONE gives values for
142          // 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
143          // COPY_ONE shifts 9 steps instead of 8, and also why y is          // COPY_ONE shifts an extra step, and also why y is
144          // initialized with a sum instead of a mean value.          // initialized with a sum instead of a mean value.
145    
146          int y, dy, ddy;          int y, dy, ddy;
147    
148            const int shift = 8 - truncatedBits;
149            const int shift1 = shift + 1;
150    
151  #define GET_PARAMS(params)                              \  #define GET_PARAMS(params)                              \
152          y = (get24(params) + get24((params) + 3));      \          y = (get24(params) + get24((params) + 3));      \
153          dy  = get24((params) + 6);                      \          dy  = get24((params) + 6);                      \
# Line 121  namespace gig { namespace { Line 160  namespace gig { namespace {
160    
161  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
162          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
163          *pDst = y >> 9;                         \          *pDst = y >> shift1;                    \
164          pDst += dstStep          pDst += dstStep
165    
166          switch (compressionmode) {          switch (compressionmode) {
167              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
168                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
169                  while (copysamples) {                  while (copysamples) {
170                      *pDst = get24(pSrc) >> 8;                      *pDst = get24(pSrc) >> shift;
171                      pDst += dstStep;                      pDst += dstStep;
172                      pSrc += 3;                      pSrc += 3;
173                      copysamples--;                      copysamples--;
# Line 201  namespace gig { namespace { Line 240  namespace gig { namespace {
240  // *************** Sample ***************  // *************** Sample ***************
241  // *  // *
242    
243      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
244      unsigned char* Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
245    
246      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) {
247          Instances++;          Instances++;
# Line 238  namespace gig { namespace { Line 276  namespace gig { namespace {
276    
277          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");
278    
279          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
280            Compressed        = ewav;
281            Dithered          = false;
282            TruncatedBits     = 0;
283          if (Compressed) {          if (Compressed) {
284                uint32_t version = ewav->ReadInt32();
285                if (version == 3 && BitDepth == 24) {
286                    Dithered = ewav->ReadInt32();
287                    ewav->SetPos(Channels == 2 ? 84 : 64);
288                    TruncatedBits = ewav->ReadInt32();
289                }
290              ScanCompressedSample();              ScanCompressedSample();
291          }          }
292    
293          // 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
294          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
295              pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
296              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
297          }          }
298          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
299    
300          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
301      }      }
# Line 260  namespace gig { namespace { Line 307  namespace gig { namespace {
307          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
308    
309          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
310          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
311    
312          // Scanning          // Scanning
313          pCkData->SetPos(0);          pCkData->SetPos(0);
# Line 341  namespace gig { namespace { Line 388  namespace gig { namespace {
388       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
389       * 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
390       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
391       *       * @code
392       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
393       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
394         * @endcode
395       *       *
396       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
397       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 389  namespace gig { namespace { Line 437  namespace gig { namespace {
437       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
438       * 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
439       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
440       *       * @code
441       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
442       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
443       *       * @endcode
444       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
445       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
446       * 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 523  namespace gig { namespace { Line 571  namespace gig { namespace {
571       * 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.
572       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
573       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
574       *       * @code
575       * <i>       * gig::playback_state_t playbackstate;
576       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
577       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
578       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
579       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
580       * 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
581       * 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.
582       * The method already handles such cases by itself.       * The method already handles such cases by itself.
583       *       *
584         * <b>Caution:</b> If you are using more than one streaming thread, you
585         * have to use an external decompression buffer for <b>EACH</b>
586         * streaming thread to avoid race conditions and crashes!
587         *
588       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
589       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
590       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
591       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
592         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
593       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
594         * @see                    CreateDecompressionBuffer()
595       */       */
596      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) {
597          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
598          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
599    
# Line 559  namespace gig { namespace { Line 611  namespace gig { namespace {
611                          if (!pPlaybackState->reverse) { // forward playback                          if (!pPlaybackState->reverse) { // forward playback
612                              do {                              do {
613                                  samplestoloopend  = this->LoopEnd - GetPos();                                  samplestoloopend  = this->LoopEnd - GetPos();
614                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
615                                  samplestoread    -= readsamples;                                  samplestoread    -= readsamples;
616                                  totalreadsamples += readsamples;                                  totalreadsamples += readsamples;
617                                  if (readsamples == samplestoloopend) {                                  if (readsamples == samplestoloopend) {
# Line 585  namespace gig { namespace { Line 637  namespace gig { namespace {
637    
638                              // read samples for backward playback                              // read samples for backward playback
639                              do {                              do {
640                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
641                                  samplestoreadinloop -= readsamples;                                  samplestoreadinloop -= readsamples;
642                                  samplestoread       -= readsamples;                                  samplestoread       -= readsamples;
643                                  totalreadsamples    += readsamples;                                  totalreadsamples    += readsamples;
# Line 609  namespace gig { namespace { Line 661  namespace gig { namespace {
661                      // forward playback (not entered the loop yet)                      // forward playback (not entered the loop yet)
662                      if (!pPlaybackState->reverse) do {                      if (!pPlaybackState->reverse) do {
663                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
664                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
665                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
666                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
667                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 639  namespace gig { namespace { Line 691  namespace gig { namespace {
691                          // 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
692                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
693                          samplestoloopend     = this->LoopEnd - GetPos();                          samplestoloopend     = this->LoopEnd - GetPos();
694                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
695                          samplestoreadinloop -= readsamples;                          samplestoreadinloop -= readsamples;
696                          samplestoread       -= readsamples;                          samplestoread       -= readsamples;
697                          totalreadsamples    += readsamples;                          totalreadsamples    += readsamples;
# Line 661  namespace gig { namespace { Line 713  namespace gig { namespace {
713                          // 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
714                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
715                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
716                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
717                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
718                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
719                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 676  namespace gig { namespace { Line 728  namespace gig { namespace {
728    
729          // read on without looping          // read on without looping
730          if (samplestoread) do {          if (samplestoread) do {
731              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
732              samplestoread    -= readsamples;              samplestoread    -= readsamples;
733              totalreadsamples += readsamples;              totalreadsamples += readsamples;
734          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 695  namespace gig { namespace { Line 747  namespace gig { namespace {
747       * 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,
748       * thus for disk streaming.       * thus for disk streaming.
749       *       *
750         * <b>Caution:</b> If you are using more than one streaming thread, you
751         * have to use an external decompression buffer for <b>EACH</b>
752         * streaming thread to avoid race conditions and crashes!
753         *
754       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
755       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
756         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
757       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
758       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
759       */       */
760      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
761          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
762          if (!Compressed) {          if (!Compressed) {
763              if (BitDepth == 24) {              if (BitDepth == 24) {
764                  // 24 bit sample. For now just truncate to 16 bit.                  // 24 bit sample. For now just truncate to 16 bit.
765                  unsigned char* pSrc = this->pDecompressionBuffer;                  unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
766                  int16_t* pDst = static_cast<int16_t*>(pBuffer);                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
767                  if (Channels == 2) { // Stereo                  if (Channels == 2) { // Stereo
768                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
# Line 742  namespace gig { namespace { Line 799  namespace gig { namespace {
799                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
800              this->FrameOffset = 0;              this->FrameOffset = 0;
801    
802              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
803                  // local buffer reallocation - hope this won't happen  
804                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
805                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
806                  this->DecompressionBufferSize = assumedsize << 1;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
807                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
808                    remainingsamples = SampleCount;
809                    assumedsize      = GuessSize(SampleCount);
810              }              }
811    
812              unsigned char* pSrc = this->pDecompressionBuffer;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
813              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
814              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
815    
# Line 832  namespace gig { namespace { Line 892  namespace gig { namespace {
892                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
893                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
894    
895                              Decompress24(mode_l, param_l, 2, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
896                                             skipsamples, copysamples, TruncatedBits);
897                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
898                                           skipsamples, copysamples);                                           skipsamples, copysamples, TruncatedBits);
899                              pDst += copysamples << 1;                              pDst += copysamples << 1;
900                          }                          }
901                          else { // Mono                          else { // Mono
902                              Decompress24(mode_l, param_l, 1, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
903                                             skipsamples, copysamples, TruncatedBits);
904                              pDst += copysamples;                              pDst += copysamples;
905                          }                          }
906                      }                      }
# Line 870  namespace gig { namespace { Line 932  namespace gig { namespace {
932                      assumedsize    = GuessSize(remainingsamples);                      assumedsize    = GuessSize(remainingsamples);
933                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
934                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
935                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                      remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
936                      pSrc = this->pDecompressionBuffer;                      pSrc = (unsigned char*) pDecompressionBuffer->pStart;
937                  }                  }
938              } // while              } // while
939    
# Line 881  namespace gig { namespace { Line 943  namespace gig { namespace {
943          }          }
944      }      }
945    
946        /**
947         * Allocates a decompression buffer for streaming (compressed) samples
948         * with Sample::Read(). If you are using more than one streaming thread
949         * in your application you <b>HAVE</b> to create a decompression buffer
950         * for <b>EACH</b> of your streaming threads and provide it with the
951         * Sample::Read() call in order to avoid race conditions and crashes.
952         *
953         * You should free the memory occupied by the allocated buffer(s) once
954         * you don't need one of your streaming threads anymore by calling
955         * DestroyDecompressionBuffer().
956         *
957         * @param MaxReadSize - the maximum size (in sample points) you ever
958         *                      expect to read with one Read() call
959         * @returns allocated decompression buffer
960         * @see DestroyDecompressionBuffer()
961         */
962        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
963            buffer_t result;
964            const double worstCaseHeaderOverhead =
965                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
966            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
967            result.pStart            = new int8_t[result.Size];
968            result.NullExtensionSize = 0;
969            return result;
970        }
971    
972        /**
973         * Free decompression buffer, previously created with
974         * CreateDecompressionBuffer().
975         *
976         * @param DecompressionBuffer - previously allocated decompression
977         *                              buffer to free
978         */
979        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
980            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
981                delete[] (int8_t*) DecompressionBuffer.pStart;
982                DecompressionBuffer.pStart = NULL;
983                DecompressionBuffer.Size   = 0;
984                DecompressionBuffer.NullExtensionSize = 0;
985            }
986        }
987    
988      Sample::~Sample() {      Sample::~Sample() {
989          Instances--;          Instances--;
990          if (!Instances && pDecompressionBuffer) {          if (!Instances && InternalDecompressionBuffer.Size) {
991              delete[] pDecompressionBuffer;              delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
992              pDecompressionBuffer = NULL;              InternalDecompressionBuffer.pStart = NULL;
993                InternalDecompressionBuffer.Size   = 0;
994          }          }
995          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
996          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
# Line 1068  namespace gig { namespace { Line 1173  namespace gig { namespace {
1173                                      VelocityResponseCurveScaling);                                      VelocityResponseCurveScaling);
1174              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
1175          }          }
1176    
1177            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1178      }      }
1179    
1180      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1319  namespace gig { namespace { Line 1426  namespace gig { namespace {
1426                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1427                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1428                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
1429                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
1430                                                                                                    : split_type_normal;                                                             dimension == dimension_roundrobin ||
1431                                                               dimension == dimension_random) ? split_type_bit
1432                                                                                              : split_type_normal;
1433                      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
1434                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1435                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
# Line 1476  namespace gig { namespace { Line 1585  namespace gig { namespace {
1585          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1586      }      }
1587    
1588      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
1589          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
1590          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1591          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1592          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample(pProgress);
1593          while (sample) {          while (sample) {
1594              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
1595              sample = file->GetNextSample();              sample = file->GetNextSample();
# Line 1493  namespace gig { namespace { Line 1602  namespace gig { namespace {
1602  // *************** Instrument ***************  // *************** Instrument ***************
1603  // *  // *
1604    
1605      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) {
1606          // Initialization          // Initialization
1607          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1608          RegionIndex = -1;          RegionIndex = -1;
# Line 1524  namespace gig { namespace { Line 1633  namespace gig { namespace {
1633          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1634          while (rgn) {          while (rgn) {
1635              if (rgn->GetListType() == LIST_TYPE_RGN) {              if (rgn->GetListType() == LIST_TYPE_RGN) {
1636                    __notify_progress(pProgress, (float) iRegion / (float) Regions);
1637                  pRegions[iRegion] = new Region(this, rgn);                  pRegions[iRegion] = new Region(this, rgn);
1638                  iRegion++;                  iRegion++;
1639              }              }
# Line 1536  namespace gig { namespace { Line 1646  namespace gig { namespace {
1646                  RegionKeyTable[iKey] = pRegions[iReg];                  RegionKeyTable[iKey] = pRegions[iReg];
1647              }              }
1648          }          }
1649    
1650            __notify_progress(pProgress, 1.0f); // notify done
1651      }      }
1652    
1653      Instrument::~Instrument() {      Instrument::~Instrument() {
# Line 1624  namespace gig { namespace { Line 1736  namespace gig { namespace {
1736          }          }
1737      }      }
1738    
1739      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
1740          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
1741          if (!pSamples) return NULL;          if (!pSamples) return NULL;
1742          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
1743          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1637  namespace gig { namespace { Line 1749  namespace gig { namespace {
1749          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1750      }      }
1751    
1752      void File::LoadSamples() {      void File::LoadSamples(progress_t* pProgress) {
1753          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1754          if (wvpl) {          if (wvpl) {
1755                // just for progress calculation
1756                int iSampleIndex  = 0;
1757                int iTotalSamples = wvpl->CountSubLists(LIST_TYPE_WAVE);
1758    
1759              unsigned long wvplFileOffset = wvpl->GetFilePos();              unsigned long wvplFileOffset = wvpl->GetFilePos();
1760              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1761              while (wave) {              while (wave) {
1762                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1763                        // notify current progress
1764                        const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
1765                        __notify_progress(pProgress, subprogress);
1766    
1767                      if (!pSamples) pSamples = new SampleList;                      if (!pSamples) pSamples = new SampleList;
1768                      unsigned long waveFileOffset = wave->GetFilePos();                      unsigned long waveFileOffset = wave->GetFilePos();
1769                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1770    
1771                        iSampleIndex++;
1772                  }                  }
1773                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
1774              }              }
1775                __notify_progress(pProgress, 1.0); // notify done
1776          }          }
1777          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1778      }      }
# Line 1670  namespace gig { namespace { Line 1793  namespace gig { namespace {
1793      /**      /**
1794       * Returns the instrument with the given index.       * Returns the instrument with the given index.
1795       *       *
1796         * @param index     - number of the sought instrument (0..n)
1797         * @param pProgress - optional: callback function for progress notification
1798       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
1799       */       */
1800      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
1801          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
1802                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
1803    
1804                // sample loading subtask
1805                progress_t subprogress;
1806                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
1807                __notify_progress(&subprogress, 0.0f);
1808                GetFirstSample(&subprogress); // now force all samples to be loaded
1809                __notify_progress(&subprogress, 1.0f);
1810    
1811                // instrument loading subtask
1812                if (pProgress && pProgress->callback) {
1813                    subprogress.__range_min = subprogress.__range_max;
1814                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
1815                }
1816                __notify_progress(&subprogress, 0.0f);
1817                LoadInstruments(&subprogress);
1818                __notify_progress(&subprogress, 1.0f);
1819            }
1820          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
1821          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
1822          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
# Line 1683  namespace gig { namespace { Line 1826  namespace gig { namespace {
1826          return NULL;          return NULL;
1827      }      }
1828    
1829      void File::LoadInstruments() {      void File::LoadInstruments(progress_t* pProgress) {
1830          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1831          if (lstInstruments) {          if (lstInstruments) {
1832                int iInstrumentIndex = 0;
1833              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1834              while (lstInstr) {              while (lstInstr) {
1835                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1836                        // notify current progress
1837                        const float localProgress = (float) iInstrumentIndex / (float) Instruments;
1838                        __notify_progress(pProgress, localProgress);
1839    
1840                        // divide local progress into subprogress for loading current Instrument
1841                        progress_t subprogress;
1842                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
1843    
1844                      if (!pInstruments) pInstruments = new InstrumentList;                      if (!pInstruments) pInstruments = new InstrumentList;
1845                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
1846    
1847                        iInstrumentIndex++;
1848                  }                  }
1849                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
1850              }              }
1851                __notify_progress(pProgress, 1.0); // notify done
1852          }          }
1853          else throw gig::Exception("Mandatory <lins> list chunk not found.");          else throw gig::Exception("Mandatory <lins> list chunk not found.");
1854      }      }
# Line 1710  namespace gig { namespace { Line 1865  namespace gig { namespace {
1865          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
1866      }      }
1867    
1868    
1869    // *************** functions ***************
1870    // *
1871    
1872        /**
1873         * Returns the name of this C++ library. This is usually "libgig" of
1874         * course. This call is equivalent to RIFF::libraryName() and
1875         * DLS::libraryName().
1876         */
1877        String libraryName() {
1878            return PACKAGE;
1879        }
1880    
1881        /**
1882         * Returns version of this C++ library. This call is equivalent to
1883         * RIFF::libraryVersion() and DLS::libraryVersion().
1884         */
1885        String libraryVersion() {
1886            return VERSION;
1887        }
1888    
1889  } // namespace gig  } // namespace gig

Legend:
Removed from v.372  
changed lines
  Added in v.518

  ViewVC Help
Powered by ViewVC