/[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 666 by persson, Sun Jun 19 15:18:59 2005 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file loader library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Christian Schoenebeck                     *   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *
6   *                               <cuse@users.sourceforge.net>              *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26  namespace gig { namespace {  #include <iostream>
27    
28    namespace gig {
29    
30    // *************** progress_t ***************
31    // *
32    
33        progress_t::progress_t() {
34            callback    = NULL;
35            custom      = NULL;
36            __range_min = 0.0f;
37            __range_max = 1.0f;
38        }
39    
40        // private helper function to convert progress of a subprocess into the global progress
41        static void __notify_progress(progress_t* pProgress, float subprogress) {
42            if (pProgress && pProgress->callback) {
43                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
44                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
45                pProgress->factor         = totalprogress;
46                pProgress->callback(pProgress); // now actually notify about the progress
47            }
48        }
49    
50        // private helper function to divide a progress into subprogresses
51        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
52            if (pParentProgress && pParentProgress->callback) {
53                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
54                pSubProgress->callback    = pParentProgress->callback;
55                pSubProgress->custom      = pParentProgress->custom;
56                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
57                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
58            }
59        }
60    
61    
62  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decopmression ***************
63  // *  // *
64    
65    namespace {
66    
67      inline int get12lo(const unsigned char* pSrc)      inline int get12lo(const unsigned char* pSrc)
68      {      {
69          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
# Line 52  namespace gig { namespace { Line 88  namespace gig { namespace {
88      }      }
89    
90      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
91                        int srcStep, const unsigned char* pSrc, int16_t* pDst,                        int srcStep, int dstStep,
92                          const unsigned char* pSrc, int16_t* pDst,
93                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
94                        unsigned long copysamples)                        unsigned long copysamples)
95      {      {
# Line 61  namespace gig { namespace { Line 98  namespace gig { namespace {
98                  pSrc += currentframeoffset * srcStep;                  pSrc += currentframeoffset * srcStep;
99                  while (copysamples) {                  while (copysamples) {
100                      *pDst = get16(pSrc);                      *pDst = get16(pSrc);
101                      pDst += 2;                      pDst += dstStep;
102                      pSrc += srcStep;                      pSrc += srcStep;
103                      copysamples--;                      copysamples--;
104                  }                  }
# Line 80  namespace gig { namespace { Line 117  namespace gig { namespace {
117                      dy -= int8_t(*pSrc);                      dy -= int8_t(*pSrc);
118                      y  -= dy;                      y  -= dy;
119                      *pDst = y;                      *pDst = y;
120                      pDst += 2;                      pDst += dstStep;
121                      pSrc += srcStep;                      pSrc += srcStep;
122                      copysamples--;                      copysamples--;
123                  }                  }
# Line 89  namespace gig { namespace { Line 126  namespace gig { namespace {
126      }      }
127    
128      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
129                        const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, int16_t* pDst,
130                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
131                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
132      {      {
133          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
134    
# Line 103  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 120  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 += 2          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 += 2;                      pDst += dstStep;
172                      pSrc += 3;                      pSrc += 3;
173                      copysamples--;                      copysamples--;
174                  }                  }
# Line 200  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, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
247          Instances++;          Instances++;
248            FileNo = fileNo;
249    
250          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
251          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
# Line 237  namespace gig { namespace { Line 277  namespace gig { namespace {
277    
278          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");
279    
280          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
281            Compressed        = ewav;
282            Dithered          = false;
283            TruncatedBits     = 0;
284          if (Compressed) {          if (Compressed) {
285                uint32_t version = ewav->ReadInt32();
286                if (version == 3 && BitDepth == 24) {
287                    Dithered = ewav->ReadInt32();
288                    ewav->SetPos(Channels == 2 ? 84 : 64);
289                    TruncatedBits = ewav->ReadInt32();
290                }
291              ScanCompressedSample();              ScanCompressedSample();
292          }          }
293    
294          // 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
295          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
296              pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
297              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
298          }          }
299          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
300    
301          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
302      }      }
# Line 259  namespace gig { namespace { Line 308  namespace gig { namespace {
308          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
309    
310          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
311          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
312    
313          // Scanning          // Scanning
314          pCkData->SetPos(0);          pCkData->SetPos(0);
# Line 340  namespace gig { namespace { Line 389  namespace gig { namespace {
389       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
390       * 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
391       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
392       *       * @code
393       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
394       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
395         * @endcode
396       *       *
397       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
398       * @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 438  namespace gig { namespace {
438       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
439       * 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
440       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
441       *       * @code
442       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
443       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
444       *       * @endcode
445       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
446       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
447       * 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 572  namespace gig { namespace {
572       * 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.
573       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
574       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
575       *       * @code
576       * <i>       * gig::playback_state_t playbackstate;
577       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
578       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
579       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
580       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
581       * 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
582       * 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.
583       * The method already handles such cases by itself.       * The method already handles such cases by itself.
584       *       *
585         * <b>Caution:</b> If you are using more than one streaming thread, you
586         * have to use an external decompression buffer for <b>EACH</b>
587         * streaming thread to avoid race conditions and crashes!
588         *
589       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
590       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
591       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
592       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
593         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
594       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
595         * @see                    CreateDecompressionBuffer()
596       */       */
597      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) {
598          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
599          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
600    
# Line 558  namespace gig { namespace { Line 612  namespace gig { namespace {
612                          if (!pPlaybackState->reverse) { // forward playback                          if (!pPlaybackState->reverse) { // forward playback
613                              do {                              do {
614                                  samplestoloopend  = this->LoopEnd - GetPos();                                  samplestoloopend  = this->LoopEnd - GetPos();
615                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                                  readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
616                                  samplestoread    -= readsamples;                                  samplestoread    -= readsamples;
617                                  totalreadsamples += readsamples;                                  totalreadsamples += readsamples;
618                                  if (readsamples == samplestoloopend) {                                  if (readsamples == samplestoloopend) {
# Line 584  namespace gig { namespace { Line 638  namespace gig { namespace {
638    
639                              // read samples for backward playback                              // read samples for backward playback
640                              do {                              do {
641                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
642                                  samplestoreadinloop -= readsamples;                                  samplestoreadinloop -= readsamples;
643                                  samplestoread       -= readsamples;                                  samplestoread       -= readsamples;
644                                  totalreadsamples    += readsamples;                                  totalreadsamples    += readsamples;
# Line 608  namespace gig { namespace { Line 662  namespace gig { namespace {
662                      // forward playback (not entered the loop yet)                      // forward playback (not entered the loop yet)
663                      if (!pPlaybackState->reverse) do {                      if (!pPlaybackState->reverse) do {
664                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
665                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
666                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
667                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
668                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 638  namespace gig { namespace { Line 692  namespace gig { namespace {
692                          // 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
693                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
694                          samplestoloopend     = this->LoopEnd - GetPos();                          samplestoloopend     = this->LoopEnd - GetPos();
695                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
696                          samplestoreadinloop -= readsamples;                          samplestoreadinloop -= readsamples;
697                          samplestoread       -= readsamples;                          samplestoread       -= readsamples;
698                          totalreadsamples    += readsamples;                          totalreadsamples    += readsamples;
# Line 660  namespace gig { namespace { Line 714  namespace gig { namespace {
714                          // 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
715                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
716                          samplestoloopend  = this->LoopEnd - GetPos();                          samplestoloopend  = this->LoopEnd - GetPos();
717                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
718                          samplestoread    -= readsamples;                          samplestoread    -= readsamples;
719                          totalreadsamples += readsamples;                          totalreadsamples += readsamples;
720                          if (readsamples == samplestoloopend) {                          if (readsamples == samplestoloopend) {
# Line 675  namespace gig { namespace { Line 729  namespace gig { namespace {
729    
730          // read on without looping          // read on without looping
731          if (samplestoread) do {          if (samplestoread) do {
732              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
733              samplestoread    -= readsamples;              samplestoread    -= readsamples;
734              totalreadsamples += readsamples;              totalreadsamples += readsamples;
735          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 694  namespace gig { namespace { Line 748  namespace gig { namespace {
748       * 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,
749       * thus for disk streaming.       * thus for disk streaming.
750       *       *
751         * <b>Caution:</b> If you are using more than one streaming thread, you
752         * have to use an external decompression buffer for <b>EACH</b>
753         * streaming thread to avoid race conditions and crashes!
754         *
755       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
756       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
757         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
758       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
759       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
760       */       */
761      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
762          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
763          if (!Compressed) {          if (!Compressed) {
764              if (BitDepth == 24) {              if (BitDepth == 24) {
765                  // 24 bit sample. For now just truncate to 16 bit.                  // 24 bit sample. For now just truncate to 16 bit.
766                  unsigned char* pSrc = this->pDecompressionBuffer;                  unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
767                  int16_t* pDst = static_cast<int16_t*>(pBuffer);                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
768                  if (Channels == 2) { // Stereo                  if (Channels == 2) { // Stereo
769                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
# Line 741  namespace gig { namespace { Line 800  namespace gig { namespace {
800                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
801              this->FrameOffset = 0;              this->FrameOffset = 0;
802    
803              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
804                  // local buffer reallocation - hope this won't happen  
805                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
806                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
807                  this->DecompressionBufferSize = assumedsize << 1;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
808                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
809                    remainingsamples = SampleCount;
810                    assumedsize      = GuessSize(SampleCount);
811              }              }
812    
813              unsigned char* pSrc = this->pDecompressionBuffer;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
814              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
815              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
816    
# Line 831  namespace gig { namespace { Line 893  namespace gig { namespace {
893                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
894                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
895    
896                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
897                              Decompress24(mode_r, param_r, pSrc + rightChannelOffset, pDst + 1,                                           skipsamples, copysamples, TruncatedBits);
898                                           skipsamples, copysamples);                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
899                                             skipsamples, copysamples, TruncatedBits);
900                              pDst += copysamples << 1;                              pDst += copysamples << 1;
901                          }                          }
902                          else { // Mono                          else { // Mono
903                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
904                                             skipsamples, copysamples, TruncatedBits);
905                              pDst += copysamples;                              pDst += copysamples;
906                          }                          }
907                      }                      }
# Line 850  namespace gig { namespace { Line 914  namespace gig { namespace {
914                              if (mode_r) pSrc += 4;                              if (mode_r) pSrc += 4;
915    
916                              step = (2 - mode_l) + (2 - mode_r);                              step = (2 - mode_l) + (2 - mode_r);
917                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
918                              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,
919                                           skipsamples, copysamples);                                           skipsamples, copysamples);
920                              pDst += copysamples << 1;                              pDst += copysamples << 1;
921                          }                          }
922                          else { // Mono                          else { // Mono
923                              step = 2 - mode_l;                              step = 2 - mode_l;
924                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
925                              pDst += copysamples;                              pDst += copysamples;
926                          }                          }
927                      }                      }
# Line 869  namespace gig { namespace { Line 933  namespace gig { namespace {
933                      assumedsize    = GuessSize(remainingsamples);                      assumedsize    = GuessSize(remainingsamples);
934                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
935                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
936                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                      remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
937                      pSrc = this->pDecompressionBuffer;                      pSrc = (unsigned char*) pDecompressionBuffer->pStart;
938                  }                  }
939              } // while              } // while
940    
# Line 880  namespace gig { namespace { Line 944  namespace gig { namespace {
944          }          }
945      }      }
946    
947        /**
948         * Allocates a decompression buffer for streaming (compressed) samples
949         * with Sample::Read(). If you are using more than one streaming thread
950         * in your application you <b>HAVE</b> to create a decompression buffer
951         * for <b>EACH</b> of your streaming threads and provide it with the
952         * Sample::Read() call in order to avoid race conditions and crashes.
953         *
954         * You should free the memory occupied by the allocated buffer(s) once
955         * you don't need one of your streaming threads anymore by calling
956         * DestroyDecompressionBuffer().
957         *
958         * @param MaxReadSize - the maximum size (in sample points) you ever
959         *                      expect to read with one Read() call
960         * @returns allocated decompression buffer
961         * @see DestroyDecompressionBuffer()
962         */
963        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
964            buffer_t result;
965            const double worstCaseHeaderOverhead =
966                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
967            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
968            result.pStart            = new int8_t[result.Size];
969            result.NullExtensionSize = 0;
970            return result;
971        }
972    
973        /**
974         * Free decompression buffer, previously created with
975         * CreateDecompressionBuffer().
976         *
977         * @param DecompressionBuffer - previously allocated decompression
978         *                              buffer to free
979         */
980        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
981            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
982                delete[] (int8_t*) DecompressionBuffer.pStart;
983                DecompressionBuffer.pStart = NULL;
984                DecompressionBuffer.Size   = 0;
985                DecompressionBuffer.NullExtensionSize = 0;
986            }
987        }
988    
989      Sample::~Sample() {      Sample::~Sample() {
990          Instances--;          Instances--;
991          if (!Instances && pDecompressionBuffer) {          if (!Instances && InternalDecompressionBuffer.Size) {
992              delete[] pDecompressionBuffer;              delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
993              pDecompressionBuffer = NULL;              InternalDecompressionBuffer.pStart = NULL;
994                InternalDecompressionBuffer.Size   = 0;
995          }          }
996          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
997          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
# Line 1055  namespace gig { namespace { Line 1162  namespace gig { namespace {
1162                  VCFType = vcf_type_lowpassturbo;                  VCFType = vcf_type_lowpassturbo;
1163          }          }
1164    
1165          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1166          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;                                                       VelocityResponseDepth,
1167                                                         VelocityResponseCurveScaling);
1168    
1169            curve_type_t curveType = ReleaseVelocityResponseCurve;
1170            uint8_t depth = ReleaseVelocityResponseDepth;
1171    
1172            // this models a strange behaviour or bug in GSt: two of the
1173            // velocity response curves for release time are not used even
1174            // if specified, instead another curve is chosen.
1175    
1176            if ((curveType == curve_type_nonlinear && depth == 0) ||
1177                (curveType == curve_type_special   && depth == 4)) {
1178                curveType = curve_type_nonlinear;
1179                depth = 3;
1180            }
1181            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1182    
1183            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1184        }
1185    
1186        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1187        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1188        {
1189            double* table;
1190            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1191          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1192              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1193          }          }
1194          else {          else {
1195              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1196                  CreateVelocityTable(VelocityResponseCurve,              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
                                     VelocityResponseDepth,  
                                     VelocityResponseCurveScaling);  
             (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map  
1197          }          }
1198            return table;
1199      }      }
1200    
1201      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1217  namespace gig { namespace { Line 1346  namespace gig { namespace {
1346          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1347      }      }
1348    
1349        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1350            return pVelocityReleaseTable[MIDIKeyVelocity];
1351        }
1352    
1353      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1354    
1355          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1318  namespace gig { namespace { Line 1451  namespace gig { namespace {
1451                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1452                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1453                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
1454                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
1455                                                                                                    : split_type_normal;                                                             dimension == dimension_roundrobin ||
1456                                                               dimension == dimension_random) ? split_type_bit
1457                                                                                              : split_type_normal;
1458                      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
1459                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1460                          (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 1610  namespace gig { namespace {
1610          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1611      }      }
1612    
1613      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
1614          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
1615          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1616          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1617          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
1618            Sample* sample = file->GetFirstSample(pProgress);
1619          while (sample) {          while (sample) {
1620              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
1621                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
1622              sample = file->GetNextSample();              sample = file->GetNextSample();
1623          }          }
1624          return NULL;          return NULL;
# Line 1492  namespace gig { namespace { Line 1629  namespace gig { namespace {
1629  // *************** Instrument ***************  // *************** Instrument ***************
1630  // *  // *
1631    
1632      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) {
1633          // Initialization          // Initialization
1634          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1635          RegionIndex = -1;          RegionIndex = -1;
# Line 1523  namespace gig { namespace { Line 1660  namespace gig { namespace {
1660          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1661          while (rgn) {          while (rgn) {
1662              if (rgn->GetListType() == LIST_TYPE_RGN) {              if (rgn->GetListType() == LIST_TYPE_RGN) {
1663                    __notify_progress(pProgress, (float) iRegion / (float) Regions);
1664                  pRegions[iRegion] = new Region(this, rgn);                  pRegions[iRegion] = new Region(this, rgn);
1665                  iRegion++;                  iRegion++;
1666              }              }
# Line 1535  namespace gig { namespace { Line 1673  namespace gig { namespace {
1673                  RegionKeyTable[iKey] = pRegions[iReg];                  RegionKeyTable[iKey] = pRegions[iReg];
1674              }              }
1675          }          }
1676    
1677            __notify_progress(pProgress, 1.0f); // notify done
1678      }      }
1679    
1680      Instrument::~Instrument() {      Instrument::~Instrument() {
# Line 1621  namespace gig { namespace { Line 1761  namespace gig { namespace {
1761              pInstruments->clear();              pInstruments->clear();
1762              delete pInstruments;              delete pInstruments;
1763          }          }
1764            // free extension files
1765            for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1766                delete *i;
1767      }      }
1768    
1769      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
1770          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
1771          if (!pSamples) return NULL;          if (!pSamples) return NULL;
1772          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
1773          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 1779  namespace gig { namespace {
1779          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1780      }      }
1781    
1782      void File::LoadSamples() {      void File::LoadSamples(progress_t* pProgress) {
1783          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::File* file = pRIFF;
1784          if (wvpl) {  
1785              unsigned long wvplFileOffset = wvpl->GetFilePos();          // just for progress calculation
1786              RIFF::List* wave = wvpl->GetFirstSubList();          int iSampleIndex  = 0;
1787              while (wave) {          int iTotalSamples = WavePoolCount;
1788                  if (wave->GetListType() == LIST_TYPE_WAVE) {  
1789                      if (!pSamples) pSamples = new SampleList;          // check if samples should be loaded from extension files
1790                      unsigned long waveFileOffset = wave->GetFilePos();          int lastFileNo = 0;
1791                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          for (int i = 0 ; i < WavePoolCount ; i++) {
1792                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
1793            }
1794            String name(pRIFF->Filename);
1795            int nameLen = pRIFF->Filename.length();
1796            char suffix[6];
1797            if (nameLen > 4 && pRIFF->Filename.substr(nameLen - 4) == ".gig") nameLen -= 4;
1798    
1799            for (int fileNo = 0 ; ; ) {
1800                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
1801                if (wvpl) {
1802                    unsigned long wvplFileOffset = wvpl->GetFilePos();
1803                    RIFF::List* wave = wvpl->GetFirstSubList();
1804                    while (wave) {
1805                        if (wave->GetListType() == LIST_TYPE_WAVE) {
1806                            // notify current progress
1807                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
1808                            __notify_progress(pProgress, subprogress);
1809    
1810                            if (!pSamples) pSamples = new SampleList;
1811                            unsigned long waveFileOffset = wave->GetFilePos();
1812                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
1813    
1814                            iSampleIndex++;
1815                        }
1816                        wave = wvpl->GetNextSubList();
1817                  }                  }
1818                  wave = wvpl->GetNextSubList();  
1819                    if (fileNo == lastFileNo) break;
1820    
1821                    // open extension file (*.gx01, *.gx02, ...)
1822                    fileNo++;
1823                    sprintf(suffix, ".gx%02d", fileNo);
1824                    name.replace(nameLen, 5, suffix);
1825                    file = new RIFF::File(name);
1826                    ExtensionFiles.push_back(file);
1827              }              }
1828                else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1829          }          }
1830          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
1831            __notify_progress(pProgress, 1.0); // notify done
1832      }      }
1833    
1834      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
# Line 1669  namespace gig { namespace { Line 1847  namespace gig { namespace {
1847      /**      /**
1848       * Returns the instrument with the given index.       * Returns the instrument with the given index.
1849       *       *
1850         * @param index     - number of the sought instrument (0..n)
1851         * @param pProgress - optional: callback function for progress notification
1852       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
1853       */       */
1854      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
1855          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
1856                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
1857    
1858                // sample loading subtask
1859                progress_t subprogress;
1860                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
1861                __notify_progress(&subprogress, 0.0f);
1862                GetFirstSample(&subprogress); // now force all samples to be loaded
1863                __notify_progress(&subprogress, 1.0f);
1864    
1865                // instrument loading subtask
1866                if (pProgress && pProgress->callback) {
1867                    subprogress.__range_min = subprogress.__range_max;
1868                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
1869                }
1870                __notify_progress(&subprogress, 0.0f);
1871                LoadInstruments(&subprogress);
1872                __notify_progress(&subprogress, 1.0f);
1873            }
1874          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
1875          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
1876          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
# Line 1682  namespace gig { namespace { Line 1880  namespace gig { namespace {
1880          return NULL;          return NULL;
1881      }      }
1882    
1883      void File::LoadInstruments() {      void File::LoadInstruments(progress_t* pProgress) {
1884          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1885          if (lstInstruments) {          if (lstInstruments) {
1886                int iInstrumentIndex = 0;
1887              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1888              while (lstInstr) {              while (lstInstr) {
1889                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1890                        // notify current progress
1891                        const float localProgress = (float) iInstrumentIndex / (float) Instruments;
1892                        __notify_progress(pProgress, localProgress);
1893    
1894                        // divide local progress into subprogress for loading current Instrument
1895                        progress_t subprogress;
1896                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
1897    
1898                      if (!pInstruments) pInstruments = new InstrumentList;                      if (!pInstruments) pInstruments = new InstrumentList;
1899                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
1900    
1901                        iInstrumentIndex++;
1902                  }                  }
1903                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
1904              }              }
1905                __notify_progress(pProgress, 1.0); // notify done
1906          }          }
1907          else throw gig::Exception("Mandatory <lins> list chunk not found.");          else throw gig::Exception("Mandatory <lins> list chunk not found.");
1908      }      }
# Line 1709  namespace gig { namespace { Line 1919  namespace gig { namespace {
1919          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
1920      }      }
1921    
1922    
1923    // *************** functions ***************
1924    // *
1925    
1926        /**
1927         * Returns the name of this C++ library. This is usually "libgig" of
1928         * course. This call is equivalent to RIFF::libraryName() and
1929         * DLS::libraryName().
1930         */
1931        String libraryName() {
1932            return PACKAGE;
1933        }
1934    
1935        /**
1936         * Returns version of this C++ library. This call is equivalent to
1937         * RIFF::libraryVersion() and DLS::libraryVersion().
1938         */
1939        String libraryVersion() {
1940            return VERSION;
1941        }
1942    
1943  } // namespace gig  } // namespace gig

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

  ViewVC Help
Powered by ViewVC