/[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 36 by schoenebeck, Wed Mar 10 21:34:28 2004 UTC revision 372 by persson, Fri Feb 11 18:58:07 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 by Christian Schoenebeck                           *   *   Copyright (C) 2003, 2004 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 gig { namespace {
27    
28    // *************** Internal functions for sample decopmression ***************
29    // *
30    
31        inline int get12lo(const unsigned char* pSrc)
32        {
33            const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
34            return x & 0x800 ? x - 0x1000 : x;
35        }
36    
37        inline int get12hi(const unsigned char* pSrc)
38        {
39            const int x = pSrc[1] >> 4 | pSrc[2] << 4;
40            return x & 0x800 ? x - 0x1000 : x;
41        }
42    
43        inline int16_t get16(const unsigned char* pSrc)
44        {
45            return int16_t(pSrc[0] | pSrc[1] << 8);
46        }
47    
48        inline int get24(const unsigned char* pSrc)
49        {
50            const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
51            return x & 0x800000 ? x - 0x1000000 : x;
52        }
53    
54        void Decompress16(int compressionmode, const unsigned char* params,
55                          int srcStep, int dstStep,
56                          const unsigned char* pSrc, int16_t* pDst,
57                          unsigned long currentframeoffset,
58                          unsigned long copysamples)
59        {
60            switch (compressionmode) {
61                case 0: // 16 bit uncompressed
62                    pSrc += currentframeoffset * srcStep;
63                    while (copysamples) {
64                        *pDst = get16(pSrc);
65                        pDst += dstStep;
66                        pSrc += srcStep;
67                        copysamples--;
68                    }
69                    break;
70    
71                case 1: // 16 bit compressed to 8 bit
72                    int y  = get16(params);
73                    int dy = get16(params + 2);
74                    while (currentframeoffset) {
75                        dy -= int8_t(*pSrc);
76                        y  -= dy;
77                        pSrc += srcStep;
78                        currentframeoffset--;
79                    }
80                    while (copysamples) {
81                        dy -= int8_t(*pSrc);
82                        y  -= dy;
83                        *pDst = y;
84                        pDst += dstStep;
85                        pSrc += srcStep;
86                        copysamples--;
87                    }
88                    break;
89            }
90        }
91    
92        void Decompress24(int compressionmode, const unsigned char* params,
93                          int dstStep, const unsigned char* pSrc, int16_t* pDst,
94                          unsigned long currentframeoffset,
95                          unsigned long copysamples)
96        {
97            // Note: The 24 bits are truncated to 16 bits for now.
98    
99            // Note: The calculation of the initial value of y is strange
100            // and not 100% correct. What should the first two parameters
101            // really be used for? Why are they two? The correct value for
102            // y seems to lie somewhere between the values of the first
103            // two parameters.
104            //
105            // Strange thing #2: The formula in SKIP_ONE gives values for
106            // y that are twice as high as they should be. That's why
107            // COPY_ONE shifts 9 steps instead of 8, and also why y is
108            // initialized with a sum instead of a mean value.
109    
110            int y, dy, ddy;
111    
112    #define GET_PARAMS(params)                              \
113            y = (get24(params) + get24((params) + 3));      \
114            dy  = get24((params) + 6);                      \
115            ddy = get24((params) + 9)
116    
117    #define SKIP_ONE(x)                             \
118            ddy -= (x);                             \
119            dy -= ddy;                              \
120            y -= dy
121    
122    #define COPY_ONE(x)                             \
123            SKIP_ONE(x);                            \
124            *pDst = y >> 9;                         \
125            pDst += dstStep
126    
127            switch (compressionmode) {
128                case 2: // 24 bit uncompressed
129                    pSrc += currentframeoffset * 3;
130                    while (copysamples) {
131                        *pDst = get24(pSrc) >> 8;
132                        pDst += dstStep;
133                        pSrc += 3;
134                        copysamples--;
135                    }
136                    break;
137    
138                case 3: // 24 bit compressed to 16 bit
139                    GET_PARAMS(params);
140                    while (currentframeoffset) {
141                        SKIP_ONE(get16(pSrc));
142                        pSrc += 2;
143                        currentframeoffset--;
144                    }
145                    while (copysamples) {
146                        COPY_ONE(get16(pSrc));
147                        pSrc += 2;
148                        copysamples--;
149                    }
150                    break;
151    
152                case 4: // 24 bit compressed to 12 bit
153                    GET_PARAMS(params);
154                    while (currentframeoffset > 1) {
155                        SKIP_ONE(get12lo(pSrc));
156                        SKIP_ONE(get12hi(pSrc));
157                        pSrc += 3;
158                        currentframeoffset -= 2;
159                    }
160                    if (currentframeoffset) {
161                        SKIP_ONE(get12lo(pSrc));
162                        currentframeoffset--;
163                        if (copysamples) {
164                            COPY_ONE(get12hi(pSrc));
165                            pSrc += 3;
166                            copysamples--;
167                        }
168                    }
169                    while (copysamples > 1) {
170                        COPY_ONE(get12lo(pSrc));
171                        COPY_ONE(get12hi(pSrc));
172                        pSrc += 3;
173                        copysamples -= 2;
174                    }
175                    if (copysamples) {
176                        COPY_ONE(get12lo(pSrc));
177                    }
178                    break;
179    
180                case 5: // 24 bit compressed to 8 bit
181                    GET_PARAMS(params);
182                    while (currentframeoffset) {
183                        SKIP_ONE(int8_t(*pSrc++));
184                        currentframeoffset--;
185                    }
186                    while (copysamples) {
187                        COPY_ONE(int8_t(*pSrc++));
188                        copysamples--;
189                    }
190                    break;
191            }
192        }
193    
194        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
195        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
196        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
197        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
198    }
199    
200    
201  // *************** Sample ***************  // *************** Sample ***************
202  // *  // *
203    
204      unsigned int  Sample::Instances               = 0;      unsigned int  Sample::Instances               = 0;
205      void*         Sample::pDecompressionBuffer    = NULL;      unsigned char* Sample::pDecompressionBuffer    = NULL;
206      unsigned long Sample::DecompressionBufferSize = 0;      unsigned long Sample::DecompressionBufferSize = 0;
207    
208      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) {
# Line 49  namespace gig { Line 222  namespace gig {
222          smpl->Read(&SMPTEFormat, 1, 4);          smpl->Read(&SMPTEFormat, 1, 4);
223          SMPTEOffset       = smpl->ReadInt32();          SMPTEOffset       = smpl->ReadInt32();
224          Loops             = smpl->ReadInt32();          Loops             = smpl->ReadInt32();
225          uint32_t manufByt = smpl->ReadInt32();          smpl->ReadInt32(); // manufByt
226          LoopID            = smpl->ReadInt32();          LoopID            = smpl->ReadInt32();
227          smpl->Read(&LoopType, 1, 4);          smpl->Read(&LoopType, 1, 4);
228          LoopStart         = smpl->ReadInt32();          LoopStart         = smpl->ReadInt32();
# Line 63  namespace gig { Line 236  namespace gig {
236          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
237          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
238    
239            if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
240    
241          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));
242          if (Compressed) {          if (Compressed) {
243              ScanCompressedSample();              ScanCompressedSample();
244              if (!pDecompressionBuffer) {          }
245                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];  
246                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
247              }          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {
248                pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
249                DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;
250          }          }
251          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
252    
# Line 82  namespace gig { Line 259  namespace gig {
259          this->SamplesTotal = 0;          this->SamplesTotal = 0;
260          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
261    
262            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
263            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;
264    
265          // Scanning          // Scanning
266          pCkData->SetPos(0);          pCkData->SetPos(0);
267          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
268              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
269              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
270              this->SamplesTotal += 2048;                  // stored, to save some memory
271              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
272                  case 1:   // left channel compressed  
273                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
274                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
275                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
276                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
277    
278                    if (pCkData->RemainingBytes() <= frameSize) {
279                        SamplesInLastFrame =
280                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
281                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
282                        SamplesTotal += SamplesInLastFrame;
283                      break;                      break;
284                  case 257: // both channels compressed                  }
285                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
286                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
287                }
288            }
289            else { // Mono
290                for (int i = 0 ; ; i++) {
291                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
292    
293                    const int mode = pCkData->ReadUint8();
294                    if (mode > 5) throw gig::Exception("Unknown compression mode");
295                    const unsigned long frameSize = bytesPerFrame[mode];
296    
297                    if (pCkData->RemainingBytes() <= frameSize) {
298                        SamplesInLastFrame =
299                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
300                        SamplesTotal += SamplesInLastFrame;
301                      break;                      break;
302                  default: // both channels uncompressed                  }
303                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
304                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
305              }              }
306          }          }
307          pCkData->SetPos(0);          pCkData->SetPos(0);
308    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
309          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
310          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
311          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 502  namespace gig { Line 702  namespace gig {
702       */       */
703      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
704          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
705          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?          if (!Compressed) {
706          else { //FIXME: no support for mono compressed samples yet, are there any?              if (BitDepth == 24) {
707                    // 24 bit sample. For now just truncate to 16 bit.
708                    unsigned char* pSrc = this->pDecompressionBuffer;
709                    int16_t* pDst = static_cast<int16_t*>(pBuffer);
710                    if (Channels == 2) { // Stereo
711                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
712                        pSrc++;
713                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
714                            *pDst++ = get16(pSrc);
715                            pSrc += 3;
716                        }
717                        return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
718                    }
719                    else { // Mono
720                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
721                        pSrc++;
722                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
723                            *pDst++ = get16(pSrc);
724                            pSrc += 3;
725                        }
726                        return pDst - static_cast<int16_t*>(pBuffer);
727                    }
728                }
729                else { // 16 bit
730                    // (pCkData->Read does endian correction)
731                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
732                                         : pCkData->Read(pBuffer, SampleCount, 2);
733                }
734            }
735            else {
736              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
737              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
738              // best case needed buffer size (all frames compressed)              unsigned long assumedsize      = GuessSize(SampleCount),
             unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                              (SampleCount >> 10) + // 10 bytes header per 2048 sample points  
                                              8194,                 // at least one worst case sample frame  
739                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
740                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
741                            copysamples;                            copysamples, skipsamples,
742              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
743              this->FrameOffset = 0;              this->FrameOffset = 0;
744    
745              if (assumedsize > this->DecompressionBufferSize) {              if (assumedsize > this->DecompressionBufferSize) {
746                  // local buffer reallocation - hope this won't happen                  // local buffer reallocation - hope this won't happen
747                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;
748                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size
749                  this->DecompressionBufferSize = assumedsize;                  this->DecompressionBufferSize = assumedsize << 1;
750              }              }
751    
752              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = this->pDecompressionBuffer;
753              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
             int16_t* pDst = (int16_t*) pBuffer;  
754              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
755    
756              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
757                    unsigned long framesamples = SamplesPerFrame;
758                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
759                  if (remainingbytes < 8194) {  
760                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
761                          this->SamplePos = this->SamplesTotal;  
762                          return (SampleCount - remainingsamples);                  if (Channels == 2) {
763                        mode_r = *pSrc++;
764                        framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
765                        rightChannelOffset = bytesPerFrameNoHdr[mode_l];
766                        nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
767                        if (remainingbytes < framebytes) { // last frame in sample
768                            framesamples = SamplesInLastFrame;
769                            if (mode_l == 4 && (framesamples & 1)) {
770                                rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
771                            }
772                            else {
773                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
774                            }
775                        }
776                    }
777                    else {
778                        framebytes = bytesPerFrame[mode_l] + 1;
779                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
780                        if (remainingbytes < framebytes) {
781                            framesamples = SamplesInLastFrame;
782                      }                      }
                     assumedsize    = remainingsamples;  
                     assumedsize    = (assumedsize << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)  
                                      (assumedsize >> 10) + // 10 bytes header per 2048 sample points  
                                      8194;                 // at least one worst case sample frame  
                     pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
                     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();  
                     remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);  
                     pSrc = (int8_t*) this->pDecompressionBuffer;  
783                  }                  }
784    
785                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
786                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
787                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
788                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
789                            skipsamples = currentframeoffset;
790                        }
791                        else {
792                            copysamples = 0;
793                            skipsamples = framesamples;
794                        }
795                  }                  }
796                  else {                  else {
797                        // This frame has enough data for pBuffer, but not
798                        // all of the frame is needed. Set file position
799                        // to start of this frame for next call to Read.
800                      copysamples = remainingsamples;                      copysamples = remainingsamples;
801                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
802                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
803                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
804                      }                  }
805                      else {                  remainingsamples -= copysamples;
806    
807                    if (remainingbytes > framebytes) {
808                        remainingbytes -= framebytes;
809                        if (remainingsamples == 0 &&
810                            currentframeoffset + copysamples == framesamples) {
811                            // This frame has enough data for pBuffer, and
812                            // all of the frame is needed. Set file
813                            // position to start of next frame for next
814                            // call to Read. FrameOffset is 0.
815                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
816                      }                      }
817                  }                  }
818                    else remainingbytes = 0;
819    
820                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
821                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
822                  switch (compressionmode) {                  if (copysamples == 0) {
823                      case 1: // left channel compressed                      // skip this frame
824                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
825                          if (!remainingsamples && copysamples == 2048)                  }
826                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
827                        const unsigned char* const param_l = pSrc;
828                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
829                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
830                          while (currentframeoffset) {  
831                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
832                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
833                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
834                              currentframeoffset--;  
835                          }                              Decompress24(mode_l, param_l, 2, pSrc, pDst, skipsamples, copysamples);
836                          while (copysamples) {                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
837                              dleft -= *pSrc; pSrc++;                                           skipsamples, copysamples);
838                              left  -= dleft;                              pDst += copysamples << 1;
                             *pDst = left; pDst++;  
                             *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;  
                             copysamples--;  
                         }  
                         break;  
                     case 256: // right channel compressed  
                         remainingbytes -= 6150; // (left 16 bit, right 8 bit, +6 byte header)  
                         if (!remainingsamples && copysamples == 2048)  
                             pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
   
                         right  = *(int16_t*)pSrc; pSrc+=2;  
                         dright = *(int16_t*)pSrc; pSrc+=2;  
                         if (currentframeoffset) {  
                             pSrc+=2; // skip uncompressed left channel, now we can increment by 3  
                             while (currentframeoffset) {  
                                 dright -= *pSrc;  
                                 right  -= dright;  
                                 pSrc+=3; // 8 bit right channel, skip uncompressed left channel (16 bit)  
                                 currentframeoffset--;  
                             }  
                             pSrc-=2; // back aligned to left channel  
839                          }                          }
840                          while (copysamples) {                          else { // Mono
841                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              Decompress24(mode_l, param_l, 1, pSrc, pDst, skipsamples, copysamples);
842                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = right; pDst++;  
                             copysamples--;  
843                          }                          }
844                          break;                      }
845                      case 257: // both channels compressed                      else { // 16 bit
846                          remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)                          if (mode_l) pSrc += 4;
847                          if (!remainingsamples && copysamples == 2048)  
848                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          int step;
849                            if (Channels == 2) { // Stereo
850                          left   = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
851                          dleft  = *(int16_t*)pSrc; pSrc+=2;                              if (mode_r) pSrc += 4;
852                          right  = *(int16_t*)pSrc; pSrc+=2;  
853                          dright = *(int16_t*)pSrc; pSrc+=2;                              step = (2 - mode_l) + (2 - mode_r);
854                          while (currentframeoffset) {                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
855                              dleft  -= *pSrc; pSrc++;                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
856                              left   -= dleft;                                           skipsamples, copysamples);
857                              dright -= *pSrc; pSrc++;                              pDst += copysamples << 1;
                             right  -= dright;  
                             currentframeoffset--;  
858                          }                          }
859                          while (copysamples) {                          else { // Mono
860                              dleft  -= *pSrc; pSrc++;                              step = 2 - mode_l;
861                              left   -= dleft;                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
862                              dright -= *pSrc; pSrc++;                              pDst += copysamples;
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
863                          }                          }
864                          break;                      }
865                      default: // both channels uncompressed                      pSrc += nextFrameOffset;
                         remainingbytes -= 8194; // (left 16 bit, right 16 bit, +2 byte header)  
                         if (!remainingsamples && copysamples == 2048)  
                             pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
   
                         pSrc += currentframeoffset << 2;  
                         currentframeoffset = 0;  
                         memcpy(pDst, pSrc, copysamples << 2);  
                         pDst += copysamples << 1;  
                         pSrc += copysamples << 2;  
                         break;  
866                  }                  }
867              }  
868                    // reload from disk to local buffer if needed
869                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
870                        assumedsize    = GuessSize(remainingsamples);
871                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
872                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
873                        remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);
874                        pSrc = this->pDecompressionBuffer;
875                    }
876                } // while
877    
878              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
879              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
880              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
# Line 660  namespace gig { Line 883  namespace gig {
883    
884      Sample::~Sample() {      Sample::~Sample() {
885          Instances--;          Instances--;
886          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && pDecompressionBuffer) {
887                delete[] pDecompressionBuffer;
888                pDecompressionBuffer = NULL;
889            }
890          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
891          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
892      }      }
# Line 680  namespace gig { Line 906  namespace gig {
906          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
907    
908          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
909          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
910          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
911          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
912          _3ewa->ReadInt16(); // unknown          _3ewa->ReadInt16(); // unknown
# Line 774  namespace gig { Line 1000  namespace gig {
1000          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1001          else                                       DimensionBypass = dim_bypass_ctrl_none;          else                                       DimensionBypass = dim_bypass_ctrl_none;
1002          uint8_t pan = _3ewa->ReadUint8();          uint8_t pan = _3ewa->ReadUint8();
1003          Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1004          SelfMask = _3ewa->ReadInt8() & 0x01;          SelfMask = _3ewa->ReadInt8() & 0x01;
1005          _3ewa->ReadInt8(); // unknown          _3ewa->ReadInt8(); // unknown
1006          uint8_t lfo3ctrl = _3ewa->ReadUint8();          uint8_t lfo3ctrl = _3ewa->ReadUint8();
1007          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1008          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1009          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
1010          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1011          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1012          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
# Line 829  namespace gig { Line 1051  namespace gig {
1051          VCFVelocityDynamicRange = vcfvelocity % 5;          VCFVelocityDynamicRange = vcfvelocity % 5;
1052          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1053          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1054            if (VCFType == vcf_type_lowpass) {
1055                if (lfo3ctrl & 0x40) // bit 6
1056                    VCFType = vcf_type_lowpassturbo;
1057            }
1058    
1059          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet
1060          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;
# Line 836  namespace gig { Line 1062  namespace gig {
1062              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];
1063          }          }
1064          else {          else {
1065              pVelocityAttenuationTable = new double[128];              pVelocityAttenuationTable =
1066              switch (VelocityResponseCurve) { // calculate the new table                  CreateVelocityTable(VelocityResponseCurve,
1067                  case curve_type_nonlinear:                                      VelocityResponseDepth,
1068                      for (int velocity = 0; velocity < 128; velocity++) {                                      VelocityResponseCurveScaling);
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_NONLINEAR((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                      }  
                      break;  
                 case curve_type_linear:  
                     for (int velocity = 0; velocity < 128; velocity++) {  
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_LINEAR((double)velocity,(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
                     break;  
                 case curve_type_special:  
                     for (int velocity = 0; velocity < 128; velocity++) {  
                         pVelocityAttenuationTable[velocity] =  
                             GIG_VELOCITY_TRANSFORM_SPECIAL((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);  
                         if      (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;  
                         else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;  
                     }  
                     break;  
                 case curve_type_unknown:  
                 default:  
                     throw gig::Exception("Unknown transform curve type.");  
             }  
1069              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map              (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
1070          }          }
1071      }      }
1072        
1073      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1074          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
1075          switch (EncodedController) {          switch (EncodedController) {
# Line 886  namespace gig { Line 1086  namespace gig {
1086                  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;                  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1087                  decodedcontroller.controller_number = 0;                  decodedcontroller.controller_number = 0;
1088                  break;                  break;
1089                
1090              // ordinary MIDI control change controller              // ordinary MIDI control change controller
1091              case _lev_ctrl_modwheel:              case _lev_ctrl_modwheel:
1092                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
# Line 980  namespace gig { Line 1180  namespace gig {
1180                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;                  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1181                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
1182                  break;                  break;
1183                
1184              // unknown controller type              // unknown controller type
1185              default:              default:
1186                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
# Line 1018  namespace gig { Line 1218  namespace gig {
1218          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1219      }      }
1220    
1221        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1222    
1223            // line-segment approximations of the 15 velocity curves
1224    
1225            // linear
1226            const int lin0[] = { 1, 1, 127, 127 };
1227            const int lin1[] = { 1, 21, 127, 127 };
1228            const int lin2[] = { 1, 45, 127, 127 };
1229            const int lin3[] = { 1, 74, 127, 127 };
1230            const int lin4[] = { 1, 127, 127, 127 };
1231    
1232            // non-linear
1233            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1234            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1235                                 127, 127 };
1236            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1237                                 127, 127 };
1238            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1239                                 127, 127 };
1240            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1241    
1242            // special
1243            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1244                                 113, 127, 127, 127 };
1245            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1246                                 118, 127, 127, 127 };
1247            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
1248                                 85, 90, 91, 127, 127, 127 };
1249            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
1250                                 117, 127, 127, 127 };
1251            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
1252                                 127, 127 };
1253    
1254            const int* const curves[] = { non0, non1, non2, non3, non4,
1255                                          lin0, lin1, lin2, lin3, lin4,
1256                                          spe0, spe1, spe2, spe3, spe4 };
1257    
1258            double* const table = new double[128];
1259    
1260            const int* curve = curves[curveType * 5 + depth];
1261            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
1262    
1263            table[0] = 0;
1264            for (int x = 1 ; x < 128 ; x++) {
1265    
1266                if (x > curve[2]) curve += 2;
1267                double y = curve[1] + (x - curve[0]) *
1268                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
1269                y = y / 127;
1270    
1271                // Scale up for s > 20, down for s < 20. When
1272                // down-scaling, the curve still ends at 1.0.
1273                if (s < 20 && y >= 0.5)
1274                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
1275                else
1276                    y = y * (s / 20.0);
1277                if (y > 1) y = 1;
1278    
1279                table[x] = y;
1280            }
1281            return table;
1282        }
1283    
1284    
1285  // *************** Region ***************  // *************** Region ***************
# Line 1026  namespace gig { Line 1288  namespace gig {
1288      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
1289          // Initialization          // Initialization
1290          Dimensions = 0;          Dimensions = 0;
1291          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1292              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
1293          }          }
1294            Layers = 1;
1295            File* file = (File*) GetParent()->GetParent();
1296            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
1297    
1298          // Actual Loading          // Actual Loading
1299    
# Line 1037  namespace gig { Line 1302  namespace gig {
1302          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1303          if (_3lnk) {          if (_3lnk) {
1304              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
1305              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
1306                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1307                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
1308                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
# Line 1053  namespace gig { Line 1318  namespace gig {
1318                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
1319                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1320                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1321                                                             dimension == dimension_samplechannel) ? split_type_bit                                                             dimension == dimension_samplechannel ||
1322                                                                                                   : split_type_normal;                                                             dimension == dimension_releasetrigger) ? split_type_bit
1323                                                                                                      : split_type_normal;
1324                      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
1325                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1326                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1327                                                                                     : 0;                                                                                     : 0;
1328                      Dimensions++;                      Dimensions++;
1329    
1330                        // if this is a layer dimension, remember the amount of layers
1331                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
1332                  }                  }
1333                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1334              }              }
# Line 1076  namespace gig { Line 1345  namespace gig {
1345                      else { // custom defined ranges                      else { // custom defined ranges
1346                          pDimDef->split_type = split_type_customvelocity;                          pDimDef->split_type = split_type_customvelocity;
1347                          pDimDef->ranges     = new range_t[pDimDef->zones];                          pDimDef->ranges     = new range_t[pDimDef->zones];
1348                          unsigned int bits[5] = {0,0,0,0,0};                          uint8_t bits[8] = { 0 };
1349                          int previousUpperLimit = -1;                          int previousUpperLimit = -1;
1350                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1351                              bits[i] = velocityZone;                              bits[i] = velocityZone;
1352                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
1353    
1354                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;
1355                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
# Line 1094  namespace gig { Line 1363  namespace gig {
1363                  }                  }
1364              }              }
1365    
1366                // jump to start of the wave pool indices (if not already there)
1367                File* file = (File*) GetParent()->GetParent();
1368                if (file->pVersion && file->pVersion->major == 3)
1369                    _3lnk->SetPos(68); // version 3 has a different 3lnk structure
1370                else
1371                    _3lnk->SetPos(44);
1372    
1373              // load sample references              // load sample references
             _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)  
1374              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
1375                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
1376                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
# Line 1124  namespace gig { Line 1399  namespace gig {
1399          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1400              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1401          }          }
1402          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1403              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
1404          }          }
1405      }      }
# Line 1142  namespace gig { Line 1417  namespace gig {
1417       * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,       * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
1418       * etc.).       * etc.).
1419       *       *
1420       * @param  Dim4Val  MIDI controller value (0-127) for dimension 4       * @param  DimValues  MIDI controller values (0-127) for dimension 0 to 7
      * @param  Dim3Val  MIDI controller value (0-127) for dimension 3  
      * @param  Dim2Val  MIDI controller value (0-127) for dimension 2  
      * @param  Dim1Val  MIDI controller value (0-127) for dimension 1  
      * @param  Dim0Val  MIDI controller value (0-127) for dimension 0  
1421       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
1422       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
1423       * @see             Dimensions       * @see             Dimensions
1424       */       */
1425      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
1426          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits[8] = { 0 };
1427          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1428                bits[i] = DimValues[i];
1429              switch (pDimensionDefinitions[i].split_type) {              switch (pDimensionDefinitions[i].split_type) {
1430                  case split_type_normal:                  case split_type_normal:
1431                      bits[i] /= pDimensionDefinitions[i].zone_size;                      bits[i] /= pDimensionDefinitions[i].zone_size;
# Line 1161  namespace gig { Line 1433  namespace gig {
1433                  case split_type_customvelocity:                  case split_type_customvelocity:
1434                      bits[i] = VelocityTable[bits[i]];                      bits[i] = VelocityTable[bits[i]];
1435                      break;                      break;
1436                  // else the value is already the sought dimension bit number                  case split_type_bit: // the value is already the sought dimension bit number
1437                        const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
1438                        bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
1439                        break;
1440              }              }
1441          }          }
1442          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          return GetDimensionRegionByBit(bits);
1443      }      }
1444    
1445      /**      /**
# Line 1172  namespace gig { Line 1447  namespace gig {
1447       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1448       * instead of calling this method directly!       * instead of calling this method directly!
1449       *       *
1450       * @param Dim4Bit  Bit number for dimension 4       * @param DimBits  Bit numbers for dimension 0 to 7
      * @param Dim3Bit  Bit number for dimension 3  
      * @param Dim2Bit  Bit number for dimension 2  
      * @param Dim1Bit  Bit number for dimension 1  
      * @param Dim0Bit  Bit number for dimension 0  
1451       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
1452       *                 bit numbers       *                 bit numbers
1453       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
1454       */       */
1455      DimensionRegion* Region::GetDimensionRegionByBit(uint8_t Dim4Bit, uint8_t Dim3Bit, uint8_t Dim2Bit, uint8_t Dim1Bit, uint8_t Dim0Bit) {      DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
1456          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
1457                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
1458                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
1459                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
1460                                                      << pDimensionDefinitions[2].bits | DimBits[2])
1461                                                      << pDimensionDefinitions[1].bits | DimBits[1])
1462                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
1463      }      }
1464    
1465      /**      /**
# Line 1203  namespace gig { Line 1477  namespace gig {
1477      }      }
1478    
1479      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
1480            if ((int32_t)WavePoolTableIndex == -1) return NULL;
1481          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1482          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1483          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
# Line 1244  namespace gig { Line 1519  namespace gig {
1519          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1520          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1521          pRegions = new Region*[Regions];          pRegions = new Region*[Regions];
1522            for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;
1523          RIFF::List* rgn = lrgn->GetFirstSubList();          RIFF::List* rgn = lrgn->GetFirstSubList();
1524          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1525          while (rgn) {          while (rgn) {
# Line 1267  namespace gig { Line 1543  namespace gig {
1543              if (pRegions) {              if (pRegions) {
1544                  if (pRegions[i]) delete (pRegions[i]);                  if (pRegions[i]) delete (pRegions[i]);
1545              }              }
             delete[] pRegions;  
1546          }          }
1547            if (pRegions) delete[] pRegions;
1548      }      }
1549    
1550      /**      /**
# Line 1310  namespace gig { Line 1586  namespace gig {
1586       * @see      GetFirstRegion()       * @see      GetFirstRegion()
1587       */       */
1588      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
1589          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;
1590          return pRegions[RegionIndex++];          return pRegions[RegionIndex++];
1591      }      }
1592    
# Line 1324  namespace gig { Line 1600  namespace gig {
1600          pInstruments = NULL;          pInstruments = NULL;
1601      }      }
1602    
1603        File::~File() {
1604            // free samples
1605            if (pSamples) {
1606                SamplesIterator = pSamples->begin();
1607                while (SamplesIterator != pSamples->end() ) {
1608                    delete (*SamplesIterator);
1609                    SamplesIterator++;
1610                }
1611                pSamples->clear();
1612                delete pSamples;
1613    
1614            }
1615            // free instruments
1616            if (pInstruments) {
1617                InstrumentsIterator = pInstruments->begin();
1618                while (InstrumentsIterator != pInstruments->end() ) {
1619                    delete (*InstrumentsIterator);
1620                    InstrumentsIterator++;
1621                }
1622                pInstruments->clear();
1623                delete pInstruments;
1624            }
1625        }
1626    
1627      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
1628          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples();
1629          if (!pSamples) return NULL;          if (!pSamples) return NULL;

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

  ViewVC Help
Powered by ViewVC