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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 773 - (hide annotations) (download)
Sat Sep 17 14:24:45 2005 UTC (18 years, 6 months ago) by persson
File size: 90817 byte(s)
* fixed the GetVelocityCutoff function, it wasn't always using the
  VCFVelocityScale parameter when no cutoff controller was defined

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

  ViewVC Help
Powered by ViewVC