/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Annotation of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 406 - (hide annotations) (download)
Wed Feb 23 19:11:07 2005 UTC (15 years, 7 months ago) by persson
File size: 82953 byte(s)
* src/gig.h, src/gig.cpp: added pre-calculated sample attenuation
  parameter
* src/gigdump: added output of Gain and SampleStartOffset

1 schoenebeck 2 /***************************************************************************
2     * *
3     * libgig - C++ cross-platform Gigasampler format file loader library *
4     * *
5 schoenebeck 384 * Copyright (C) 2003-2005 by Christian Schoenebeck *
6     * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8     * 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 *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This library is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this library; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include "gig.h"
25    
26 schoenebeck 384 #include <iostream>
27    
28 persson 365 namespace gig { namespace {
29 schoenebeck 2
30 persson 365 // *************** Internal functions for sample decopmression ***************
31     // *
32    
33     inline int get12lo(const unsigned char* pSrc)
34     {
35     const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
36     return x & 0x800 ? x - 0x1000 : x;
37     }
38    
39     inline int get12hi(const unsigned char* pSrc)
40     {
41     const int x = pSrc[1] >> 4 | pSrc[2] << 4;
42     return x & 0x800 ? x - 0x1000 : x;
43     }
44    
45     inline int16_t get16(const unsigned char* pSrc)
46     {
47     return int16_t(pSrc[0] | pSrc[1] << 8);
48     }
49    
50     inline int get24(const unsigned char* pSrc)
51     {
52     const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
53     return x & 0x800000 ? x - 0x1000000 : x;
54     }
55    
56     void Decompress16(int compressionmode, const unsigned char* params,
57 persson 372 int srcStep, int dstStep,
58     const unsigned char* pSrc, int16_t* pDst,
59 persson 365 unsigned long currentframeoffset,
60     unsigned long copysamples)
61     {
62     switch (compressionmode) {
63     case 0: // 16 bit uncompressed
64     pSrc += currentframeoffset * srcStep;
65     while (copysamples) {
66     *pDst = get16(pSrc);
67 persson 372 pDst += dstStep;
68 persson 365 pSrc += srcStep;
69     copysamples--;
70     }
71     break;
72    
73     case 1: // 16 bit compressed to 8 bit
74     int y = get16(params);
75     int dy = get16(params + 2);
76     while (currentframeoffset) {
77     dy -= int8_t(*pSrc);
78     y -= dy;
79     pSrc += srcStep;
80     currentframeoffset--;
81     }
82     while (copysamples) {
83     dy -= int8_t(*pSrc);
84     y -= dy;
85     *pDst = y;
86 persson 372 pDst += dstStep;
87 persson 365 pSrc += srcStep;
88     copysamples--;
89     }
90     break;
91     }
92     }
93    
94     void Decompress24(int compressionmode, const unsigned char* params,
95 persson 372 int dstStep, const unsigned char* pSrc, int16_t* pDst,
96 persson 365 unsigned long currentframeoffset,
97     unsigned long copysamples)
98     {
99     // Note: The 24 bits are truncated to 16 bits for now.
100    
101     // Note: The calculation of the initial value of y is strange
102     // and not 100% correct. What should the first two parameters
103     // really be used for? Why are they two? The correct value for
104     // y seems to lie somewhere between the values of the first
105     // two parameters.
106     //
107     // Strange thing #2: The formula in SKIP_ONE gives values for
108     // y that are twice as high as they should be. That's why
109     // COPY_ONE shifts 9 steps instead of 8, and also why y is
110     // initialized with a sum instead of a mean value.
111    
112     int y, dy, ddy;
113    
114     #define GET_PARAMS(params) \
115     y = (get24(params) + get24((params) + 3)); \
116     dy = get24((params) + 6); \
117     ddy = get24((params) + 9)
118    
119     #define SKIP_ONE(x) \
120     ddy -= (x); \
121     dy -= ddy; \
122     y -= dy
123    
124     #define COPY_ONE(x) \
125     SKIP_ONE(x); \
126     *pDst = y >> 9; \
127 persson 372 pDst += dstStep
128 persson 365
129     switch (compressionmode) {
130     case 2: // 24 bit uncompressed
131     pSrc += currentframeoffset * 3;
132     while (copysamples) {
133     *pDst = get24(pSrc) >> 8;
134 persson 372 pDst += dstStep;
135 persson 365 pSrc += 3;
136     copysamples--;
137     }
138     break;
139    
140     case 3: // 24 bit compressed to 16 bit
141     GET_PARAMS(params);
142     while (currentframeoffset) {
143     SKIP_ONE(get16(pSrc));
144     pSrc += 2;
145     currentframeoffset--;
146     }
147     while (copysamples) {
148     COPY_ONE(get16(pSrc));
149     pSrc += 2;
150     copysamples--;
151     }
152     break;
153    
154     case 4: // 24 bit compressed to 12 bit
155     GET_PARAMS(params);
156     while (currentframeoffset > 1) {
157     SKIP_ONE(get12lo(pSrc));
158     SKIP_ONE(get12hi(pSrc));
159     pSrc += 3;
160     currentframeoffset -= 2;
161     }
162     if (currentframeoffset) {
163     SKIP_ONE(get12lo(pSrc));
164     currentframeoffset--;
165     if (copysamples) {
166     COPY_ONE(get12hi(pSrc));
167     pSrc += 3;
168     copysamples--;
169     }
170     }
171     while (copysamples > 1) {
172     COPY_ONE(get12lo(pSrc));
173     COPY_ONE(get12hi(pSrc));
174     pSrc += 3;
175     copysamples -= 2;
176     }
177     if (copysamples) {
178     COPY_ONE(get12lo(pSrc));
179     }
180     break;
181    
182     case 5: // 24 bit compressed to 8 bit
183     GET_PARAMS(params);
184     while (currentframeoffset) {
185     SKIP_ONE(int8_t(*pSrc++));
186     currentframeoffset--;
187     }
188     while (copysamples) {
189     COPY_ONE(int8_t(*pSrc++));
190     copysamples--;
191     }
192     break;
193     }
194     }
195    
196     const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
197     const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
198     const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
199     const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
200     }
201    
202    
203 schoenebeck 2 // *************** Sample ***************
204     // *
205    
206 schoenebeck 384 unsigned int Sample::Instances = 0;
207     buffer_t Sample::InternalDecompressionBuffer;
208 schoenebeck 2
209     Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
210     Instances++;
211    
212     RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
213     if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
214     SampleGroup = _3gix->ReadInt16();
215    
216     RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
217     if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
218     Manufacturer = smpl->ReadInt32();
219     Product = smpl->ReadInt32();
220     SamplePeriod = smpl->ReadInt32();
221     MIDIUnityNote = smpl->ReadInt32();
222 schoenebeck 21 FineTune = smpl->ReadInt32();
223 schoenebeck 2 smpl->Read(&SMPTEFormat, 1, 4);
224     SMPTEOffset = smpl->ReadInt32();
225     Loops = smpl->ReadInt32();
226 persson 365 smpl->ReadInt32(); // manufByt
227 schoenebeck 2 LoopID = smpl->ReadInt32();
228     smpl->Read(&LoopType, 1, 4);
229     LoopStart = smpl->ReadInt32();
230     LoopEnd = smpl->ReadInt32();
231     LoopFraction = smpl->ReadInt32();
232     LoopPlayCount = smpl->ReadInt32();
233    
234     FrameTable = NULL;
235     SamplePos = 0;
236     RAMCache.Size = 0;
237     RAMCache.pStart = NULL;
238     RAMCache.NullExtensionSize = 0;
239    
240 persson 365 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
241    
242 schoenebeck 2 Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));
243     if (Compressed) {
244     ScanCompressedSample();
245     }
246 schoenebeck 317
247     // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
248 schoenebeck 384 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
249     InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
250     InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
251 schoenebeck 317 }
252 schoenebeck 2 FrameOffset = 0; // just for streaming compressed samples
253 schoenebeck 21
254 schoenebeck 27 LoopSize = LoopEnd - LoopStart;
255 schoenebeck 2 }
256    
257     /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
258     void Sample::ScanCompressedSample() {
259     //TODO: we have to add some more scans here (e.g. determine compression rate)
260     this->SamplesTotal = 0;
261     std::list<unsigned long> frameOffsets;
262    
263 persson 365 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
264 schoenebeck 384 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
265 persson 365
266 schoenebeck 2 // Scanning
267     pCkData->SetPos(0);
268 persson 365 if (Channels == 2) { // Stereo
269     for (int i = 0 ; ; i++) {
270     // for 24 bit samples every 8:th frame offset is
271     // stored, to save some memory
272     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
273    
274     const int mode_l = pCkData->ReadUint8();
275     const int mode_r = pCkData->ReadUint8();
276     if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
277     const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
278    
279     if (pCkData->RemainingBytes() <= frameSize) {
280     SamplesInLastFrame =
281     ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
282     (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
283     SamplesTotal += SamplesInLastFrame;
284 schoenebeck 2 break;
285 persson 365 }
286     SamplesTotal += SamplesPerFrame;
287     pCkData->SetPos(frameSize, RIFF::stream_curpos);
288     }
289     }
290     else { // Mono
291     for (int i = 0 ; ; i++) {
292     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
293    
294     const int mode = pCkData->ReadUint8();
295     if (mode > 5) throw gig::Exception("Unknown compression mode");
296     const unsigned long frameSize = bytesPerFrame[mode];
297    
298     if (pCkData->RemainingBytes() <= frameSize) {
299     SamplesInLastFrame =
300     ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
301     SamplesTotal += SamplesInLastFrame;
302 schoenebeck 2 break;
303 persson 365 }
304     SamplesTotal += SamplesPerFrame;
305     pCkData->SetPos(frameSize, RIFF::stream_curpos);
306 schoenebeck 2 }
307     }
308     pCkData->SetPos(0);
309    
310     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
311     if (FrameTable) delete[] FrameTable;
312     FrameTable = new unsigned long[frameOffsets.size()];
313     std::list<unsigned long>::iterator end = frameOffsets.end();
314     std::list<unsigned long>::iterator iter = frameOffsets.begin();
315     for (int i = 0; iter != end; i++, iter++) {
316     FrameTable[i] = *iter;
317     }
318     }
319    
320     /**
321     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
322     * ReleaseSampleData() to free the memory if you don't need the cached
323     * sample data anymore.
324     *
325     * @returns buffer_t structure with start address and size of the buffer
326     * in bytes
327     * @see ReleaseSampleData(), Read(), SetPos()
328     */
329     buffer_t Sample::LoadSampleData() {
330     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
331     }
332    
333     /**
334     * Reads (uncompresses if needed) and caches the first \a SampleCount
335     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
336     * memory space if you don't need the cached samples anymore. There is no
337     * guarantee that exactly \a SampleCount samples will be cached; this is
338     * not an error. The size will be eventually truncated e.g. to the
339     * beginning of a frame of a compressed sample. This is done for
340     * efficiency reasons while streaming the wave by your sampler engine
341     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
342     * that will be returned to determine the actual cached samples, but note
343     * that the size is given in bytes! You get the number of actually cached
344     * samples by dividing it by the frame size of the sample:
345 schoenebeck 384 * @code
346 schoenebeck 2 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
347     * long cachedsamples = buf.Size / pSample->FrameSize;
348 schoenebeck 384 * @endcode
349 schoenebeck 2 *
350     * @param SampleCount - number of sample points to load into RAM
351     * @returns buffer_t structure with start address and size of
352     * the cached sample data in bytes
353     * @see ReleaseSampleData(), Read(), SetPos()
354     */
355     buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
356     return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
357     }
358    
359     /**
360     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
361     * ReleaseSampleData() to free the memory if you don't need the cached
362     * sample data anymore.
363     * The method will add \a NullSamplesCount silence samples past the
364     * official buffer end (this won't affect the 'Size' member of the
365     * buffer_t structure, that means 'Size' always reflects the size of the
366     * actual sample data, the buffer might be bigger though). Silence
367     * samples past the official buffer are needed for differential
368     * algorithms that always have to take subsequent samples into account
369     * (resampling/interpolation would be an important example) and avoids
370     * memory access faults in such cases.
371     *
372     * @param NullSamplesCount - number of silence samples the buffer should
373     * be extended past it's data end
374     * @returns buffer_t structure with start address and
375     * size of the buffer in bytes
376     * @see ReleaseSampleData(), Read(), SetPos()
377     */
378     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
379     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
380     }
381    
382     /**
383     * Reads (uncompresses if needed) and caches the first \a SampleCount
384     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
385     * memory space if you don't need the cached samples anymore. There is no
386     * guarantee that exactly \a SampleCount samples will be cached; this is
387     * not an error. The size will be eventually truncated e.g. to the
388     * beginning of a frame of a compressed sample. This is done for
389     * efficiency reasons while streaming the wave by your sampler engine
390     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
391     * that will be returned to determine the actual cached samples, but note
392     * that the size is given in bytes! You get the number of actually cached
393     * samples by dividing it by the frame size of the sample:
394 schoenebeck 384 * @code
395 schoenebeck 2 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
396     * long cachedsamples = buf.Size / pSample->FrameSize;
397 schoenebeck 384 * @endcode
398 schoenebeck 2 * The method will add \a NullSamplesCount silence samples past the
399     * official buffer end (this won't affect the 'Size' member of the
400     * buffer_t structure, that means 'Size' always reflects the size of the
401     * actual sample data, the buffer might be bigger though). Silence
402     * samples past the official buffer are needed for differential
403     * algorithms that always have to take subsequent samples into account
404     * (resampling/interpolation would be an important example) and avoids
405     * memory access faults in such cases.
406     *
407     * @param SampleCount - number of sample points to load into RAM
408     * @param NullSamplesCount - number of silence samples the buffer should
409     * be extended past it's data end
410     * @returns buffer_t structure with start address and
411     * size of the cached sample data in bytes
412     * @see ReleaseSampleData(), Read(), SetPos()
413     */
414     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
415     if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
416     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
417     unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
418     RAMCache.pStart = new int8_t[allocationsize];
419     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
420     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
421     // fill the remaining buffer space with silence samples
422     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
423     return GetCache();
424     }
425    
426     /**
427     * Returns current cached sample points. A buffer_t structure will be
428     * returned which contains address pointer to the begin of the cache and
429     * the size of the cached sample data in bytes. Use
430     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
431     * RAM.
432     *
433     * @returns buffer_t structure with current cached sample points
434     * @see LoadSampleData();
435     */
436     buffer_t Sample::GetCache() {
437     // return a copy of the buffer_t structure
438     buffer_t result;
439     result.Size = this->RAMCache.Size;
440     result.pStart = this->RAMCache.pStart;
441     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
442     return result;
443     }
444    
445     /**
446     * Frees the cached sample from RAM if loaded with
447     * <i>LoadSampleData()</i> previously.
448     *
449     * @see LoadSampleData();
450     */
451     void Sample::ReleaseSampleData() {
452     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
453     RAMCache.pStart = NULL;
454     RAMCache.Size = 0;
455     }
456    
457     /**
458     * Sets the position within the sample (in sample points, not in
459     * bytes). Use this method and <i>Read()</i> if you don't want to load
460     * the sample into RAM, thus for disk streaming.
461     *
462     * Although the original Gigasampler engine doesn't allow positioning
463     * within compressed samples, I decided to implement it. Even though
464     * the Gigasampler format doesn't allow to define loops for compressed
465     * samples at the moment, positioning within compressed samples might be
466     * interesting for some sampler engines though. The only drawback about
467     * my decision is that it takes longer to load compressed gig Files on
468     * startup, because it's neccessary to scan the samples for some
469     * mandatory informations. But I think as it doesn't affect the runtime
470     * efficiency, nobody will have a problem with that.
471     *
472     * @param SampleCount number of sample points to jump
473     * @param Whence optional: to which relation \a SampleCount refers
474     * to, if omited <i>RIFF::stream_start</i> is assumed
475     * @returns the new sample position
476     * @see Read()
477     */
478     unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
479     if (Compressed) {
480     switch (Whence) {
481     case RIFF::stream_curpos:
482     this->SamplePos += SampleCount;
483     break;
484     case RIFF::stream_end:
485     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
486     break;
487     case RIFF::stream_backward:
488     this->SamplePos -= SampleCount;
489     break;
490     case RIFF::stream_start: default:
491     this->SamplePos = SampleCount;
492     break;
493     }
494     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
495    
496     unsigned long frame = this->SamplePos / 2048; // to which frame to jump
497     this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
498     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
499     return this->SamplePos;
500     }
501     else { // not compressed
502     unsigned long orderedBytes = SampleCount * this->FrameSize;
503     unsigned long result = pCkData->SetPos(orderedBytes, Whence);
504     return (result == orderedBytes) ? SampleCount
505     : result / this->FrameSize;
506     }
507     }
508    
509     /**
510     * Returns the current position in the sample (in sample points).
511     */
512     unsigned long Sample::GetPos() {
513     if (Compressed) return SamplePos;
514     else return pCkData->GetPos() / FrameSize;
515     }
516    
517     /**
518 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
519     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
520     * the position within the sample respectively, this method honors the
521     * looping informations of the sample (if any). The sample wave stream
522     * will be decompressed on the fly if using a compressed sample. Use this
523     * method if you don't want to load the sample into RAM, thus for disk
524     * streaming. All this methods needs to know to proceed with streaming
525     * for the next time you call this method is stored in \a pPlaybackState.
526     * You have to allocate and initialize the playback_state_t structure by
527     * yourself before you use it to stream a sample:
528 schoenebeck 384 * @code
529     * gig::playback_state_t playbackstate;
530     * playbackstate.position = 0;
531     * playbackstate.reverse = false;
532     * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
533     * @endcode
534 schoenebeck 24 * You don't have to take care of things like if there is actually a loop
535     * defined or if the current read position is located within a loop area.
536     * The method already handles such cases by itself.
537     *
538 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
539     * have to use an external decompression buffer for <b>EACH</b>
540     * streaming thread to avoid race conditions and crashes!
541     *
542 schoenebeck 24 * @param pBuffer destination buffer
543     * @param SampleCount number of sample points to read
544     * @param pPlaybackState will be used to store and reload the playback
545     * state for the next ReadAndLoop() call
546 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
547 schoenebeck 24 * @returns number of successfully read sample points
548 schoenebeck 384 * @see CreateDecompressionBuffer()
549 schoenebeck 24 */
550 schoenebeck 384 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {
551 schoenebeck 24 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
552     uint8_t* pDst = (uint8_t*) pBuffer;
553    
554     SetPos(pPlaybackState->position); // recover position from the last time
555    
556     if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined
557    
558     switch (this->LoopType) {
559    
560     case loop_type_bidirectional: { //TODO: not tested yet!
561     do {
562     // if not endless loop check if max. number of loop cycles have been passed
563     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
564    
565     if (!pPlaybackState->reverse) { // forward playback
566     do {
567     samplestoloopend = this->LoopEnd - GetPos();
568 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
569 schoenebeck 24 samplestoread -= readsamples;
570     totalreadsamples += readsamples;
571     if (readsamples == samplestoloopend) {
572     pPlaybackState->reverse = true;
573     break;
574     }
575     } while (samplestoread && readsamples);
576     }
577     else { // backward playback
578    
579     // as we can only read forward from disk, we have to
580     // determine the end position within the loop first,
581     // read forward from that 'end' and finally after
582     // reading, swap all sample frames so it reflects
583     // backward playback
584    
585     unsigned long swapareastart = totalreadsamples;
586     unsigned long loopoffset = GetPos() - this->LoopStart;
587     unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
588     unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
589    
590     SetPos(reverseplaybackend);
591    
592     // read samples for backward playback
593     do {
594 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
595 schoenebeck 24 samplestoreadinloop -= readsamples;
596     samplestoread -= readsamples;
597     totalreadsamples += readsamples;
598     } while (samplestoreadinloop && readsamples);
599    
600     SetPos(reverseplaybackend); // pretend we really read backwards
601    
602     if (reverseplaybackend == this->LoopStart) {
603     pPlaybackState->loop_cycles_left--;
604     pPlaybackState->reverse = false;
605     }
606    
607     // reverse the sample frames for backward playback
608     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
609     }
610     } while (samplestoread && readsamples);
611     break;
612     }
613    
614     case loop_type_backward: { // TODO: not tested yet!
615     // forward playback (not entered the loop yet)
616     if (!pPlaybackState->reverse) do {
617     samplestoloopend = this->LoopEnd - GetPos();
618 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
619 schoenebeck 24 samplestoread -= readsamples;
620     totalreadsamples += readsamples;
621     if (readsamples == samplestoloopend) {
622     pPlaybackState->reverse = true;
623     break;
624     }
625     } while (samplestoread && readsamples);
626    
627     if (!samplestoread) break;
628    
629     // as we can only read forward from disk, we have to
630     // determine the end position within the loop first,
631     // read forward from that 'end' and finally after
632     // reading, swap all sample frames so it reflects
633     // backward playback
634    
635     unsigned long swapareastart = totalreadsamples;
636     unsigned long loopoffset = GetPos() - this->LoopStart;
637     unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)
638     : samplestoread;
639     unsigned long reverseplaybackend = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);
640    
641     SetPos(reverseplaybackend);
642    
643     // read samples for backward playback
644     do {
645     // if not endless loop check if max. number of loop cycles have been passed
646     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
647     samplestoloopend = this->LoopEnd - GetPos();
648 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
649 schoenebeck 24 samplestoreadinloop -= readsamples;
650     samplestoread -= readsamples;
651     totalreadsamples += readsamples;
652     if (readsamples == samplestoloopend) {
653     pPlaybackState->loop_cycles_left--;
654     SetPos(this->LoopStart);
655     }
656     } while (samplestoreadinloop && readsamples);
657    
658     SetPos(reverseplaybackend); // pretend we really read backwards
659    
660     // reverse the sample frames for backward playback
661     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
662     break;
663     }
664    
665     default: case loop_type_normal: {
666     do {
667     // if not endless loop check if max. number of loop cycles have been passed
668     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
669     samplestoloopend = this->LoopEnd - GetPos();
670 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
671 schoenebeck 24 samplestoread -= readsamples;
672     totalreadsamples += readsamples;
673     if (readsamples == samplestoloopend) {
674     pPlaybackState->loop_cycles_left--;
675     SetPos(this->LoopStart);
676     }
677     } while (samplestoread && readsamples);
678     break;
679     }
680     }
681     }
682    
683     // read on without looping
684     if (samplestoread) do {
685 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
686 schoenebeck 24 samplestoread -= readsamples;
687     totalreadsamples += readsamples;
688     } while (readsamples && samplestoread);
689    
690     // store current position
691     pPlaybackState->position = GetPos();
692    
693     return totalreadsamples;
694     }
695    
696     /**
697 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
698     * position into the buffer pointed by \a pBuffer and increments the
699     * position within the sample. The sample wave stream will be
700     * decompressed on the fly if using a compressed sample. Use this method
701     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
702     * thus for disk streaming.
703     *
704 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
705     * have to use an external decompression buffer for <b>EACH</b>
706     * streaming thread to avoid race conditions and crashes!
707     *
708 schoenebeck 2 * @param pBuffer destination buffer
709     * @param SampleCount number of sample points to read
710 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
711 schoenebeck 2 * @returns number of successfully read sample points
712 schoenebeck 384 * @see SetPos(), CreateDecompressionBuffer()
713 schoenebeck 2 */
714 schoenebeck 384 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
715 schoenebeck 21 if (SampleCount == 0) return 0;
716 schoenebeck 317 if (!Compressed) {
717     if (BitDepth == 24) {
718     // 24 bit sample. For now just truncate to 16 bit.
719 schoenebeck 384 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
720 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
721     if (Channels == 2) { // Stereo
722     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
723 schoenebeck 317 pSrc++;
724 persson 365 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
725     *pDst++ = get16(pSrc);
726     pSrc += 3;
727     }
728     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
729 schoenebeck 317 }
730 persson 365 else { // Mono
731     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
732     pSrc++;
733     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
734     *pDst++ = get16(pSrc);
735     pSrc += 3;
736     }
737     return pDst - static_cast<int16_t*>(pBuffer);
738     }
739 schoenebeck 317 }
740 persson 365 else { // 16 bit
741     // (pCkData->Read does endian correction)
742     return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
743     : pCkData->Read(pBuffer, SampleCount, 2);
744     }
745 schoenebeck 317 }
746 persson 365 else {
747 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
748 persson 365 //TODO: efficiency: maybe we should test for an average compression rate
749     unsigned long assumedsize = GuessSize(SampleCount),
750 schoenebeck 2 remainingbytes = 0, // remaining bytes in the local buffer
751     remainingsamples = SampleCount,
752 persson 365 copysamples, skipsamples,
753     currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
754 schoenebeck 2 this->FrameOffset = 0;
755    
756 schoenebeck 384 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
757    
758     // if decompression buffer too small, then reduce amount of samples to read
759     if (pDecompressionBuffer->Size < assumedsize) {
760     std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
761     SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
762     remainingsamples = SampleCount;
763     assumedsize = GuessSize(SampleCount);
764 schoenebeck 2 }
765    
766 schoenebeck 384 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
767 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
768 schoenebeck 2 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
769    
770 persson 365 while (remainingsamples && remainingbytes) {
771     unsigned long framesamples = SamplesPerFrame;
772     unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
773 schoenebeck 2
774 persson 365 int mode_l = *pSrc++, mode_r = 0;
775    
776     if (Channels == 2) {
777     mode_r = *pSrc++;
778     framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
779     rightChannelOffset = bytesPerFrameNoHdr[mode_l];
780     nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
781     if (remainingbytes < framebytes) { // last frame in sample
782     framesamples = SamplesInLastFrame;
783     if (mode_l == 4 && (framesamples & 1)) {
784     rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
785     }
786     else {
787     rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
788     }
789 schoenebeck 2 }
790     }
791 persson 365 else {
792     framebytes = bytesPerFrame[mode_l] + 1;
793     nextFrameOffset = bytesPerFrameNoHdr[mode_l];
794     if (remainingbytes < framebytes) {
795     framesamples = SamplesInLastFrame;
796     }
797     }
798 schoenebeck 2
799     // determine how many samples in this frame to skip and read
800 persson 365 if (currentframeoffset + remainingsamples >= framesamples) {
801     if (currentframeoffset <= framesamples) {
802     copysamples = framesamples - currentframeoffset;
803     skipsamples = currentframeoffset;
804     }
805     else {
806     copysamples = 0;
807     skipsamples = framesamples;
808     }
809 schoenebeck 2 }
810     else {
811 persson 365 // This frame has enough data for pBuffer, but not
812     // all of the frame is needed. Set file position
813     // to start of this frame for next call to Read.
814 schoenebeck 2 copysamples = remainingsamples;
815 persson 365 skipsamples = currentframeoffset;
816     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
817     this->FrameOffset = currentframeoffset + copysamples;
818     }
819     remainingsamples -= copysamples;
820    
821     if (remainingbytes > framebytes) {
822     remainingbytes -= framebytes;
823     if (remainingsamples == 0 &&
824     currentframeoffset + copysamples == framesamples) {
825     // This frame has enough data for pBuffer, and
826     // all of the frame is needed. Set file
827     // position to start of next frame for next
828     // call to Read. FrameOffset is 0.
829 schoenebeck 2 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
830     }
831     }
832 persson 365 else remainingbytes = 0;
833 schoenebeck 2
834 persson 365 currentframeoffset -= skipsamples;
835 schoenebeck 2
836 persson 365 if (copysamples == 0) {
837     // skip this frame
838     pSrc += framebytes - Channels;
839     }
840     else {
841     const unsigned char* const param_l = pSrc;
842     if (BitDepth == 24) {
843     if (mode_l != 2) pSrc += 12;
844 schoenebeck 2
845 persson 365 if (Channels == 2) { // Stereo
846     const unsigned char* const param_r = pSrc;
847     if (mode_r != 2) pSrc += 12;
848    
849 persson 372 Decompress24(mode_l, param_l, 2, pSrc, pDst, skipsamples, copysamples);
850     Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
851 persson 365 skipsamples, copysamples);
852     pDst += copysamples << 1;
853 schoenebeck 2 }
854 persson 365 else { // Mono
855 persson 372 Decompress24(mode_l, param_l, 1, pSrc, pDst, skipsamples, copysamples);
856 persson 365 pDst += copysamples;
857 schoenebeck 2 }
858 persson 365 }
859     else { // 16 bit
860     if (mode_l) pSrc += 4;
861 schoenebeck 2
862 persson 365 int step;
863     if (Channels == 2) { // Stereo
864     const unsigned char* const param_r = pSrc;
865     if (mode_r) pSrc += 4;
866    
867     step = (2 - mode_l) + (2 - mode_r);
868 persson 372 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
869     Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
870 persson 365 skipsamples, copysamples);
871     pDst += copysamples << 1;
872 schoenebeck 2 }
873 persson 365 else { // Mono
874     step = 2 - mode_l;
875 persson 372 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
876 persson 365 pDst += copysamples;
877 schoenebeck 2 }
878 persson 365 }
879     pSrc += nextFrameOffset;
880     }
881 schoenebeck 2
882 persson 365 // reload from disk to local buffer if needed
883     if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
884     assumedsize = GuessSize(remainingsamples);
885     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
886     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
887 schoenebeck 384 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
888     pSrc = (unsigned char*) pDecompressionBuffer->pStart;
889 schoenebeck 2 }
890 persson 365 } // while
891    
892 schoenebeck 2 this->SamplePos += (SampleCount - remainingsamples);
893 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
894 schoenebeck 2 return (SampleCount - remainingsamples);
895     }
896     }
897    
898 schoenebeck 384 /**
899     * Allocates a decompression buffer for streaming (compressed) samples
900     * with Sample::Read(). If you are using more than one streaming thread
901     * in your application you <b>HAVE</b> to create a decompression buffer
902     * for <b>EACH</b> of your streaming threads and provide it with the
903     * Sample::Read() call in order to avoid race conditions and crashes.
904     *
905     * You should free the memory occupied by the allocated buffer(s) once
906     * you don't need one of your streaming threads anymore by calling
907     * DestroyDecompressionBuffer().
908     *
909     * @param MaxReadSize - the maximum size (in sample points) you ever
910     * expect to read with one Read() call
911     * @returns allocated decompression buffer
912     * @see DestroyDecompressionBuffer()
913     */
914     buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
915     buffer_t result;
916     const double worstCaseHeaderOverhead =
917     (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
918     result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
919     result.pStart = new int8_t[result.Size];
920     result.NullExtensionSize = 0;
921     return result;
922     }
923    
924     /**
925     * Free decompression buffer, previously created with
926     * CreateDecompressionBuffer().
927     *
928     * @param DecompressionBuffer - previously allocated decompression
929     * buffer to free
930     */
931     void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
932     if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
933     delete[] (int8_t*) DecompressionBuffer.pStart;
934     DecompressionBuffer.pStart = NULL;
935     DecompressionBuffer.Size = 0;
936     DecompressionBuffer.NullExtensionSize = 0;
937     }
938     }
939    
940 schoenebeck 2 Sample::~Sample() {
941     Instances--;
942 schoenebeck 384 if (!Instances && InternalDecompressionBuffer.Size) {
943     delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
944     InternalDecompressionBuffer.pStart = NULL;
945     InternalDecompressionBuffer.Size = 0;
946 schoenebeck 355 }
947 schoenebeck 2 if (FrameTable) delete[] FrameTable;
948     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
949     }
950    
951    
952    
953     // *************** DimensionRegion ***************
954     // *
955    
956 schoenebeck 16 uint DimensionRegion::Instances = 0;
957     DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
958    
959 schoenebeck 2 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
960 schoenebeck 16 Instances++;
961    
962 schoenebeck 2 memcpy(&Crossfade, &SamplerOptions, 4);
963 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
964 schoenebeck 2
965     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
966 schoenebeck 241 _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
967 schoenebeck 2 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
968     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
969     _3ewa->ReadInt16(); // unknown
970     LFO1InternalDepth = _3ewa->ReadUint16();
971     _3ewa->ReadInt16(); // unknown
972     LFO3InternalDepth = _3ewa->ReadInt16();
973     _3ewa->ReadInt16(); // unknown
974     LFO1ControlDepth = _3ewa->ReadUint16();
975     _3ewa->ReadInt16(); // unknown
976     LFO3ControlDepth = _3ewa->ReadInt16();
977     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
978     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
979     _3ewa->ReadInt16(); // unknown
980     EG1Sustain = _3ewa->ReadUint16();
981     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
982 schoenebeck 36 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
983 schoenebeck 2 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
984     EG1ControllerInvert = eg1ctrloptions & 0x01;
985     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
986     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
987     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
988 schoenebeck 36 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
989 schoenebeck 2 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
990     EG2ControllerInvert = eg2ctrloptions & 0x01;
991     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
992     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
993     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
994     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
995     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
996     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
997     _3ewa->ReadInt16(); // unknown
998     EG2Sustain = _3ewa->ReadUint16();
999     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1000     _3ewa->ReadInt16(); // unknown
1001     LFO2ControlDepth = _3ewa->ReadUint16();
1002     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1003     _3ewa->ReadInt16(); // unknown
1004     LFO2InternalDepth = _3ewa->ReadUint16();
1005     int32_t eg1decay2 = _3ewa->ReadInt32();
1006     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1007     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1008     _3ewa->ReadInt16(); // unknown
1009     EG1PreAttack = _3ewa->ReadUint16();
1010     int32_t eg2decay2 = _3ewa->ReadInt32();
1011     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1012     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1013     _3ewa->ReadInt16(); // unknown
1014     EG2PreAttack = _3ewa->ReadUint16();
1015     uint8_t velocityresponse = _3ewa->ReadUint8();
1016     if (velocityresponse < 5) {
1017     VelocityResponseCurve = curve_type_nonlinear;
1018     VelocityResponseDepth = velocityresponse;
1019     }
1020     else if (velocityresponse < 10) {
1021     VelocityResponseCurve = curve_type_linear;
1022     VelocityResponseDepth = velocityresponse - 5;
1023     }
1024     else if (velocityresponse < 15) {
1025     VelocityResponseCurve = curve_type_special;
1026     VelocityResponseDepth = velocityresponse - 10;
1027     }
1028     else {
1029     VelocityResponseCurve = curve_type_unknown;
1030     VelocityResponseDepth = 0;
1031     }
1032     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1033     if (releasevelocityresponse < 5) {
1034     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1035     ReleaseVelocityResponseDepth = releasevelocityresponse;
1036     }
1037     else if (releasevelocityresponse < 10) {
1038     ReleaseVelocityResponseCurve = curve_type_linear;
1039     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1040     }
1041     else if (releasevelocityresponse < 15) {
1042     ReleaseVelocityResponseCurve = curve_type_special;
1043     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1044     }
1045     else {
1046     ReleaseVelocityResponseCurve = curve_type_unknown;
1047     ReleaseVelocityResponseDepth = 0;
1048     }
1049     VelocityResponseCurveScaling = _3ewa->ReadUint8();
1050 schoenebeck 36 AttenuationControllerThreshold = _3ewa->ReadInt8();
1051 schoenebeck 2 _3ewa->ReadInt32(); // unknown
1052     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1053     _3ewa->ReadInt16(); // unknown
1054     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1055     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1056     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1057     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1058     else DimensionBypass = dim_bypass_ctrl_none;
1059     uint8_t pan = _3ewa->ReadUint8();
1060 schoenebeck 269 Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1061 schoenebeck 2 SelfMask = _3ewa->ReadInt8() & 0x01;
1062     _3ewa->ReadInt8(); // unknown
1063     uint8_t lfo3ctrl = _3ewa->ReadUint8();
1064     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1065     LFO3Sync = lfo3ctrl & 0x20; // bit 5
1066 schoenebeck 36 InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1067     AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1068 schoenebeck 2 uint8_t lfo2ctrl = _3ewa->ReadUint8();
1069     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1070     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1071     LFO2Sync = lfo2ctrl & 0x20; // bit 5
1072     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1073     uint8_t lfo1ctrl = _3ewa->ReadUint8();
1074     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1075     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1076     LFO1Sync = lfo1ctrl & 0x40; // bit 6
1077     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1078     : vcf_res_ctrl_none;
1079     uint16_t eg3depth = _3ewa->ReadUint16();
1080     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1081     : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1082     _3ewa->ReadInt16(); // unknown
1083     ChannelOffset = _3ewa->ReadUint8() / 4;
1084     uint8_t regoptions = _3ewa->ReadUint8();
1085     MSDecode = regoptions & 0x01; // bit 0
1086     SustainDefeat = regoptions & 0x02; // bit 1
1087     _3ewa->ReadInt16(); // unknown
1088     VelocityUpperLimit = _3ewa->ReadInt8();
1089     _3ewa->ReadInt8(); // unknown
1090     _3ewa->ReadInt16(); // unknown
1091     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1092     _3ewa->ReadInt8(); // unknown
1093     _3ewa->ReadInt8(); // unknown
1094     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1095     uint8_t vcfcutoff = _3ewa->ReadUint8();
1096     VCFEnabled = vcfcutoff & 0x80; // bit 7
1097     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1098     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1099     VCFVelocityScale = _3ewa->ReadUint8();
1100     _3ewa->ReadInt8(); // unknown
1101     uint8_t vcfresonance = _3ewa->ReadUint8();
1102     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1103     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1104     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1105     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1106     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1107     uint8_t vcfvelocity = _3ewa->ReadUint8();
1108     VCFVelocityDynamicRange = vcfvelocity % 5;
1109     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1110     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1111 schoenebeck 345 if (VCFType == vcf_type_lowpass) {
1112     if (lfo3ctrl & 0x40) // bit 6
1113     VCFType = vcf_type_lowpassturbo;
1114     }
1115 schoenebeck 16
1116     // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet
1117     uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;
1118     if (pVelocityTables->count(tableKey)) { // if key exists
1119     pVelocityAttenuationTable = (*pVelocityTables)[tableKey];
1120     }
1121     else {
1122 schoenebeck 317 pVelocityAttenuationTable =
1123 schoenebeck 308 CreateVelocityTable(VelocityResponseCurve,
1124     VelocityResponseDepth,
1125     VelocityResponseCurveScaling);
1126 schoenebeck 16 (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
1127     }
1128 persson 406
1129     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1130 schoenebeck 2 }
1131 schoenebeck 55
1132 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1133     leverage_ctrl_t decodedcontroller;
1134     switch (EncodedController) {
1135     // special controller
1136     case _lev_ctrl_none:
1137     decodedcontroller.type = leverage_ctrl_t::type_none;
1138     decodedcontroller.controller_number = 0;
1139     break;
1140     case _lev_ctrl_velocity:
1141     decodedcontroller.type = leverage_ctrl_t::type_velocity;
1142     decodedcontroller.controller_number = 0;
1143     break;
1144     case _lev_ctrl_channelaftertouch:
1145     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1146     decodedcontroller.controller_number = 0;
1147     break;
1148 schoenebeck 55
1149 schoenebeck 36 // ordinary MIDI control change controller
1150     case _lev_ctrl_modwheel:
1151     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1152     decodedcontroller.controller_number = 1;
1153     break;
1154     case _lev_ctrl_breath:
1155     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1156     decodedcontroller.controller_number = 2;
1157     break;
1158     case _lev_ctrl_foot:
1159     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1160     decodedcontroller.controller_number = 4;
1161     break;
1162     case _lev_ctrl_effect1:
1163     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1164     decodedcontroller.controller_number = 12;
1165     break;
1166     case _lev_ctrl_effect2:
1167     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1168     decodedcontroller.controller_number = 13;
1169     break;
1170     case _lev_ctrl_genpurpose1:
1171     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1172     decodedcontroller.controller_number = 16;
1173     break;
1174     case _lev_ctrl_genpurpose2:
1175     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1176     decodedcontroller.controller_number = 17;
1177     break;
1178     case _lev_ctrl_genpurpose3:
1179     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1180     decodedcontroller.controller_number = 18;
1181     break;
1182     case _lev_ctrl_genpurpose4:
1183     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1184     decodedcontroller.controller_number = 19;
1185     break;
1186     case _lev_ctrl_portamentotime:
1187     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1188     decodedcontroller.controller_number = 5;
1189     break;
1190     case _lev_ctrl_sustainpedal:
1191     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1192     decodedcontroller.controller_number = 64;
1193     break;
1194     case _lev_ctrl_portamento:
1195     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1196     decodedcontroller.controller_number = 65;
1197     break;
1198     case _lev_ctrl_sostenutopedal:
1199     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1200     decodedcontroller.controller_number = 66;
1201     break;
1202     case _lev_ctrl_softpedal:
1203     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1204     decodedcontroller.controller_number = 67;
1205     break;
1206     case _lev_ctrl_genpurpose5:
1207     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1208     decodedcontroller.controller_number = 80;
1209     break;
1210     case _lev_ctrl_genpurpose6:
1211     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1212     decodedcontroller.controller_number = 81;
1213     break;
1214     case _lev_ctrl_genpurpose7:
1215     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1216     decodedcontroller.controller_number = 82;
1217     break;
1218     case _lev_ctrl_genpurpose8:
1219     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1220     decodedcontroller.controller_number = 83;
1221     break;
1222     case _lev_ctrl_effect1depth:
1223     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1224     decodedcontroller.controller_number = 91;
1225     break;
1226     case _lev_ctrl_effect2depth:
1227     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1228     decodedcontroller.controller_number = 92;
1229     break;
1230     case _lev_ctrl_effect3depth:
1231     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1232     decodedcontroller.controller_number = 93;
1233     break;
1234     case _lev_ctrl_effect4depth:
1235     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1236     decodedcontroller.controller_number = 94;
1237     break;
1238     case _lev_ctrl_effect5depth:
1239     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1240     decodedcontroller.controller_number = 95;
1241     break;
1242 schoenebeck 55
1243 schoenebeck 36 // unknown controller type
1244     default:
1245     throw gig::Exception("Unknown leverage controller type.");
1246     }
1247     return decodedcontroller;
1248     }
1249 schoenebeck 2
1250 schoenebeck 16 DimensionRegion::~DimensionRegion() {
1251     Instances--;
1252     if (!Instances) {
1253     // delete the velocity->volume tables
1254     VelocityTableMap::iterator iter;
1255     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
1256     double* pTable = iter->second;
1257     if (pTable) delete[] pTable;
1258     }
1259     pVelocityTables->clear();
1260     delete pVelocityTables;
1261     pVelocityTables = NULL;
1262     }
1263     }
1264 schoenebeck 2
1265 schoenebeck 16 /**
1266     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1267     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1268     * and VelocityResponseCurveScaling) involved are taken into account to
1269     * calculate the amplitude factor. Use this method when a key was
1270     * triggered to get the volume with which the sample should be played
1271     * back.
1272     *
1273 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
1274     * @returns amplitude factor (between 0.0 and 1.0)
1275 schoenebeck 16 */
1276     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1277     return pVelocityAttenuationTable[MIDIKeyVelocity];
1278     }
1279 schoenebeck 2
1280 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1281 schoenebeck 317
1282 schoenebeck 308 // line-segment approximations of the 15 velocity curves
1283 schoenebeck 16
1284 schoenebeck 308 // linear
1285     const int lin0[] = { 1, 1, 127, 127 };
1286     const int lin1[] = { 1, 21, 127, 127 };
1287     const int lin2[] = { 1, 45, 127, 127 };
1288     const int lin3[] = { 1, 74, 127, 127 };
1289     const int lin4[] = { 1, 127, 127, 127 };
1290 schoenebeck 16
1291 schoenebeck 308 // non-linear
1292     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1293 schoenebeck 317 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1294 schoenebeck 308 127, 127 };
1295     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1296     127, 127 };
1297     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1298     127, 127 };
1299     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1300 schoenebeck 317
1301 schoenebeck 308 // special
1302 schoenebeck 317 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1303 schoenebeck 308 113, 127, 127, 127 };
1304     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1305     118, 127, 127, 127 };
1306 schoenebeck 317 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
1307 schoenebeck 308 85, 90, 91, 127, 127, 127 };
1308 schoenebeck 317 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
1309 schoenebeck 308 117, 127, 127, 127 };
1310 schoenebeck 317 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
1311 schoenebeck 308 127, 127 };
1312 schoenebeck 317
1313 schoenebeck 308 const int* const curves[] = { non0, non1, non2, non3, non4,
1314 schoenebeck 317 lin0, lin1, lin2, lin3, lin4,
1315 schoenebeck 308 spe0, spe1, spe2, spe3, spe4 };
1316 schoenebeck 317
1317 schoenebeck 308 double* const table = new double[128];
1318    
1319     const int* curve = curves[curveType * 5 + depth];
1320     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
1321 schoenebeck 317
1322 schoenebeck 308 table[0] = 0;
1323     for (int x = 1 ; x < 128 ; x++) {
1324    
1325     if (x > curve[2]) curve += 2;
1326 schoenebeck 317 double y = curve[1] + (x - curve[0]) *
1327 schoenebeck 308 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
1328     y = y / 127;
1329    
1330     // Scale up for s > 20, down for s < 20. When
1331     // down-scaling, the curve still ends at 1.0.
1332     if (s < 20 && y >= 0.5)
1333     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
1334     else
1335     y = y * (s / 20.0);
1336     if (y > 1) y = 1;
1337    
1338     table[x] = y;
1339     }
1340     return table;
1341     }
1342    
1343    
1344 schoenebeck 2 // *************** Region ***************
1345     // *
1346    
1347     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
1348     // Initialization
1349     Dimensions = 0;
1350 schoenebeck 347 for (int i = 0; i < 256; i++) {
1351 schoenebeck 2 pDimensionRegions[i] = NULL;
1352     }
1353 schoenebeck 282 Layers = 1;
1354 schoenebeck 347 File* file = (File*) GetParent()->GetParent();
1355     int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
1356 schoenebeck 2
1357     // Actual Loading
1358    
1359     LoadDimensionRegions(rgnList);
1360    
1361     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1362     if (_3lnk) {
1363     DimensionRegions = _3lnk->ReadUint32();
1364 schoenebeck 347 for (int i = 0; i < dimensionBits; i++) {
1365 schoenebeck 2 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1366     uint8_t bits = _3lnk->ReadUint8();
1367     if (dimension == dimension_none) { // inactive dimension
1368     pDimensionDefinitions[i].dimension = dimension_none;
1369     pDimensionDefinitions[i].bits = 0;
1370     pDimensionDefinitions[i].zones = 0;
1371     pDimensionDefinitions[i].split_type = split_type_bit;
1372     pDimensionDefinitions[i].ranges = NULL;
1373     pDimensionDefinitions[i].zone_size = 0;
1374     }
1375     else { // active dimension
1376     pDimensionDefinitions[i].dimension = dimension;
1377     pDimensionDefinitions[i].bits = bits;
1378     pDimensionDefinitions[i].zones = 0x01 << bits; // = pow(2,bits)
1379     pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1380 schoenebeck 241 dimension == dimension_samplechannel ||
1381     dimension == dimension_releasetrigger) ? split_type_bit
1382     : split_type_normal;
1383 schoenebeck 2 pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
1384     pDimensionDefinitions[i].zone_size =
1385     (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1386     : 0;
1387     Dimensions++;
1388 schoenebeck 282
1389     // if this is a layer dimension, remember the amount of layers
1390     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
1391 schoenebeck 2 }
1392     _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1393     }
1394    
1395     // check velocity dimension (if there is one) for custom defined zone ranges
1396     for (uint i = 0; i < Dimensions; i++) {
1397     dimension_def_t* pDimDef = pDimensionDefinitions + i;
1398     if (pDimDef->dimension == dimension_velocity) {
1399     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {
1400     // no custom defined ranges
1401     pDimDef->split_type = split_type_normal;
1402     pDimDef->ranges = NULL;
1403     }
1404     else { // custom defined ranges
1405     pDimDef->split_type = split_type_customvelocity;
1406     pDimDef->ranges = new range_t[pDimDef->zones];
1407 schoenebeck 347 uint8_t bits[8] = { 0 };
1408 schoenebeck 2 int previousUpperLimit = -1;
1409     for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1410     bits[i] = velocityZone;
1411 schoenebeck 347 DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
1412 schoenebeck 2
1413     pDimDef->ranges[velocityZone].low = previousUpperLimit + 1;
1414     pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
1415     previousUpperLimit = pDimDef->ranges[velocityZone].high;
1416     // fill velocity table
1417     for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
1418     VelocityTable[i] = velocityZone;
1419     }
1420     }
1421     }
1422     }
1423     }
1424    
1425 schoenebeck 317 // jump to start of the wave pool indices (if not already there)
1426     File* file = (File*) GetParent()->GetParent();
1427     if (file->pVersion && file->pVersion->major == 3)
1428     _3lnk->SetPos(68); // version 3 has a different 3lnk structure
1429     else
1430     _3lnk->SetPos(44);
1431    
1432 schoenebeck 2 // load sample references
1433     for (uint i = 0; i < DimensionRegions; i++) {
1434     uint32_t wavepoolindex = _3lnk->ReadUint32();
1435     pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
1436     }
1437     }
1438     else throw gig::Exception("Mandatory <3lnk> chunk not found.");
1439     }
1440    
1441     void Region::LoadDimensionRegions(RIFF::List* rgn) {
1442     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
1443     if (_3prg) {
1444     int dimensionRegionNr = 0;
1445     RIFF::List* _3ewl = _3prg->GetFirstSubList();
1446     while (_3ewl) {
1447     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
1448     pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
1449     dimensionRegionNr++;
1450     }
1451     _3ewl = _3prg->GetNextSubList();
1452     }
1453     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
1454     }
1455     }
1456    
1457     Region::~Region() {
1458     for (uint i = 0; i < Dimensions; i++) {
1459     if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1460     }
1461 schoenebeck 350 for (int i = 0; i < 256; i++) {
1462 schoenebeck 2 if (pDimensionRegions[i]) delete pDimensionRegions[i];
1463     }
1464     }
1465    
1466     /**
1467     * Use this method in your audio engine to get the appropriate dimension
1468     * region with it's articulation data for the current situation. Just
1469     * call the method with the current MIDI controller values and you'll get
1470     * the DimensionRegion with the appropriate articulation data for the
1471     * current situation (for this Region of course only). To do that you'll
1472     * first have to look which dimensions with which controllers and in
1473     * which order are defined for this Region when you load the .gig file.
1474     * Special cases are e.g. layer or channel dimensions where you just put
1475     * in the index numbers instead of a MIDI controller value (means 0 for
1476     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
1477     * etc.).
1478     *
1479 schoenebeck 347 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
1480 schoenebeck 2 * @returns adress to the DimensionRegion for the given situation
1481     * @see pDimensionDefinitions
1482     * @see Dimensions
1483     */
1484 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
1485     uint8_t bits[8] = { 0 };
1486 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
1487 schoenebeck 347 bits[i] = DimValues[i];
1488 schoenebeck 2 switch (pDimensionDefinitions[i].split_type) {
1489     case split_type_normal:
1490     bits[i] /= pDimensionDefinitions[i].zone_size;
1491     break;
1492     case split_type_customvelocity:
1493     bits[i] = VelocityTable[bits[i]];
1494     break;
1495 schoenebeck 241 case split_type_bit: // the value is already the sought dimension bit number
1496     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
1497     bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
1498     break;
1499 schoenebeck 2 }
1500     }
1501 schoenebeck 347 return GetDimensionRegionByBit(bits);
1502 schoenebeck 2 }
1503    
1504     /**
1505     * Returns the appropriate DimensionRegion for the given dimension bit
1506     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1507     * instead of calling this method directly!
1508     *
1509 schoenebeck 347 * @param DimBits Bit numbers for dimension 0 to 7
1510 schoenebeck 2 * @returns adress to the DimensionRegion for the given dimension
1511     * bit numbers
1512     * @see GetDimensionRegionByValue()
1513     */
1514 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
1515     return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
1516     << pDimensionDefinitions[5].bits | DimBits[5])
1517     << pDimensionDefinitions[4].bits | DimBits[4])
1518     << pDimensionDefinitions[3].bits | DimBits[3])
1519     << pDimensionDefinitions[2].bits | DimBits[2])
1520     << pDimensionDefinitions[1].bits | DimBits[1])
1521     << pDimensionDefinitions[0].bits | DimBits[0]];
1522 schoenebeck 2 }
1523    
1524     /**
1525     * Returns pointer address to the Sample referenced with this region.
1526     * This is the global Sample for the entire Region (not sure if this is
1527     * actually used by the Gigasampler engine - I would only use the Sample
1528     * referenced by the appropriate DimensionRegion instead of this sample).
1529     *
1530     * @returns address to Sample or NULL if there is no reference to a
1531     * sample saved in the .gig file
1532     */
1533     Sample* Region::GetSample() {
1534     if (pSample) return static_cast<gig::Sample*>(pSample);
1535     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1536     }
1537    
1538     Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
1539 schoenebeck 352 if ((int32_t)WavePoolTableIndex == -1) return NULL;
1540 schoenebeck 2 File* file = (File*) GetParent()->GetParent();
1541     unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1542     Sample* sample = file->GetFirstSample();
1543     while (sample) {
1544     if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
1545     sample = file->GetNextSample();
1546     }
1547     return NULL;
1548     }
1549    
1550    
1551    
1552     // *************** Instrument ***************
1553     // *
1554    
1555     Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {
1556     // Initialization
1557     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1558     RegionIndex = -1;
1559    
1560     // Loading
1561     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
1562     if (lart) {
1563     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
1564     if (_3ewg) {
1565     EffectSend = _3ewg->ReadUint16();
1566     Attenuation = _3ewg->ReadInt32();
1567     FineTune = _3ewg->ReadInt16();
1568     PitchbendRange = _3ewg->ReadInt16();
1569     uint8_t dimkeystart = _3ewg->ReadUint8();
1570     PianoReleaseMode = dimkeystart & 0x01;
1571     DimensionKeyRange.low = dimkeystart >> 1;
1572     DimensionKeyRange.high = _3ewg->ReadUint8();
1573     }
1574     else throw gig::Exception("Mandatory <3ewg> chunk not found.");
1575     }
1576     else throw gig::Exception("Mandatory <lart> list chunk not found.");
1577    
1578     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1579     if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1580     pRegions = new Region*[Regions];
1581 schoenebeck 350 for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;
1582 schoenebeck 2 RIFF::List* rgn = lrgn->GetFirstSubList();
1583     unsigned int iRegion = 0;
1584     while (rgn) {
1585     if (rgn->GetListType() == LIST_TYPE_RGN) {
1586     pRegions[iRegion] = new Region(this, rgn);
1587     iRegion++;
1588     }
1589     rgn = lrgn->GetNextSubList();
1590     }
1591    
1592     // Creating Region Key Table for fast lookup
1593     for (uint iReg = 0; iReg < Regions; iReg++) {
1594     for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {
1595     RegionKeyTable[iKey] = pRegions[iReg];
1596     }
1597     }
1598     }
1599    
1600     Instrument::~Instrument() {
1601     for (uint i = 0; i < Regions; i++) {
1602     if (pRegions) {
1603     if (pRegions[i]) delete (pRegions[i]);
1604     }
1605     }
1606 schoenebeck 350 if (pRegions) delete[] pRegions;
1607 schoenebeck 2 }
1608    
1609     /**
1610     * Returns the appropriate Region for a triggered note.
1611     *
1612     * @param Key MIDI Key number of triggered note / key (0 - 127)
1613     * @returns pointer adress to the appropriate Region or NULL if there
1614     * there is no Region defined for the given \a Key
1615     */
1616     Region* Instrument::GetRegion(unsigned int Key) {
1617     if (!pRegions || Key > 127) return NULL;
1618     return RegionKeyTable[Key];
1619     /*for (int i = 0; i < Regions; i++) {
1620     if (Key <= pRegions[i]->KeyRange.high &&
1621     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
1622     }
1623     return NULL;*/
1624     }
1625    
1626     /**
1627     * Returns the first Region of the instrument. You have to call this
1628     * method once before you use GetNextRegion().
1629     *
1630     * @returns pointer address to first region or NULL if there is none
1631     * @see GetNextRegion()
1632     */
1633     Region* Instrument::GetFirstRegion() {
1634     if (!Regions) return NULL;
1635     RegionIndex = 1;
1636     return pRegions[0];
1637     }
1638    
1639     /**
1640     * Returns the next Region of the instrument. You have to call
1641     * GetFirstRegion() once before you can use this method. By calling this
1642     * method multiple times it iterates through the available Regions.
1643     *
1644     * @returns pointer address to the next region or NULL if end reached
1645     * @see GetFirstRegion()
1646     */
1647     Region* Instrument::GetNextRegion() {
1648 persson 365 if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;
1649 schoenebeck 2 return pRegions[RegionIndex++];
1650     }
1651    
1652    
1653    
1654     // *************** File ***************
1655     // *
1656    
1657     File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
1658     pSamples = NULL;
1659     pInstruments = NULL;
1660     }
1661    
1662 schoenebeck 350 File::~File() {
1663     // free samples
1664     if (pSamples) {
1665     SamplesIterator = pSamples->begin();
1666     while (SamplesIterator != pSamples->end() ) {
1667     delete (*SamplesIterator);
1668     SamplesIterator++;
1669     }
1670     pSamples->clear();
1671 schoenebeck 355 delete pSamples;
1672 schoenebeck 350
1673     }
1674     // free instruments
1675     if (pInstruments) {
1676     InstrumentsIterator = pInstruments->begin();
1677     while (InstrumentsIterator != pInstruments->end() ) {
1678     delete (*InstrumentsIterator);
1679     InstrumentsIterator++;
1680     }
1681     pInstruments->clear();
1682 schoenebeck 355 delete pInstruments;
1683 schoenebeck 350 }
1684     }
1685    
1686 schoenebeck 2 Sample* File::GetFirstSample() {
1687     if (!pSamples) LoadSamples();
1688     if (!pSamples) return NULL;
1689     SamplesIterator = pSamples->begin();
1690     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1691     }
1692    
1693     Sample* File::GetNextSample() {
1694     if (!pSamples) return NULL;
1695     SamplesIterator++;
1696     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1697     }
1698    
1699     void File::LoadSamples() {
1700     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1701     if (wvpl) {
1702     unsigned long wvplFileOffset = wvpl->GetFilePos();
1703     RIFF::List* wave = wvpl->GetFirstSubList();
1704     while (wave) {
1705     if (wave->GetListType() == LIST_TYPE_WAVE) {
1706     if (!pSamples) pSamples = new SampleList;
1707     unsigned long waveFileOffset = wave->GetFilePos();
1708     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1709     }
1710     wave = wvpl->GetNextSubList();
1711     }
1712     }
1713     else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1714     }
1715    
1716     Instrument* File::GetFirstInstrument() {
1717     if (!pInstruments) LoadInstruments();
1718     if (!pInstruments) return NULL;
1719     InstrumentsIterator = pInstruments->begin();
1720     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1721     }
1722    
1723     Instrument* File::GetNextInstrument() {
1724     if (!pInstruments) return NULL;
1725     InstrumentsIterator++;
1726     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1727     }
1728    
1729 schoenebeck 21 /**
1730     * Returns the instrument with the given index.
1731     *
1732     * @returns sought instrument or NULL if there's no such instrument
1733     */
1734     Instrument* File::GetInstrument(uint index) {
1735     if (!pInstruments) LoadInstruments();
1736     if (!pInstruments) return NULL;
1737     InstrumentsIterator = pInstruments->begin();
1738     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
1739     if (i == index) return *InstrumentsIterator;
1740     InstrumentsIterator++;
1741     }
1742     return NULL;
1743     }
1744    
1745 schoenebeck 2 void File::LoadInstruments() {
1746     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1747     if (lstInstruments) {
1748     RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1749     while (lstInstr) {
1750     if (lstInstr->GetListType() == LIST_TYPE_INS) {
1751     if (!pInstruments) pInstruments = new InstrumentList;
1752     pInstruments->push_back(new Instrument(this, lstInstr));
1753     }
1754     lstInstr = lstInstruments->GetNextSubList();
1755     }
1756     }
1757     else throw gig::Exception("Mandatory <lins> list chunk not found.");
1758     }
1759    
1760    
1761    
1762     // *************** Exception ***************
1763     // *
1764    
1765     Exception::Exception(String Message) : DLS::Exception(Message) {
1766     }
1767    
1768     void Exception::PrintMessage() {
1769     std::cout << "gig::Exception: " << Message << std::endl;
1770     }
1771    
1772     } // namespace gig

  ViewVC Help
Powered by ViewVC