/[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 2 by schoenebeck, Sat Oct 25 20:15:04 2003 UTC revision 365 by persson, Thu Feb 10 19:16:31 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, const unsigned char* pSrc, int16_t* pDst,
56                          unsigned long currentframeoffset,
57                          unsigned long copysamples)
58        {
59            switch (compressionmode) {
60                case 0: // 16 bit uncompressed
61                    pSrc += currentframeoffset * srcStep;
62                    while (copysamples) {
63                        *pDst = get16(pSrc);
64                        pDst += 2;
65                        pSrc += srcStep;
66                        copysamples--;
67                    }
68                    break;
69    
70                case 1: // 16 bit compressed to 8 bit
71                    int y  = get16(params);
72                    int dy = get16(params + 2);
73                    while (currentframeoffset) {
74                        dy -= int8_t(*pSrc);
75                        y  -= dy;
76                        pSrc += srcStep;
77                        currentframeoffset--;
78                    }
79                    while (copysamples) {
80                        dy -= int8_t(*pSrc);
81                        y  -= dy;
82                        *pDst = y;
83                        pDst += 2;
84                        pSrc += srcStep;
85                        copysamples--;
86                    }
87                    break;
88            }
89        }
90    
91        void Decompress24(int compressionmode, const unsigned char* params,
92                          const unsigned char* pSrc, int16_t* pDst,
93                          unsigned long currentframeoffset,
94                          unsigned long copysamples)
95        {
96            // Note: The 24 bits are truncated to 16 bits for now.
97    
98            // Note: The calculation of the initial value of y is strange
99            // and not 100% correct. What should the first two parameters
100            // really be used for? Why are they two? The correct value for
101            // y seems to lie somewhere between the values of the first
102            // two parameters.
103            //
104            // Strange thing #2: The formula in SKIP_ONE gives values for
105            // y that are twice as high as they should be. That's why
106            // COPY_ONE shifts 9 steps instead of 8, and also why y is
107            // initialized with a sum instead of a mean value.
108    
109            int y, dy, ddy;
110    
111    #define GET_PARAMS(params)                              \
112            y = (get24(params) + get24((params) + 3));      \
113            dy  = get24((params) + 6);                      \
114            ddy = get24((params) + 9)
115    
116    #define SKIP_ONE(x)                             \
117            ddy -= (x);                             \
118            dy -= ddy;                              \
119            y -= dy
120    
121    #define COPY_ONE(x)                             \
122            SKIP_ONE(x);                            \
123            *pDst = y >> 9;                         \
124            pDst += 2
125    
126            switch (compressionmode) {
127                case 2: // 24 bit uncompressed
128                    pSrc += currentframeoffset * 3;
129                    while (copysamples) {
130                        *pDst = get24(pSrc) >> 8;
131                        pDst += 2;
132                        pSrc += 3;
133                        copysamples--;
134                    }
135                    break;
136    
137                case 3: // 24 bit compressed to 16 bit
138                    GET_PARAMS(params);
139                    while (currentframeoffset) {
140                        SKIP_ONE(get16(pSrc));
141                        pSrc += 2;
142                        currentframeoffset--;
143                    }
144                    while (copysamples) {
145                        COPY_ONE(get16(pSrc));
146                        pSrc += 2;
147                        copysamples--;
148                    }
149                    break;
150    
151                case 4: // 24 bit compressed to 12 bit
152                    GET_PARAMS(params);
153                    while (currentframeoffset > 1) {
154                        SKIP_ONE(get12lo(pSrc));
155                        SKIP_ONE(get12hi(pSrc));
156                        pSrc += 3;
157                        currentframeoffset -= 2;
158                    }
159                    if (currentframeoffset) {
160                        SKIP_ONE(get12lo(pSrc));
161                        currentframeoffset--;
162                        if (copysamples) {
163                            COPY_ONE(get12hi(pSrc));
164                            pSrc += 3;
165                            copysamples--;
166                        }
167                    }
168                    while (copysamples > 1) {
169                        COPY_ONE(get12lo(pSrc));
170                        COPY_ONE(get12hi(pSrc));
171                        pSrc += 3;
172                        copysamples -= 2;
173                    }
174                    if (copysamples) {
175                        COPY_ONE(get12lo(pSrc));
176                    }
177                    break;
178    
179                case 5: // 24 bit compressed to 8 bit
180                    GET_PARAMS(params);
181                    while (currentframeoffset) {
182                        SKIP_ONE(int8_t(*pSrc++));
183                        currentframeoffset--;
184                    }
185                    while (copysamples) {
186                        COPY_ONE(int8_t(*pSrc++));
187                        copysamples--;
188                    }
189                    break;
190            }
191        }
192    
193        const int bytesPerFrame[] =      { 4096, 2052, 768, 524, 396, 268 };
194        const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
195        const int headerSize[] =         { 0, 4, 0, 12, 12, 12 };
196        const int bitsPerSample[] =      { 16, 8, 24, 16, 12, 8 };
197    }
198    
199    
200  // *************** Sample ***************  // *************** Sample ***************
201  // *  // *
202    
203      unsigned int  Sample::Instances               = 0;      unsigned int  Sample::Instances               = 0;
204      void*         Sample::pDecompressionBuffer    = NULL;      unsigned char* Sample::pDecompressionBuffer    = NULL;
205      unsigned long Sample::DecompressionBufferSize = 0;      unsigned long Sample::DecompressionBufferSize = 0;
206    
207      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 45  namespace gig { Line 217  namespace gig {
217          Product           = smpl->ReadInt32();          Product           = smpl->ReadInt32();
218          SamplePeriod      = smpl->ReadInt32();          SamplePeriod      = smpl->ReadInt32();
219          MIDIUnityNote     = smpl->ReadInt32();          MIDIUnityNote     = smpl->ReadInt32();
220          MIDIPitchFraction = smpl->ReadInt32();          FineTune          = smpl->ReadInt32();
221          smpl->Read(&SMPTEFormat, 1, 4);          smpl->Read(&SMPTEFormat, 1, 4);
222          SMPTEOffset       = smpl->ReadInt32();          SMPTEOffset       = smpl->ReadInt32();
223          Loops             = smpl->ReadInt32();          Loops             = smpl->ReadInt32();
224            smpl->ReadInt32(); // manufByt
225          LoopID            = smpl->ReadInt32();          LoopID            = smpl->ReadInt32();
226          smpl->Read(&LoopType, 1, 4);          smpl->Read(&LoopType, 1, 4);
227          LoopStart         = smpl->ReadInt32();          LoopStart         = smpl->ReadInt32();
# Line 62  namespace gig { Line 235  namespace gig {
235          RAMCache.pStart            = NULL;          RAMCache.pStart            = NULL;
236          RAMCache.NullExtensionSize = 0;          RAMCache.NullExtensionSize = 0;
237    
238            if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
239    
240          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));
241          if (Compressed) {          if (Compressed) {
242              ScanCompressedSample();              ScanCompressedSample();
243              if (!pDecompressionBuffer) {          }
244                  pDecompressionBuffer    = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];  
245                  DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
246              }          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {
247                pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
248                DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;
249          }          }
250          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
251    
252            LoopSize = LoopEnd - LoopStart;
253      }      }
254    
255      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 79  namespace gig { Line 258  namespace gig {
258          this->SamplesTotal = 0;          this->SamplesTotal = 0;
259          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
260    
261            SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
262            WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;
263    
264          // Scanning          // Scanning
265          pCkData->SetPos(0);          pCkData->SetPos(0);
266          while (pCkData->GetState() == RIFF::stream_ready) {          if (Channels == 2) { // Stereo
267              frameOffsets.push_back(pCkData->GetPos());              for (int i = 0 ; ; i++) {
268              int16_t compressionmode = pCkData->ReadInt16();                  // for 24 bit samples every 8:th frame offset is
269              this->SamplesTotal += 2048;                  // stored, to save some memory
270              switch (compressionmode) {                  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
271                  case 1:   // left channel compressed  
272                  case 256: // right channel compressed                  const int mode_l = pCkData->ReadUint8();
273                      pCkData->SetPos(6148, RIFF::stream_curpos);                  const int mode_r = pCkData->ReadUint8();
274                    if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
275                    const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
276    
277                    if (pCkData->RemainingBytes() <= frameSize) {
278                        SamplesInLastFrame =
279                            ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
280                            (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
281                        SamplesTotal += SamplesInLastFrame;
282                      break;                      break;
283                  case 257: // both channels compressed                  }
284                      pCkData->SetPos(4104, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
285                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
286                }
287            }
288            else { // Mono
289                for (int i = 0 ; ; i++) {
290                    if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
291    
292                    const int mode = pCkData->ReadUint8();
293                    if (mode > 5) throw gig::Exception("Unknown compression mode");
294                    const unsigned long frameSize = bytesPerFrame[mode];
295    
296                    if (pCkData->RemainingBytes() <= frameSize) {
297                        SamplesInLastFrame =
298                            ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
299                        SamplesTotal += SamplesInLastFrame;
300                      break;                      break;
301                  default: // both channels uncompressed                  }
302                      pCkData->SetPos(8192, RIFF::stream_curpos);                  SamplesTotal += SamplesPerFrame;
303                    pCkData->SetPos(frameSize, RIFF::stream_curpos);
304              }              }
305          }          }
306          pCkData->SetPos(0);          pCkData->SetPos(0);
307    
         //FIXME: only seen compressed samples with 16 bit stereo so far  
         this->FrameSize = 4;  
         this->BitDepth  = 16;  
   
308          // 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)
309          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
310          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new unsigned long[frameOffsets.size()];
# Line 310  namespace gig { Line 512  namespace gig {
512      }      }
513    
514      /**      /**
515         * Reads \a SampleCount number of sample points from the position stored
516         * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
517         * the position within the sample respectively, this method honors the
518         * looping informations of the sample (if any). The sample wave stream
519         * will be decompressed on the fly if using a compressed sample. Use this
520         * method if you don't want to load the sample into RAM, thus for disk
521         * streaming. All this methods needs to know to proceed with streaming
522         * for the next time you call this method is stored in \a pPlaybackState.
523         * You have to allocate and initialize the playback_state_t structure by
524         * yourself before you use it to stream a sample:
525         *
526         * <i>
527         * gig::playback_state_t playbackstate;                           <br>
528         * playbackstate.position         = 0;                            <br>
529         * playbackstate.reverse          = false;                        <br>
530         * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>
531         * </i>
532         *
533         * You don't have to take care of things like if there is actually a loop
534         * defined or if the current read position is located within a loop area.
535         * The method already handles such cases by itself.
536         *
537         * @param pBuffer          destination buffer
538         * @param SampleCount      number of sample points to read
539         * @param pPlaybackState   will be used to store and reload the playback
540         *                         state for the next ReadAndLoop() call
541         * @returns                number of successfully read sample points
542         */
543        unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {
544            unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
545            uint8_t* pDst = (uint8_t*) pBuffer;
546    
547            SetPos(pPlaybackState->position); // recover position from the last time
548    
549            if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined
550    
551                switch (this->LoopType) {
552    
553                    case loop_type_bidirectional: { //TODO: not tested yet!
554                        do {
555                            // if not endless loop check if max. number of loop cycles have been passed
556                            if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
557    
558                            if (!pPlaybackState->reverse) { // forward playback
559                                do {
560                                    samplestoloopend  = this->LoopEnd - GetPos();
561                                    readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
562                                    samplestoread    -= readsamples;
563                                    totalreadsamples += readsamples;
564                                    if (readsamples == samplestoloopend) {
565                                        pPlaybackState->reverse = true;
566                                        break;
567                                    }
568                                } while (samplestoread && readsamples);
569                            }
570                            else { // backward playback
571    
572                                // as we can only read forward from disk, we have to
573                                // determine the end position within the loop first,
574                                // read forward from that 'end' and finally after
575                                // reading, swap all sample frames so it reflects
576                                // backward playback
577    
578                                unsigned long swapareastart       = totalreadsamples;
579                                unsigned long loopoffset          = GetPos() - this->LoopStart;
580                                unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
581                                unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
582    
583                                SetPos(reverseplaybackend);
584    
585                                // read samples for backward playback
586                                do {
587                                    readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);
588                                    samplestoreadinloop -= readsamples;
589                                    samplestoread       -= readsamples;
590                                    totalreadsamples    += readsamples;
591                                } while (samplestoreadinloop && readsamples);
592    
593                                SetPos(reverseplaybackend); // pretend we really read backwards
594    
595                                if (reverseplaybackend == this->LoopStart) {
596                                    pPlaybackState->loop_cycles_left--;
597                                    pPlaybackState->reverse = false;
598                                }
599    
600                                // reverse the sample frames for backward playback
601                                SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
602                            }
603                        } while (samplestoread && readsamples);
604                        break;
605                    }
606    
607                    case loop_type_backward: { // TODO: not tested yet!
608                        // forward playback (not entered the loop yet)
609                        if (!pPlaybackState->reverse) do {
610                            samplestoloopend  = this->LoopEnd - GetPos();
611                            readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
612                            samplestoread    -= readsamples;
613                            totalreadsamples += readsamples;
614                            if (readsamples == samplestoloopend) {
615                                pPlaybackState->reverse = true;
616                                break;
617                            }
618                        } while (samplestoread && readsamples);
619    
620                        if (!samplestoread) break;
621    
622                        // as we can only read forward from disk, we have to
623                        // determine the end position within the loop first,
624                        // read forward from that 'end' and finally after
625                        // reading, swap all sample frames so it reflects
626                        // backward playback
627    
628                        unsigned long swapareastart       = totalreadsamples;
629                        unsigned long loopoffset          = GetPos() - this->LoopStart;
630                        unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)
631                                                                                  : samplestoread;
632                        unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);
633    
634                        SetPos(reverseplaybackend);
635    
636                        // read samples for backward playback
637                        do {
638                            // if not endless loop check if max. number of loop cycles have been passed
639                            if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
640                            samplestoloopend     = this->LoopEnd - GetPos();
641                            readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));
642                            samplestoreadinloop -= readsamples;
643                            samplestoread       -= readsamples;
644                            totalreadsamples    += readsamples;
645                            if (readsamples == samplestoloopend) {
646                                pPlaybackState->loop_cycles_left--;
647                                SetPos(this->LoopStart);
648                            }
649                        } while (samplestoreadinloop && readsamples);
650    
651                        SetPos(reverseplaybackend); // pretend we really read backwards
652    
653                        // reverse the sample frames for backward playback
654                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
655                        break;
656                    }
657    
658                    default: case loop_type_normal: {
659                        do {
660                            // if not endless loop check if max. number of loop cycles have been passed
661                            if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
662                            samplestoloopend  = this->LoopEnd - GetPos();
663                            readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
664                            samplestoread    -= readsamples;
665                            totalreadsamples += readsamples;
666                            if (readsamples == samplestoloopend) {
667                                pPlaybackState->loop_cycles_left--;
668                                SetPos(this->LoopStart);
669                            }
670                        } while (samplestoread && readsamples);
671                        break;
672                    }
673                }
674            }
675    
676            // read on without looping
677            if (samplestoread) do {
678                readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);
679                samplestoread    -= readsamples;
680                totalreadsamples += readsamples;
681            } while (readsamples && samplestoread);
682    
683            // store current position
684            pPlaybackState->position = GetPos();
685    
686            return totalreadsamples;
687        }
688    
689        /**
690       * Reads \a SampleCount number of sample points from the current       * Reads \a SampleCount number of sample points from the current
691       * position into the buffer pointed by \a pBuffer and increments the       * position into the buffer pointed by \a pBuffer and increments the
692       * position within the sample. The sample wave stream will be       * position within the sample. The sample wave stream will be
# Line 323  namespace gig { Line 700  namespace gig {
700       * @see                SetPos()       * @see                SetPos()
701       */       */
702      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
703          if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize);          if (SampleCount == 0) return 0;
704          else { //FIXME: no support for mono compressed samples yet, are there any?          if (!Compressed) {
705              //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate              if (BitDepth == 24) {
706              // best case needed buffer size (all frames compressed)                  // 24 bit sample. For now just truncate to 16 bit.
707              unsigned long assumedsize      = (SampleCount << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)                  unsigned char* pSrc = this->pDecompressionBuffer;
708                                               (SampleCount >> 10) + // 10 bytes header per 2048 sample points                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
709                                               8194,                 // at least one worst case sample frame                  if (Channels == 2) { // Stereo
710                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
711                        pSrc++;
712                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
713                            *pDst++ = get16(pSrc);
714                            pSrc += 3;
715                        }
716                        return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
717                    }
718                    else { // Mono
719                        unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
720                        pSrc++;
721                        for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
722                            *pDst++ = get16(pSrc);
723                            pSrc += 3;
724                        }
725                        return pDst - static_cast<int16_t*>(pBuffer);
726                    }
727                }
728                else { // 16 bit
729                    // (pCkData->Read does endian correction)
730                    return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
731                                         : pCkData->Read(pBuffer, SampleCount, 2);
732                }
733            }
734            else {
735                if (this->SamplePos >= this->SamplesTotal) return 0;
736                //TODO: efficiency: maybe we should test for an average compression rate
737                unsigned long assumedsize      = GuessSize(SampleCount),
738                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
739                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
740                            copysamples;                            copysamples, skipsamples,
741              int currentframeoffset = this->FrameOffset;   // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
742              this->FrameOffset = 0;              this->FrameOffset = 0;
743    
744              if (assumedsize > this->DecompressionBufferSize) {              if (assumedsize > this->DecompressionBufferSize) {
745                  // local buffer reallocation - hope this won't happen                  // local buffer reallocation - hope this won't happen
746                  if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;
747                  this->pDecompressionBuffer    = new int8_t[assumedsize << 1]; // double of current needed size                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size
748                  this->DecompressionBufferSize = assumedsize;                  this->DecompressionBufferSize = assumedsize << 1;
749              }              }
750    
751              int16_t  compressionmode, left, dleft, right, dright;              unsigned char* pSrc = this->pDecompressionBuffer;
752              int8_t*  pSrc = (int8_t*)  this->pDecompressionBuffer;              int16_t* pDst = static_cast<int16_t*>(pBuffer);
             int16_t* pDst = (int16_t*) pBuffer;  
753              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
754    
755              while (remainingsamples) {              while (remainingsamples && remainingbytes) {
756                    unsigned long framesamples = SamplesPerFrame;
757                  // reload from disk to local buffer if needed                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
758                  if (remainingbytes < 8194) {  
759                      if (pCkData->GetState() != RIFF::stream_ready) {                  int mode_l = *pSrc++, mode_r = 0;
760                          this->SamplePos += (SampleCount - remainingsamples);  
761                          //if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;                  if (Channels == 2) {
762                          return (SampleCount - remainingsamples);                      mode_r = *pSrc++;
763                      }                      framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
764                      assumedsize    = remainingsamples;                      rightChannelOffset = bytesPerFrameNoHdr[mode_l];
765                      assumedsize    = (assumedsize << 1)  + // *2 (16 Bit, stereo, but assume all frames compressed)                      nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
766                                       (assumedsize >> 10) + // 10 bytes header per 2048 sample points                      if (remainingbytes < framebytes) { // last frame in sample
767                                       8194;                 // at least one worst case sample frame                          framesamples = SamplesInLastFrame;
768                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          if (mode_l == 4 && (framesamples & 1)) {
769                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                              rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
770                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                          }
771                      pSrc = (int8_t*) this->pDecompressionBuffer;                          else {
772                                rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
773                            }
774                        }
775                    }
776                    else {
777                        framebytes = bytesPerFrame[mode_l] + 1;
778                        nextFrameOffset = bytesPerFrameNoHdr[mode_l];
779                        if (remainingbytes < framebytes) {
780                            framesamples = SamplesInLastFrame;
781                        }
782                  }                  }
783    
784                  // determine how many samples in this frame to skip and read                  // determine how many samples in this frame to skip and read
785                  if (remainingsamples >= 2048) {                  if (currentframeoffset + remainingsamples >= framesamples) {
786                      copysamples       = 2048 - currentframeoffset;                      if (currentframeoffset <= framesamples) {
787                      remainingsamples -= copysamples;                          copysamples = framesamples - currentframeoffset;
788                            skipsamples = currentframeoffset;
789                        }
790                        else {
791                            copysamples = 0;
792                            skipsamples = framesamples;
793                        }
794                  }                  }
795                  else {                  else {
796                        // This frame has enough data for pBuffer, but not
797                        // all of the frame is needed. Set file position
798                        // to start of this frame for next call to Read.
799                      copysamples = remainingsamples;                      copysamples = remainingsamples;
800                      if (currentframeoffset + copysamples > 2048) {                      skipsamples = currentframeoffset;
801                          copysamples = 2048 - currentframeoffset;                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
802                          remainingsamples -= copysamples;                      this->FrameOffset = currentframeoffset + copysamples;
803                      }                  }
804                      else {                  remainingsamples -= copysamples;
805    
806                    if (remainingbytes > framebytes) {
807                        remainingbytes -= framebytes;
808                        if (remainingsamples == 0 &&
809                            currentframeoffset + copysamples == framesamples) {
810                            // This frame has enough data for pBuffer, and
811                            // all of the frame is needed. Set file
812                            // position to start of next frame for next
813                            // call to Read. FrameOffset is 0.
814                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);                          pCkData->SetPos(remainingbytes, RIFF::stream_backward);
                         remainingsamples = 0;  
                         this->FrameOffset = currentframeoffset + copysamples;  
815                      }                      }
816                  }                  }
817                    else remainingbytes = 0;
818    
819                  // decompress and copy current frame from local buffer to destination buffer                  currentframeoffset -= skipsamples;
820                  compressionmode = *(int16_t*)pSrc; pSrc+=2;  
821                  switch (compressionmode) {                  if (copysamples == 0) {
822                      case 1: // left channel compressed                      // skip this frame
823                          remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)                      pSrc += framebytes - Channels;
824                          if (!remainingsamples && copysamples == 2048)                  }
825                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);                  else {
826                        const unsigned char* const param_l = pSrc;
827                          left  = *(int16_t*)pSrc; pSrc+=2;                      if (BitDepth == 24) {
828                          dleft = *(int16_t*)pSrc; pSrc+=2;                          if (mode_l != 2) pSrc += 12;
829                          while (currentframeoffset) {  
830                              dleft -= *pSrc;                          if (Channels == 2) { // Stereo
831                              left  -= dleft;                              const unsigned char* const param_r = pSrc;
832                              pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)                              if (mode_r != 2) pSrc += 12;
833                              currentframeoffset--;  
834                          }                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);
835                          while (copysamples) {                              Decompress24(mode_r, param_r, pSrc + rightChannelOffset, pDst + 1,
836                              dleft -= *pSrc; pSrc++;                                           skipsamples, copysamples);
837                              left  -= dleft;                              pDst += copysamples << 1;
838                              *pDst = left; pDst++;                          }
839                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                          else { // Mono
840                              copysamples--;                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);
841                          }                              pDst += copysamples;
842                          break;                          }
843                      case 256: // right channel compressed                      }
844                          remainingbytes -= 6150; // (left 16 bit, right 8 bit, +6 byte header)                      else { // 16 bit
845                          if (!remainingsamples && copysamples == 2048)                          if (mode_l) pSrc += 4;
846                              pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
847                            int step;
848                          right  = *(int16_t*)pSrc; pSrc+=2;                          if (Channels == 2) { // Stereo
849                          dright = *(int16_t*)pSrc; pSrc+=2;                              const unsigned char* const param_r = pSrc;
850                          if (currentframeoffset) {                              if (mode_r) pSrc += 4;
851                              pSrc+=2; // skip uncompressed left channel, now we can increment by 3  
852                              while (currentframeoffset) {                              step = (2 - mode_l) + (2 - mode_r);
853                                  dright -= *pSrc;                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);
854                                  right  -= dright;                              Decompress16(mode_r, param_r, step, pSrc + (2 - mode_l), pDst + 1,
855                                  pSrc+=3; // 8 bit right channel, skip uncompressed left channel (16 bit)                                           skipsamples, copysamples);
856                                  currentframeoffset--;                              pDst += copysamples << 1;
                             }  
                             pSrc-=2; // back aligned to left channel  
857                          }                          }
858                          while (copysamples) {                          else { // Mono
859                              *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;                              step = 2 - mode_l;
860                              dright -= *pSrc; pSrc++;                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);
861                              right  -= dright;                              pDst += copysamples;
862                              *pDst = right; pDst++;                          }
863                              copysamples--;                      }
864                          }                      pSrc += nextFrameOffset;
                         break;  
                     case 257: // both channels compressed  
                         remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)  
                         if (!remainingsamples && copysamples == 2048)  
                             pCkData->SetPos(remainingbytes, RIFF::stream_backward);  
   
                         left   = *(int16_t*)pSrc; pSrc+=2;  
                         dleft  = *(int16_t*)pSrc; pSrc+=2;  
                         right  = *(int16_t*)pSrc; pSrc+=2;  
                         dright = *(int16_t*)pSrc; pSrc+=2;  
                         while (currentframeoffset) {  
                             dleft  -= *pSrc; pSrc++;  
                             left   -= dleft;  
                             dright -= *pSrc; pSrc++;  
                             right  -= dright;  
                             currentframeoffset--;  
                         }  
                         while (copysamples) {  
                             dleft  -= *pSrc; pSrc++;  
                             left   -= dleft;  
                             dright -= *pSrc; pSrc++;  
                             right  -= dright;  
                             *pDst = left;  pDst++;  
                             *pDst = right; pDst++;  
                             copysamples--;  
                         }  
                         break;  
                     default: // both channels uncompressed  
                         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;  
865                  }                  }
866              }  
867                    // reload from disk to local buffer if needed
868                    if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
869                        assumedsize    = GuessSize(remainingsamples);
870                        pCkData->SetPos(remainingbytes, RIFF::stream_backward);
871                        if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
872                        remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);
873                        pSrc = this->pDecompressionBuffer;
874                    }
875                } // while
876    
877              this->SamplePos += (SampleCount - remainingsamples);              this->SamplePos += (SampleCount - remainingsamples);
878              //if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
879              return (SampleCount - remainingsamples);              return (SampleCount - remainingsamples);
880          }          }
881      }      }
882    
883      Sample::~Sample() {      Sample::~Sample() {
884          Instances--;          Instances--;
885          if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;          if (!Instances && pDecompressionBuffer) {
886                delete[] pDecompressionBuffer;
887                pDecompressionBuffer = NULL;
888            }
889          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
890          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
891      }      }
# Line 491  namespace gig { Line 895  namespace gig {
895  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
896  // *  // *
897    
898        uint                               DimensionRegion::Instances       = 0;
899        DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
900    
901      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
902            Instances++;
903    
904          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
905            if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
906    
907          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
908          _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
909          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
910          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
911          _3ewa->ReadInt16(); // unknown          _3ewa->ReadInt16(); // unknown
# Line 511  namespace gig { Line 921  namespace gig {
921          _3ewa->ReadInt16(); // unknown          _3ewa->ReadInt16(); // unknown
922          EG1Sustain          = _3ewa->ReadUint16();          EG1Sustain          = _3ewa->ReadUint16();
923          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
924          EG1Controller       = static_cast<eg1_ctrl_t>(_3ewa->ReadUint8());          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
925          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
926          EG1ControllerInvert           = eg1ctrloptions & 0x01;          EG1ControllerInvert           = eg1ctrloptions & 0x01;
927          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
928          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
929          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
930          EG2Controller       = static_cast<eg2_ctrl_t>(_3ewa->ReadUint8());          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
931          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
932          EG2ControllerInvert           = eg2ctrloptions & 0x01;          EG2ControllerInvert           = eg2ctrloptions & 0x01;
933          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
# Line 579  namespace gig { Line 989  namespace gig {
989              ReleaseVelocityResponseDepth = 0;              ReleaseVelocityResponseDepth = 0;
990          }          }
991          VelocityResponseCurveScaling = _3ewa->ReadUint8();          VelocityResponseCurveScaling = _3ewa->ReadUint8();
992          AttenuationControlTreshold   = _3ewa->ReadInt8();          AttenuationControllerThreshold = _3ewa->ReadInt8();
993          _3ewa->ReadInt32(); // unknown          _3ewa->ReadInt32(); // unknown
994          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
995          _3ewa->ReadInt16(); // unknown          _3ewa->ReadInt16(); // unknown
# Line 589  namespace gig { Line 999  namespace gig {
999          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1000          else                                       DimensionBypass = dim_bypass_ctrl_none;          else                                       DimensionBypass = dim_bypass_ctrl_none;
1001          uint8_t pan = _3ewa->ReadUint8();          uint8_t pan = _3ewa->ReadUint8();
1002          Pan         = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1003          SelfMask = _3ewa->ReadInt8() & 0x01;          SelfMask = _3ewa->ReadInt8() & 0x01;
1004          _3ewa->ReadInt8(); // unknown          _3ewa->ReadInt8(); // unknown
1005          uint8_t lfo3ctrl = _3ewa->ReadUint8();          uint8_t lfo3ctrl = _3ewa->ReadUint8();
1006          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1007          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1008          InvertAttenuationControl = lfo3ctrl & 0x80; // bit 7          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1009          if (VCFType == vcf_type_lowpass) {          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
         }  
         AttenuationControl = static_cast<attenuation_ctrl_t>(_3ewa->ReadUint8());  
1010          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1011          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1012          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
# Line 644  namespace gig { Line 1050  namespace gig {
1050          VCFVelocityDynamicRange = vcfvelocity % 5;          VCFVelocityDynamicRange = vcfvelocity % 5;
1051          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1052          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1053            if (VCFType == vcf_type_lowpass) {
1054                if (lfo3ctrl & 0x40) // bit 6
1055                    VCFType = vcf_type_lowpassturbo;
1056            }
1057    
1058            // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet
1059            uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;
1060            if (pVelocityTables->count(tableKey)) { // if key exists
1061                pVelocityAttenuationTable = (*pVelocityTables)[tableKey];
1062            }
1063            else {
1064                pVelocityAttenuationTable =
1065                    CreateVelocityTable(VelocityResponseCurve,
1066                                        VelocityResponseDepth,
1067                                        VelocityResponseCurveScaling);
1068                (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
1069            }
1070        }
1071    
1072        leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1073            leverage_ctrl_t decodedcontroller;
1074            switch (EncodedController) {
1075                // special controller
1076                case _lev_ctrl_none:
1077                    decodedcontroller.type = leverage_ctrl_t::type_none;
1078                    decodedcontroller.controller_number = 0;
1079                    break;
1080                case _lev_ctrl_velocity:
1081                    decodedcontroller.type = leverage_ctrl_t::type_velocity;
1082                    decodedcontroller.controller_number = 0;
1083                    break;
1084                case _lev_ctrl_channelaftertouch:
1085                    decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1086                    decodedcontroller.controller_number = 0;
1087                    break;
1088    
1089                // ordinary MIDI control change controller
1090                case _lev_ctrl_modwheel:
1091                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1092                    decodedcontroller.controller_number = 1;
1093                    break;
1094                case _lev_ctrl_breath:
1095                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1096                    decodedcontroller.controller_number = 2;
1097                    break;
1098                case _lev_ctrl_foot:
1099                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1100                    decodedcontroller.controller_number = 4;
1101                    break;
1102                case _lev_ctrl_effect1:
1103                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1104                    decodedcontroller.controller_number = 12;
1105                    break;
1106                case _lev_ctrl_effect2:
1107                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1108                    decodedcontroller.controller_number = 13;
1109                    break;
1110                case _lev_ctrl_genpurpose1:
1111                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1112                    decodedcontroller.controller_number = 16;
1113                    break;
1114                case _lev_ctrl_genpurpose2:
1115                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1116                    decodedcontroller.controller_number = 17;
1117                    break;
1118                case _lev_ctrl_genpurpose3:
1119                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1120                    decodedcontroller.controller_number = 18;
1121                    break;
1122                case _lev_ctrl_genpurpose4:
1123                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1124                    decodedcontroller.controller_number = 19;
1125                    break;
1126                case _lev_ctrl_portamentotime:
1127                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1128                    decodedcontroller.controller_number = 5;
1129                    break;
1130                case _lev_ctrl_sustainpedal:
1131                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1132                    decodedcontroller.controller_number = 64;
1133                    break;
1134                case _lev_ctrl_portamento:
1135                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1136                    decodedcontroller.controller_number = 65;
1137                    break;
1138                case _lev_ctrl_sostenutopedal:
1139                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1140                    decodedcontroller.controller_number = 66;
1141                    break;
1142                case _lev_ctrl_softpedal:
1143                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1144                    decodedcontroller.controller_number = 67;
1145                    break;
1146                case _lev_ctrl_genpurpose5:
1147                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1148                    decodedcontroller.controller_number = 80;
1149                    break;
1150                case _lev_ctrl_genpurpose6:
1151                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1152                    decodedcontroller.controller_number = 81;
1153                    break;
1154                case _lev_ctrl_genpurpose7:
1155                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1156                    decodedcontroller.controller_number = 82;
1157                    break;
1158                case _lev_ctrl_genpurpose8:
1159                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1160                    decodedcontroller.controller_number = 83;
1161                    break;
1162                case _lev_ctrl_effect1depth:
1163                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1164                    decodedcontroller.controller_number = 91;
1165                    break;
1166                case _lev_ctrl_effect2depth:
1167                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1168                    decodedcontroller.controller_number = 92;
1169                    break;
1170                case _lev_ctrl_effect3depth:
1171                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1172                    decodedcontroller.controller_number = 93;
1173                    break;
1174                case _lev_ctrl_effect4depth:
1175                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1176                    decodedcontroller.controller_number = 94;
1177                    break;
1178                case _lev_ctrl_effect5depth:
1179                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1180                    decodedcontroller.controller_number = 95;
1181                    break;
1182    
1183                // unknown controller type
1184                default:
1185                    throw gig::Exception("Unknown leverage controller type.");
1186            }
1187            return decodedcontroller;
1188        }
1189    
1190        DimensionRegion::~DimensionRegion() {
1191            Instances--;
1192            if (!Instances) {
1193                // delete the velocity->volume tables
1194                VelocityTableMap::iterator iter;
1195                for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
1196                    double* pTable = iter->second;
1197                    if (pTable) delete[] pTable;
1198                }
1199                pVelocityTables->clear();
1200                delete pVelocityTables;
1201                pVelocityTables = NULL;
1202            }
1203      }      }
1204    
1205        /**
1206         * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1207         * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1208         * and VelocityResponseCurveScaling) involved are taken into account to
1209         * calculate the amplitude factor. Use this method when a key was
1210         * triggered to get the volume with which the sample should be played
1211         * back.
1212         *
1213         * @param MIDIKeyVelocity  MIDI velocity value of the triggered key (between 0 and 127)
1214         * @returns                amplitude factor (between 0.0 and 1.0)
1215         */
1216        double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1217            return pVelocityAttenuationTable[MIDIKeyVelocity];
1218        }
1219    
1220        double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1221    
1222            // line-segment approximations of the 15 velocity curves
1223    
1224            // linear
1225            const int lin0[] = { 1, 1, 127, 127 };
1226            const int lin1[] = { 1, 21, 127, 127 };
1227            const int lin2[] = { 1, 45, 127, 127 };
1228            const int lin3[] = { 1, 74, 127, 127 };
1229            const int lin4[] = { 1, 127, 127, 127 };
1230    
1231            // non-linear
1232            const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1233            const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1234                                 127, 127 };
1235            const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1236                                 127, 127 };
1237            const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1238                                 127, 127 };
1239            const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1240    
1241            // special
1242            const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1243                                 113, 127, 127, 127 };
1244            const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1245                                 118, 127, 127, 127 };
1246            const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
1247                                 85, 90, 91, 127, 127, 127 };
1248            const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
1249                                 117, 127, 127, 127 };
1250            const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
1251                                 127, 127 };
1252    
1253            const int* const curves[] = { non0, non1, non2, non3, non4,
1254                                          lin0, lin1, lin2, lin3, lin4,
1255                                          spe0, spe1, spe2, spe3, spe4 };
1256    
1257            double* const table = new double[128];
1258    
1259            const int* curve = curves[curveType * 5 + depth];
1260            const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
1261    
1262            table[0] = 0;
1263            for (int x = 1 ; x < 128 ; x++) {
1264    
1265                if (x > curve[2]) curve += 2;
1266                double y = curve[1] + (x - curve[0]) *
1267                    (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
1268                y = y / 127;
1269    
1270                // Scale up for s > 20, down for s < 20. When
1271                // down-scaling, the curve still ends at 1.0.
1272                if (s < 20 && y >= 0.5)
1273                    y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
1274                else
1275                    y = y * (s / 20.0);
1276                if (y > 1) y = 1;
1277    
1278                table[x] = y;
1279            }
1280            return table;
1281        }
1282    
1283    
1284  // *************** Region ***************  // *************** Region ***************
# Line 654  namespace gig { Line 1287  namespace gig {
1287      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) {
1288          // Initialization          // Initialization
1289          Dimensions = 0;          Dimensions = 0;
1290          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1291              pDimensionRegions[i] = NULL;              pDimensionRegions[i] = NULL;
1292          }          }
1293            Layers = 1;
1294            File* file = (File*) GetParent()->GetParent();
1295            int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
1296    
1297          // Actual Loading          // Actual Loading
1298    
# Line 665  namespace gig { Line 1301  namespace gig {
1301          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1302          if (_3lnk) {          if (_3lnk) {
1303              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
1304              for (int i = 0; i < 5; i++) {              for (int i = 0; i < dimensionBits; i++) {
1305                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1306                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
1307                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
# Line 681  namespace gig { Line 1317  namespace gig {
1317                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
1318                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)
1319                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1320                                                             dimension == dimension_samplechannel) ? split_type_bit                                                             dimension == dimension_samplechannel ||
1321                                                                                                   : split_type_normal;                                                             dimension == dimension_releasetrigger) ? split_type_bit
1322                                                                                                      : split_type_normal;
1323                      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
1324                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
1325                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1326                                                                                     : 0;                                                                                     : 0;
1327                      Dimensions++;                      Dimensions++;
1328    
1329                        // if this is a layer dimension, remember the amount of layers
1330                        if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
1331                  }                  }
1332                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1333              }              }
# Line 704  namespace gig { Line 1344  namespace gig {
1344                      else { // custom defined ranges                      else { // custom defined ranges
1345                          pDimDef->split_type = split_type_customvelocity;                          pDimDef->split_type = split_type_customvelocity;
1346                          pDimDef->ranges     = new range_t[pDimDef->zones];                          pDimDef->ranges     = new range_t[pDimDef->zones];
1347                          unsigned int bits[5] = {0,0,0,0,0};                          uint8_t bits[8] = { 0 };
1348                          int previousUpperLimit = -1;                          int previousUpperLimit = -1;
1349                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {                          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1350                              bits[i] = velocityZone;                              bits[i] = velocityZone;
1351                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);                              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
1352    
1353                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;
1354                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
# Line 722  namespace gig { Line 1362  namespace gig {
1362                  }                  }
1363              }              }
1364    
1365                // jump to start of the wave pool indices (if not already there)
1366                File* file = (File*) GetParent()->GetParent();
1367                if (file->pVersion && file->pVersion->major == 3)
1368                    _3lnk->SetPos(68); // version 3 has a different 3lnk structure
1369                else
1370                    _3lnk->SetPos(44);
1371    
1372              // load sample references              // load sample references
             _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)  
1373              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
1374                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
1375                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
# Line 752  namespace gig { Line 1398  namespace gig {
1398          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1399              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1400          }          }
1401          for (int i = 0; i < 32; i++) {          for (int i = 0; i < 256; i++) {
1402              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
1403          }          }
1404      }      }
# Line 770  namespace gig { Line 1416  namespace gig {
1416       * 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,
1417       * etc.).       * etc.).
1418       *       *
1419       * @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  
1420       * @returns         adress to the DimensionRegion for the given situation       * @returns         adress to the DimensionRegion for the given situation
1421       * @see             pDimensionDefinitions       * @see             pDimensionDefinitions
1422       * @see             Dimensions       * @see             Dimensions
1423       */       */
1424      DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
1425          unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};          uint8_t bits[8] = { 0 };
1426          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
1427                bits[i] = DimValues[i];
1428              switch (pDimensionDefinitions[i].split_type) {              switch (pDimensionDefinitions[i].split_type) {
1429                  case split_type_normal:                  case split_type_normal:
1430                      bits[i] /= pDimensionDefinitions[i].zone_size;                      bits[i] /= pDimensionDefinitions[i].zone_size;
# Line 789  namespace gig { Line 1432  namespace gig {
1432                  case split_type_customvelocity:                  case split_type_customvelocity:
1433                      bits[i] = VelocityTable[bits[i]];                      bits[i] = VelocityTable[bits[i]];
1434                      break;                      break;
1435                  // else the value is already the sought dimension bit number                  case split_type_bit: // the value is already the sought dimension bit number
1436                        const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
1437                        bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
1438                        break;
1439              }              }
1440          }          }
1441          return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);          return GetDimensionRegionByBit(bits);
1442      }      }
1443    
1444      /**      /**
# Line 800  namespace gig { Line 1446  namespace gig {
1446       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1447       * instead of calling this method directly!       * instead of calling this method directly!
1448       *       *
1449       * @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  
1450       * @returns        adress to the DimensionRegion for the given dimension       * @returns        adress to the DimensionRegion for the given dimension
1451       *                 bit numbers       *                 bit numbers
1452       * @see            GetDimensionRegionByValue()       * @see            GetDimensionRegionByValue()
1453       */       */
1454      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]) {
1455          return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)          return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
1456                                                       << pDimensionDefinitions[2].bits) | Dim2Bit)                                                    << pDimensionDefinitions[5].bits | DimBits[5])
1457                                                       << pDimensionDefinitions[1].bits) | Dim1Bit)                                                    << pDimensionDefinitions[4].bits | DimBits[4])
1458                                                       << pDimensionDefinitions[0].bits) | Dim0Bit) );                                                    << pDimensionDefinitions[3].bits | DimBits[3])
1459                                                      << pDimensionDefinitions[2].bits | DimBits[2])
1460                                                      << pDimensionDefinitions[1].bits | DimBits[1])
1461                                                      << pDimensionDefinitions[0].bits | DimBits[0]];
1462      }      }
1463    
1464      /**      /**
# Line 831  namespace gig { Line 1476  namespace gig {
1476      }      }
1477    
1478      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
1479            if ((int32_t)WavePoolTableIndex == -1) return NULL;
1480          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1481          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1482          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
# Line 872  namespace gig { Line 1518  namespace gig {
1518          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1519          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1520          pRegions = new Region*[Regions];          pRegions = new Region*[Regions];
1521            for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;
1522          RIFF::List* rgn = lrgn->GetFirstSubList();          RIFF::List* rgn = lrgn->GetFirstSubList();
1523          unsigned int iRegion = 0;          unsigned int iRegion = 0;
1524          while (rgn) {          while (rgn) {
# Line 895  namespace gig { Line 1542  namespace gig {
1542              if (pRegions) {              if (pRegions) {
1543                  if (pRegions[i]) delete (pRegions[i]);                  if (pRegions[i]) delete (pRegions[i]);
1544              }              }
             delete[] pRegions;  
1545          }          }
1546            if (pRegions) delete[] pRegions;
1547      }      }
1548    
1549      /**      /**
# Line 938  namespace gig { Line 1585  namespace gig {
1585       * @see      GetFirstRegion()       * @see      GetFirstRegion()
1586       */       */
1587      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
1588          if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;
1589          return pRegions[RegionIndex++];          return pRegions[RegionIndex++];
1590      }      }
1591    
# Line 952  namespace gig { Line 1599  namespace gig {
1599          pInstruments = NULL;          pInstruments = NULL;
1600      }      }
1601    
1602        File::~File() {
1603            // free samples
1604            if (pSamples) {
1605                SamplesIterator = pSamples->begin();
1606                while (SamplesIterator != pSamples->end() ) {
1607                    delete (*SamplesIterator);
1608                    SamplesIterator++;
1609                }
1610                pSamples->clear();
1611                delete pSamples;
1612    
1613            }
1614            // free instruments
1615            if (pInstruments) {
1616                InstrumentsIterator = pInstruments->begin();
1617                while (InstrumentsIterator != pInstruments->end() ) {
1618                    delete (*InstrumentsIterator);
1619                    InstrumentsIterator++;
1620                }
1621                pInstruments->clear();
1622                delete pInstruments;
1623            }
1624        }
1625    
1626      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
1627          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples();
1628          if (!pSamples) return NULL;          if (!pSamples) return NULL;
# Line 995  namespace gig { Line 1666  namespace gig {
1666          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1667      }      }
1668    
1669        /**
1670         * Returns the instrument with the given index.
1671         *
1672         * @returns  sought instrument or NULL if there's no such instrument
1673         */
1674        Instrument* File::GetInstrument(uint index) {
1675            if (!pInstruments) LoadInstruments();
1676            if (!pInstruments) return NULL;
1677            InstrumentsIterator = pInstruments->begin();
1678            for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
1679                if (i == index) return *InstrumentsIterator;
1680                InstrumentsIterator++;
1681            }
1682            return NULL;
1683        }
1684    
1685      void File::LoadInstruments() {      void File::LoadInstruments() {
1686          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1687          if (lstInstruments) {          if (lstInstruments) {

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

  ViewVC Help
Powered by ViewVC