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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 231 - (hide annotations) (download)
Sun Sep 5 00:46:28 2004 UTC (19 years, 6 months ago) by schoenebeck
File size: 69899 byte(s)
* src/gig.h, src/gig.cpp: fixed / improved accuracy of all three velocity
  to volume transformation functions (a.k.a. 'nonlinear','linear',
  'special'), denormals are filtered from the velocity to volume tables
* src/gigdump.cpp: added printout of velocity response curve parameters

1 schoenebeck 2 /***************************************************************************
2     * *
3     * libgig - C++ cross-platform Gigasampler format file loader library *
4     * *
5 schoenebeck 55 * Copyright (C) 2003, 2004 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     namespace gig {
27    
28     // *************** Sample ***************
29     // *
30    
31     unsigned int Sample::Instances = 0;
32     void* Sample::pDecompressionBuffer = NULL;
33     unsigned long Sample::DecompressionBufferSize = 0;
34    
35     Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
36     Instances++;
37    
38     RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
39     if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
40     SampleGroup = _3gix->ReadInt16();
41    
42     RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
43     if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
44     Manufacturer = smpl->ReadInt32();
45     Product = smpl->ReadInt32();
46     SamplePeriod = smpl->ReadInt32();
47     MIDIUnityNote = smpl->ReadInt32();
48 schoenebeck 21 FineTune = smpl->ReadInt32();
49 schoenebeck 2 smpl->Read(&SMPTEFormat, 1, 4);
50     SMPTEOffset = smpl->ReadInt32();
51     Loops = smpl->ReadInt32();
52 schoenebeck 21 uint32_t manufByt = smpl->ReadInt32();
53 schoenebeck 2 LoopID = smpl->ReadInt32();
54     smpl->Read(&LoopType, 1, 4);
55     LoopStart = smpl->ReadInt32();
56     LoopEnd = smpl->ReadInt32();
57     LoopFraction = smpl->ReadInt32();
58     LoopPlayCount = smpl->ReadInt32();
59    
60     FrameTable = NULL;
61     SamplePos = 0;
62     RAMCache.Size = 0;
63     RAMCache.pStart = NULL;
64     RAMCache.NullExtensionSize = 0;
65    
66     Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));
67     if (Compressed) {
68     ScanCompressedSample();
69     if (!pDecompressionBuffer) {
70     pDecompressionBuffer = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];
71     DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;
72     }
73     }
74     FrameOffset = 0; // just for streaming compressed samples
75 schoenebeck 21
76 schoenebeck 27 LoopSize = LoopEnd - LoopStart;
77 schoenebeck 2 }
78    
79     /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
80     void Sample::ScanCompressedSample() {
81     //TODO: we have to add some more scans here (e.g. determine compression rate)
82     this->SamplesTotal = 0;
83     std::list<unsigned long> frameOffsets;
84    
85     // Scanning
86     pCkData->SetPos(0);
87     while (pCkData->GetState() == RIFF::stream_ready) {
88     frameOffsets.push_back(pCkData->GetPos());
89     int16_t compressionmode = pCkData->ReadInt16();
90     this->SamplesTotal += 2048;
91     switch (compressionmode) {
92     case 1: // left channel compressed
93     case 256: // right channel compressed
94     pCkData->SetPos(6148, RIFF::stream_curpos);
95     break;
96     case 257: // both channels compressed
97     pCkData->SetPos(4104, RIFF::stream_curpos);
98     break;
99     default: // both channels uncompressed
100     pCkData->SetPos(8192, RIFF::stream_curpos);
101     }
102     }
103     pCkData->SetPos(0);
104    
105     //FIXME: only seen compressed samples with 16 bit stereo so far
106     this->FrameSize = 4;
107     this->BitDepth = 16;
108    
109     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
110     if (FrameTable) delete[] FrameTable;
111     FrameTable = new unsigned long[frameOffsets.size()];
112     std::list<unsigned long>::iterator end = frameOffsets.end();
113     std::list<unsigned long>::iterator iter = frameOffsets.begin();
114     for (int i = 0; iter != end; i++, iter++) {
115     FrameTable[i] = *iter;
116     }
117     }
118    
119     /**
120     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
121     * ReleaseSampleData() to free the memory if you don't need the cached
122     * sample data anymore.
123     *
124     * @returns buffer_t structure with start address and size of the buffer
125     * in bytes
126     * @see ReleaseSampleData(), Read(), SetPos()
127     */
128     buffer_t Sample::LoadSampleData() {
129     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
130     }
131    
132     /**
133     * Reads (uncompresses if needed) and caches the first \a SampleCount
134     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
135     * memory space if you don't need the cached samples anymore. There is no
136     * guarantee that exactly \a SampleCount samples will be cached; this is
137     * not an error. The size will be eventually truncated e.g. to the
138     * beginning of a frame of a compressed sample. This is done for
139     * efficiency reasons while streaming the wave by your sampler engine
140     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
141     * that will be returned to determine the actual cached samples, but note
142     * that the size is given in bytes! You get the number of actually cached
143     * samples by dividing it by the frame size of the sample:
144     *
145     * buffer_t buf = pSample->LoadSampleData(acquired_samples);
146     * long cachedsamples = buf.Size / pSample->FrameSize;
147     *
148     * @param SampleCount - number of sample points to load into RAM
149     * @returns buffer_t structure with start address and size of
150     * the cached sample data in bytes
151     * @see ReleaseSampleData(), Read(), SetPos()
152     */
153     buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
154     return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
155     }
156    
157     /**
158     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
159     * ReleaseSampleData() to free the memory if you don't need the cached
160     * sample data anymore.
161     * The method will add \a NullSamplesCount silence samples past the
162     * official buffer end (this won't affect the 'Size' member of the
163     * buffer_t structure, that means 'Size' always reflects the size of the
164     * actual sample data, the buffer might be bigger though). Silence
165     * samples past the official buffer are needed for differential
166     * algorithms that always have to take subsequent samples into account
167     * (resampling/interpolation would be an important example) and avoids
168     * memory access faults in such cases.
169     *
170     * @param NullSamplesCount - number of silence samples the buffer should
171     * be extended past it's data end
172     * @returns buffer_t structure with start address and
173     * size of the buffer in bytes
174     * @see ReleaseSampleData(), Read(), SetPos()
175     */
176     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
177     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
178     }
179    
180     /**
181     * Reads (uncompresses if needed) and caches the first \a SampleCount
182     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
183     * memory space if you don't need the cached samples anymore. There is no
184     * guarantee that exactly \a SampleCount samples will be cached; this is
185     * not an error. The size will be eventually truncated e.g. to the
186     * beginning of a frame of a compressed sample. This is done for
187     * efficiency reasons while streaming the wave by your sampler engine
188     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
189     * that will be returned to determine the actual cached samples, but note
190     * that the size is given in bytes! You get the number of actually cached
191     * samples by dividing it by the frame size of the sample:
192     *
193     * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
194     * long cachedsamples = buf.Size / pSample->FrameSize;
195     *
196     * The method will add \a NullSamplesCount silence samples past the
197     * official buffer end (this won't affect the 'Size' member of the
198     * buffer_t structure, that means 'Size' always reflects the size of the
199     * actual sample data, the buffer might be bigger though). Silence
200     * samples past the official buffer are needed for differential
201     * algorithms that always have to take subsequent samples into account
202     * (resampling/interpolation would be an important example) and avoids
203     * memory access faults in such cases.
204     *
205     * @param SampleCount - number of sample points to load into RAM
206     * @param NullSamplesCount - number of silence samples the buffer should
207     * be extended past it's data end
208     * @returns buffer_t structure with start address and
209     * size of the cached sample data in bytes
210     * @see ReleaseSampleData(), Read(), SetPos()
211     */
212     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
213     if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
214     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
215     unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
216     RAMCache.pStart = new int8_t[allocationsize];
217     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
218     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
219     // fill the remaining buffer space with silence samples
220     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
221     return GetCache();
222     }
223    
224     /**
225     * Returns current cached sample points. A buffer_t structure will be
226     * returned which contains address pointer to the begin of the cache and
227     * the size of the cached sample data in bytes. Use
228     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
229     * RAM.
230     *
231     * @returns buffer_t structure with current cached sample points
232     * @see LoadSampleData();
233     */
234     buffer_t Sample::GetCache() {
235     // return a copy of the buffer_t structure
236     buffer_t result;
237     result.Size = this->RAMCache.Size;
238     result.pStart = this->RAMCache.pStart;
239     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
240     return result;
241     }
242    
243     /**
244     * Frees the cached sample from RAM if loaded with
245     * <i>LoadSampleData()</i> previously.
246     *
247     * @see LoadSampleData();
248     */
249     void Sample::ReleaseSampleData() {
250     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
251     RAMCache.pStart = NULL;
252     RAMCache.Size = 0;
253     }
254    
255     /**
256     * Sets the position within the sample (in sample points, not in
257     * bytes). Use this method and <i>Read()</i> if you don't want to load
258     * the sample into RAM, thus for disk streaming.
259     *
260     * Although the original Gigasampler engine doesn't allow positioning
261     * within compressed samples, I decided to implement it. Even though
262     * the Gigasampler format doesn't allow to define loops for compressed
263     * samples at the moment, positioning within compressed samples might be
264     * interesting for some sampler engines though. The only drawback about
265     * my decision is that it takes longer to load compressed gig Files on
266     * startup, because it's neccessary to scan the samples for some
267     * mandatory informations. But I think as it doesn't affect the runtime
268     * efficiency, nobody will have a problem with that.
269     *
270     * @param SampleCount number of sample points to jump
271     * @param Whence optional: to which relation \a SampleCount refers
272     * to, if omited <i>RIFF::stream_start</i> is assumed
273     * @returns the new sample position
274     * @see Read()
275     */
276     unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
277     if (Compressed) {
278     switch (Whence) {
279     case RIFF::stream_curpos:
280     this->SamplePos += SampleCount;
281     break;
282     case RIFF::stream_end:
283     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
284     break;
285     case RIFF::stream_backward:
286     this->SamplePos -= SampleCount;
287     break;
288     case RIFF::stream_start: default:
289     this->SamplePos = SampleCount;
290     break;
291     }
292     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
293    
294     unsigned long frame = this->SamplePos / 2048; // to which frame to jump
295     this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
296     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
297     return this->SamplePos;
298     }
299     else { // not compressed
300     unsigned long orderedBytes = SampleCount * this->FrameSize;
301     unsigned long result = pCkData->SetPos(orderedBytes, Whence);
302     return (result == orderedBytes) ? SampleCount
303     : result / this->FrameSize;
304     }
305     }
306    
307     /**
308     * Returns the current position in the sample (in sample points).
309     */
310     unsigned long Sample::GetPos() {
311     if (Compressed) return SamplePos;
312     else return pCkData->GetPos() / FrameSize;
313     }
314    
315     /**
316 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
317     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
318     * the position within the sample respectively, this method honors the
319     * looping informations of the sample (if any). The sample wave stream
320     * will be decompressed on the fly if using a compressed sample. Use this
321     * method if you don't want to load the sample into RAM, thus for disk
322     * streaming. All this methods needs to know to proceed with streaming
323     * for the next time you call this method is stored in \a pPlaybackState.
324     * You have to allocate and initialize the playback_state_t structure by
325     * yourself before you use it to stream a sample:
326     *
327     * <i>
328     * gig::playback_state_t playbackstate; <br>
329     * playbackstate.position = 0; <br>
330     * playbackstate.reverse = false; <br>
331     * playbackstate.loop_cycles_left = pSample->LoopPlayCount; <br>
332     * </i>
333     *
334     * You don't have to take care of things like if there is actually a loop
335     * defined or if the current read position is located within a loop area.
336     * The method already handles such cases by itself.
337     *
338     * @param pBuffer destination buffer
339     * @param SampleCount number of sample points to read
340     * @param pPlaybackState will be used to store and reload the playback
341     * state for the next ReadAndLoop() call
342     * @returns number of successfully read sample points
343     */
344     unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {
345     unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
346     uint8_t* pDst = (uint8_t*) pBuffer;
347    
348     SetPos(pPlaybackState->position); // recover position from the last time
349    
350     if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined
351    
352     switch (this->LoopType) {
353    
354     case loop_type_bidirectional: { //TODO: not tested yet!
355     do {
356     // if not endless loop check if max. number of loop cycles have been passed
357     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
358    
359     if (!pPlaybackState->reverse) { // forward playback
360     do {
361     samplestoloopend = this->LoopEnd - GetPos();
362     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
363     samplestoread -= readsamples;
364     totalreadsamples += readsamples;
365     if (readsamples == samplestoloopend) {
366     pPlaybackState->reverse = true;
367     break;
368     }
369     } while (samplestoread && readsamples);
370     }
371     else { // backward playback
372    
373     // as we can only read forward from disk, we have to
374     // determine the end position within the loop first,
375     // read forward from that 'end' and finally after
376     // reading, swap all sample frames so it reflects
377     // backward playback
378    
379     unsigned long swapareastart = totalreadsamples;
380     unsigned long loopoffset = GetPos() - this->LoopStart;
381     unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
382     unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
383    
384     SetPos(reverseplaybackend);
385    
386     // read samples for backward playback
387     do {
388     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);
389     samplestoreadinloop -= readsamples;
390     samplestoread -= readsamples;
391     totalreadsamples += readsamples;
392     } while (samplestoreadinloop && readsamples);
393    
394     SetPos(reverseplaybackend); // pretend we really read backwards
395    
396     if (reverseplaybackend == this->LoopStart) {
397     pPlaybackState->loop_cycles_left--;
398     pPlaybackState->reverse = false;
399     }
400    
401     // reverse the sample frames for backward playback
402     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
403     }
404     } while (samplestoread && readsamples);
405     break;
406     }
407    
408     case loop_type_backward: { // TODO: not tested yet!
409     // forward playback (not entered the loop yet)
410     if (!pPlaybackState->reverse) do {
411     samplestoloopend = this->LoopEnd - GetPos();
412     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
413     samplestoread -= readsamples;
414     totalreadsamples += readsamples;
415     if (readsamples == samplestoloopend) {
416     pPlaybackState->reverse = true;
417     break;
418     }
419     } while (samplestoread && readsamples);
420    
421     if (!samplestoread) break;
422    
423     // as we can only read forward from disk, we have to
424     // determine the end position within the loop first,
425     // read forward from that 'end' and finally after
426     // reading, swap all sample frames so it reflects
427     // backward playback
428    
429     unsigned long swapareastart = totalreadsamples;
430     unsigned long loopoffset = GetPos() - this->LoopStart;
431     unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)
432     : samplestoread;
433     unsigned long reverseplaybackend = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);
434    
435     SetPos(reverseplaybackend);
436    
437     // read samples for backward playback
438     do {
439     // if not endless loop check if max. number of loop cycles have been passed
440     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
441     samplestoloopend = this->LoopEnd - GetPos();
442     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));
443     samplestoreadinloop -= readsamples;
444     samplestoread -= readsamples;
445     totalreadsamples += readsamples;
446     if (readsamples == samplestoloopend) {
447     pPlaybackState->loop_cycles_left--;
448     SetPos(this->LoopStart);
449     }
450     } while (samplestoreadinloop && readsamples);
451    
452     SetPos(reverseplaybackend); // pretend we really read backwards
453    
454     // reverse the sample frames for backward playback
455     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
456     break;
457     }
458    
459     default: case loop_type_normal: {
460     do {
461     // if not endless loop check if max. number of loop cycles have been passed
462     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
463     samplestoloopend = this->LoopEnd - GetPos();
464     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));
465     samplestoread -= readsamples;
466     totalreadsamples += readsamples;
467     if (readsamples == samplestoloopend) {
468     pPlaybackState->loop_cycles_left--;
469     SetPos(this->LoopStart);
470     }
471     } while (samplestoread && readsamples);
472     break;
473     }
474     }
475     }
476    
477     // read on without looping
478     if (samplestoread) do {
479     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);
480     samplestoread -= readsamples;
481     totalreadsamples += readsamples;
482     } while (readsamples && samplestoread);
483    
484     // store current position
485     pPlaybackState->position = GetPos();
486    
487     return totalreadsamples;
488     }
489    
490     /**
491 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
492     * position into the buffer pointed by \a pBuffer and increments the
493     * position within the sample. The sample wave stream will be
494     * decompressed on the fly if using a compressed sample. Use this method
495     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
496     * thus for disk streaming.
497     *
498     * @param pBuffer destination buffer
499     * @param SampleCount number of sample points to read
500     * @returns number of successfully read sample points
501     * @see SetPos()
502     */
503     unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
504 schoenebeck 21 if (SampleCount == 0) return 0;
505 schoenebeck 11 if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?
506 schoenebeck 2 else { //FIXME: no support for mono compressed samples yet, are there any?
507 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
508 schoenebeck 2 //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate
509     // best case needed buffer size (all frames compressed)
510     unsigned long assumedsize = (SampleCount << 1) + // *2 (16 Bit, stereo, but assume all frames compressed)
511     (SampleCount >> 10) + // 10 bytes header per 2048 sample points
512     8194, // at least one worst case sample frame
513     remainingbytes = 0, // remaining bytes in the local buffer
514     remainingsamples = SampleCount,
515     copysamples;
516     int currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
517     this->FrameOffset = 0;
518    
519     if (assumedsize > this->DecompressionBufferSize) {
520     // local buffer reallocation - hope this won't happen
521     if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;
522     this->pDecompressionBuffer = new int8_t[assumedsize << 1]; // double of current needed size
523     this->DecompressionBufferSize = assumedsize;
524     }
525    
526     int16_t compressionmode, left, dleft, right, dright;
527     int8_t* pSrc = (int8_t*) this->pDecompressionBuffer;
528     int16_t* pDst = (int16_t*) pBuffer;
529     remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
530    
531     while (remainingsamples) {
532    
533     // reload from disk to local buffer if needed
534     if (remainingbytes < 8194) {
535     if (pCkData->GetState() != RIFF::stream_ready) {
536 schoenebeck 11 this->SamplePos = this->SamplesTotal;
537 schoenebeck 2 return (SampleCount - remainingsamples);
538     }
539     assumedsize = remainingsamples;
540     assumedsize = (assumedsize << 1) + // *2 (16 Bit, stereo, but assume all frames compressed)
541     (assumedsize >> 10) + // 10 bytes header per 2048 sample points
542     8194; // at least one worst case sample frame
543     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
544     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
545     remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);
546     pSrc = (int8_t*) this->pDecompressionBuffer;
547     }
548    
549     // determine how many samples in this frame to skip and read
550     if (remainingsamples >= 2048) {
551     copysamples = 2048 - currentframeoffset;
552     remainingsamples -= copysamples;
553     }
554     else {
555     copysamples = remainingsamples;
556     if (currentframeoffset + copysamples > 2048) {
557     copysamples = 2048 - currentframeoffset;
558     remainingsamples -= copysamples;
559     }
560     else {
561     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
562     remainingsamples = 0;
563     this->FrameOffset = currentframeoffset + copysamples;
564     }
565     }
566    
567     // decompress and copy current frame from local buffer to destination buffer
568     compressionmode = *(int16_t*)pSrc; pSrc+=2;
569     switch (compressionmode) {
570     case 1: // left channel compressed
571     remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)
572     if (!remainingsamples && copysamples == 2048)
573     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
574    
575     left = *(int16_t*)pSrc; pSrc+=2;
576     dleft = *(int16_t*)pSrc; pSrc+=2;
577     while (currentframeoffset) {
578     dleft -= *pSrc;
579     left -= dleft;
580     pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)
581     currentframeoffset--;
582     }
583     while (copysamples) {
584     dleft -= *pSrc; pSrc++;
585     left -= dleft;
586     *pDst = left; pDst++;
587     *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;
588     copysamples--;
589     }
590     break;
591     case 256: // right channel compressed
592     remainingbytes -= 6150; // (left 16 bit, right 8 bit, +6 byte header)
593     if (!remainingsamples && copysamples == 2048)
594     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
595    
596     right = *(int16_t*)pSrc; pSrc+=2;
597     dright = *(int16_t*)pSrc; pSrc+=2;
598     if (currentframeoffset) {
599     pSrc+=2; // skip uncompressed left channel, now we can increment by 3
600     while (currentframeoffset) {
601     dright -= *pSrc;
602     right -= dright;
603     pSrc+=3; // 8 bit right channel, skip uncompressed left channel (16 bit)
604     currentframeoffset--;
605     }
606     pSrc-=2; // back aligned to left channel
607     }
608     while (copysamples) {
609     *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;
610     dright -= *pSrc; pSrc++;
611     right -= dright;
612     *pDst = right; pDst++;
613     copysamples--;
614     }
615     break;
616     case 257: // both channels compressed
617     remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)
618     if (!remainingsamples && copysamples == 2048)
619     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
620    
621     left = *(int16_t*)pSrc; pSrc+=2;
622     dleft = *(int16_t*)pSrc; pSrc+=2;
623     right = *(int16_t*)pSrc; pSrc+=2;
624     dright = *(int16_t*)pSrc; pSrc+=2;
625     while (currentframeoffset) {
626     dleft -= *pSrc; pSrc++;
627     left -= dleft;
628     dright -= *pSrc; pSrc++;
629     right -= dright;
630     currentframeoffset--;
631     }
632     while (copysamples) {
633     dleft -= *pSrc; pSrc++;
634     left -= dleft;
635     dright -= *pSrc; pSrc++;
636     right -= dright;
637     *pDst = left; pDst++;
638     *pDst = right; pDst++;
639     copysamples--;
640     }
641     break;
642     default: // both channels uncompressed
643     remainingbytes -= 8194; // (left 16 bit, right 16 bit, +2 byte header)
644     if (!remainingsamples && copysamples == 2048)
645     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
646    
647     pSrc += currentframeoffset << 2;
648     currentframeoffset = 0;
649     memcpy(pDst, pSrc, copysamples << 2);
650     pDst += copysamples << 1;
651     pSrc += copysamples << 2;
652     break;
653     }
654     }
655     this->SamplePos += (SampleCount - remainingsamples);
656 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
657 schoenebeck 2 return (SampleCount - remainingsamples);
658     }
659     }
660    
661     Sample::~Sample() {
662     Instances--;
663     if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;
664     if (FrameTable) delete[] FrameTable;
665     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
666     }
667    
668    
669    
670     // *************** DimensionRegion ***************
671     // *
672    
673 schoenebeck 16 uint DimensionRegion::Instances = 0;
674     DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
675    
676 schoenebeck 2 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
677 schoenebeck 16 Instances++;
678    
679 schoenebeck 2 memcpy(&Crossfade, &SamplerOptions, 4);
680 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
681 schoenebeck 2
682     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
683     _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?
684     LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
685     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
686     _3ewa->ReadInt16(); // unknown
687     LFO1InternalDepth = _3ewa->ReadUint16();
688     _3ewa->ReadInt16(); // unknown
689     LFO3InternalDepth = _3ewa->ReadInt16();
690     _3ewa->ReadInt16(); // unknown
691     LFO1ControlDepth = _3ewa->ReadUint16();
692     _3ewa->ReadInt16(); // unknown
693     LFO3ControlDepth = _3ewa->ReadInt16();
694     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
695     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
696     _3ewa->ReadInt16(); // unknown
697     EG1Sustain = _3ewa->ReadUint16();
698     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
699 schoenebeck 36 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
700 schoenebeck 2 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
701     EG1ControllerInvert = eg1ctrloptions & 0x01;
702     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
703     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
704     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
705 schoenebeck 36 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
706 schoenebeck 2 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
707     EG2ControllerInvert = eg2ctrloptions & 0x01;
708     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
709     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
710     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
711     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
712     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
713     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
714     _3ewa->ReadInt16(); // unknown
715     EG2Sustain = _3ewa->ReadUint16();
716     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
717     _3ewa->ReadInt16(); // unknown
718     LFO2ControlDepth = _3ewa->ReadUint16();
719     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
720     _3ewa->ReadInt16(); // unknown
721     LFO2InternalDepth = _3ewa->ReadUint16();
722     int32_t eg1decay2 = _3ewa->ReadInt32();
723     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
724     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
725     _3ewa->ReadInt16(); // unknown
726     EG1PreAttack = _3ewa->ReadUint16();
727     int32_t eg2decay2 = _3ewa->ReadInt32();
728     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
729     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
730     _3ewa->ReadInt16(); // unknown
731     EG2PreAttack = _3ewa->ReadUint16();
732     uint8_t velocityresponse = _3ewa->ReadUint8();
733     if (velocityresponse < 5) {
734     VelocityResponseCurve = curve_type_nonlinear;
735     VelocityResponseDepth = velocityresponse;
736     }
737     else if (velocityresponse < 10) {
738     VelocityResponseCurve = curve_type_linear;
739     VelocityResponseDepth = velocityresponse - 5;
740     }
741     else if (velocityresponse < 15) {
742     VelocityResponseCurve = curve_type_special;
743     VelocityResponseDepth = velocityresponse - 10;
744     }
745     else {
746     VelocityResponseCurve = curve_type_unknown;
747     VelocityResponseDepth = 0;
748     }
749     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
750     if (releasevelocityresponse < 5) {
751     ReleaseVelocityResponseCurve = curve_type_nonlinear;
752     ReleaseVelocityResponseDepth = releasevelocityresponse;
753     }
754     else if (releasevelocityresponse < 10) {
755     ReleaseVelocityResponseCurve = curve_type_linear;
756     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
757     }
758     else if (releasevelocityresponse < 15) {
759     ReleaseVelocityResponseCurve = curve_type_special;
760     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
761     }
762     else {
763     ReleaseVelocityResponseCurve = curve_type_unknown;
764     ReleaseVelocityResponseDepth = 0;
765     }
766     VelocityResponseCurveScaling = _3ewa->ReadUint8();
767 schoenebeck 36 AttenuationControllerThreshold = _3ewa->ReadInt8();
768 schoenebeck 2 _3ewa->ReadInt32(); // unknown
769     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
770     _3ewa->ReadInt16(); // unknown
771     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
772     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
773     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
774     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
775     else DimensionBypass = dim_bypass_ctrl_none;
776     uint8_t pan = _3ewa->ReadUint8();
777     Pan = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;
778     SelfMask = _3ewa->ReadInt8() & 0x01;
779     _3ewa->ReadInt8(); // unknown
780     uint8_t lfo3ctrl = _3ewa->ReadUint8();
781     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
782     LFO3Sync = lfo3ctrl & 0x20; // bit 5
783 schoenebeck 36 InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
784 schoenebeck 2 if (VCFType == vcf_type_lowpass) {
785     if (lfo3ctrl & 0x40) // bit 6
786     VCFType = vcf_type_lowpassturbo;
787     }
788 schoenebeck 36 AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
789 schoenebeck 2 uint8_t lfo2ctrl = _3ewa->ReadUint8();
790     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
791     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
792     LFO2Sync = lfo2ctrl & 0x20; // bit 5
793     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
794     uint8_t lfo1ctrl = _3ewa->ReadUint8();
795     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
796     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
797     LFO1Sync = lfo1ctrl & 0x40; // bit 6
798     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
799     : vcf_res_ctrl_none;
800     uint16_t eg3depth = _3ewa->ReadUint16();
801     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
802     : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
803     _3ewa->ReadInt16(); // unknown
804     ChannelOffset = _3ewa->ReadUint8() / 4;
805     uint8_t regoptions = _3ewa->ReadUint8();
806     MSDecode = regoptions & 0x01; // bit 0
807     SustainDefeat = regoptions & 0x02; // bit 1
808     _3ewa->ReadInt16(); // unknown
809     VelocityUpperLimit = _3ewa->ReadInt8();
810     _3ewa->ReadInt8(); // unknown
811     _3ewa->ReadInt16(); // unknown
812     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
813     _3ewa->ReadInt8(); // unknown
814     _3ewa->ReadInt8(); // unknown
815     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
816     uint8_t vcfcutoff = _3ewa->ReadUint8();
817     VCFEnabled = vcfcutoff & 0x80; // bit 7
818     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
819     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
820     VCFVelocityScale = _3ewa->ReadUint8();
821     _3ewa->ReadInt8(); // unknown
822     uint8_t vcfresonance = _3ewa->ReadUint8();
823     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
824     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
825     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
826     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
827     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
828     uint8_t vcfvelocity = _3ewa->ReadUint8();
829     VCFVelocityDynamicRange = vcfvelocity % 5;
830     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
831     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
832 schoenebeck 16
833     // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet
834     uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;
835     if (pVelocityTables->count(tableKey)) { // if key exists
836     pVelocityAttenuationTable = (*pVelocityTables)[tableKey];
837     }
838     else {
839     pVelocityAttenuationTable = new double[128];
840     switch (VelocityResponseCurve) { // calculate the new table
841     case curve_type_nonlinear:
842     for (int velocity = 0; velocity < 128; velocity++) {
843     pVelocityAttenuationTable[velocity] =
844 schoenebeck 231 GIG_VELOCITY_TRANSFORM_NONLINEAR(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));
845     if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
846     else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;
847 schoenebeck 16 }
848     break;
849     case curve_type_linear:
850     for (int velocity = 0; velocity < 128; velocity++) {
851     pVelocityAttenuationTable[velocity] =
852 schoenebeck 231 GIG_VELOCITY_TRANSFORM_LINEAR(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));
853     if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
854     else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;
855 schoenebeck 16 }
856     break;
857     case curve_type_special:
858     for (int velocity = 0; velocity < 128; velocity++) {
859     pVelocityAttenuationTable[velocity] =
860 schoenebeck 231 GIG_VELOCITY_TRANSFORM_SPECIAL(((double)velocity),((double)VelocityResponseDepth),((double)VelocityResponseCurveScaling));
861     if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
862     else if (pVelocityAttenuationTable[velocity] < 1e-15) pVelocityAttenuationTable[velocity] = 0.0;
863 schoenebeck 16 }
864     break;
865     case curve_type_unknown:
866     default:
867     throw gig::Exception("Unknown transform curve type.");
868     }
869     (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
870     }
871 schoenebeck 2 }
872 schoenebeck 55
873 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
874     leverage_ctrl_t decodedcontroller;
875     switch (EncodedController) {
876     // special controller
877     case _lev_ctrl_none:
878     decodedcontroller.type = leverage_ctrl_t::type_none;
879     decodedcontroller.controller_number = 0;
880     break;
881     case _lev_ctrl_velocity:
882     decodedcontroller.type = leverage_ctrl_t::type_velocity;
883     decodedcontroller.controller_number = 0;
884     break;
885     case _lev_ctrl_channelaftertouch:
886     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
887     decodedcontroller.controller_number = 0;
888     break;
889 schoenebeck 55
890 schoenebeck 36 // ordinary MIDI control change controller
891     case _lev_ctrl_modwheel:
892     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
893     decodedcontroller.controller_number = 1;
894     break;
895     case _lev_ctrl_breath:
896     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
897     decodedcontroller.controller_number = 2;
898     break;
899     case _lev_ctrl_foot:
900     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
901     decodedcontroller.controller_number = 4;
902     break;
903     case _lev_ctrl_effect1:
904     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
905     decodedcontroller.controller_number = 12;
906     break;
907     case _lev_ctrl_effect2:
908     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
909     decodedcontroller.controller_number = 13;
910     break;
911     case _lev_ctrl_genpurpose1:
912     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
913     decodedcontroller.controller_number = 16;
914     break;
915     case _lev_ctrl_genpurpose2:
916     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
917     decodedcontroller.controller_number = 17;
918     break;
919     case _lev_ctrl_genpurpose3:
920     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
921     decodedcontroller.controller_number = 18;
922     break;
923     case _lev_ctrl_genpurpose4:
924     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
925     decodedcontroller.controller_number = 19;
926     break;
927     case _lev_ctrl_portamentotime:
928     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
929     decodedcontroller.controller_number = 5;
930     break;
931     case _lev_ctrl_sustainpedal:
932     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
933     decodedcontroller.controller_number = 64;
934     break;
935     case _lev_ctrl_portamento:
936     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
937     decodedcontroller.controller_number = 65;
938     break;
939     case _lev_ctrl_sostenutopedal:
940     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
941     decodedcontroller.controller_number = 66;
942     break;
943     case _lev_ctrl_softpedal:
944     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
945     decodedcontroller.controller_number = 67;
946     break;
947     case _lev_ctrl_genpurpose5:
948     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
949     decodedcontroller.controller_number = 80;
950     break;
951     case _lev_ctrl_genpurpose6:
952     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
953     decodedcontroller.controller_number = 81;
954     break;
955     case _lev_ctrl_genpurpose7:
956     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
957     decodedcontroller.controller_number = 82;
958     break;
959     case _lev_ctrl_genpurpose8:
960     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
961     decodedcontroller.controller_number = 83;
962     break;
963     case _lev_ctrl_effect1depth:
964     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
965     decodedcontroller.controller_number = 91;
966     break;
967     case _lev_ctrl_effect2depth:
968     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
969     decodedcontroller.controller_number = 92;
970     break;
971     case _lev_ctrl_effect3depth:
972     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
973     decodedcontroller.controller_number = 93;
974     break;
975     case _lev_ctrl_effect4depth:
976     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
977     decodedcontroller.controller_number = 94;
978     break;
979     case _lev_ctrl_effect5depth:
980     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
981     decodedcontroller.controller_number = 95;
982     break;
983 schoenebeck 55
984 schoenebeck 36 // unknown controller type
985     default:
986     throw gig::Exception("Unknown leverage controller type.");
987     }
988     return decodedcontroller;
989     }
990 schoenebeck 2
991 schoenebeck 16 DimensionRegion::~DimensionRegion() {
992     Instances--;
993     if (!Instances) {
994     // delete the velocity->volume tables
995     VelocityTableMap::iterator iter;
996     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
997     double* pTable = iter->second;
998     if (pTable) delete[] pTable;
999     }
1000     pVelocityTables->clear();
1001     delete pVelocityTables;
1002     pVelocityTables = NULL;
1003     }
1004     }
1005 schoenebeck 2
1006 schoenebeck 16 /**
1007     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1008     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1009     * and VelocityResponseCurveScaling) involved are taken into account to
1010     * calculate the amplitude factor. Use this method when a key was
1011     * triggered to get the volume with which the sample should be played
1012     * back.
1013     *
1014 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
1015     * @returns amplitude factor (between 0.0 and 1.0)
1016 schoenebeck 16 */
1017     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1018     return pVelocityAttenuationTable[MIDIKeyVelocity];
1019     }
1020 schoenebeck 2
1021 schoenebeck 16
1022    
1023 schoenebeck 2 // *************** Region ***************
1024     // *
1025    
1026     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
1027     // Initialization
1028     Dimensions = 0;
1029     for (int i = 0; i < 32; i++) {
1030     pDimensionRegions[i] = NULL;
1031     }
1032    
1033     // Actual Loading
1034    
1035     LoadDimensionRegions(rgnList);
1036    
1037     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1038     if (_3lnk) {
1039     DimensionRegions = _3lnk->ReadUint32();
1040     for (int i = 0; i < 5; i++) {
1041     dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1042     uint8_t bits = _3lnk->ReadUint8();
1043     if (dimension == dimension_none) { // inactive dimension
1044     pDimensionDefinitions[i].dimension = dimension_none;
1045     pDimensionDefinitions[i].bits = 0;
1046     pDimensionDefinitions[i].zones = 0;
1047     pDimensionDefinitions[i].split_type = split_type_bit;
1048     pDimensionDefinitions[i].ranges = NULL;
1049     pDimensionDefinitions[i].zone_size = 0;
1050     }
1051     else { // active dimension
1052     pDimensionDefinitions[i].dimension = dimension;
1053     pDimensionDefinitions[i].bits = bits;
1054     pDimensionDefinitions[i].zones = 0x01 << bits; // = pow(2,bits)
1055     pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1056     dimension == dimension_samplechannel) ? split_type_bit
1057     : split_type_normal;
1058     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
1059     pDimensionDefinitions[i].zone_size =
1060     (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1061     : 0;
1062     Dimensions++;
1063     }
1064     _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1065     }
1066    
1067     // check velocity dimension (if there is one) for custom defined zone ranges
1068     for (uint i = 0; i < Dimensions; i++) {
1069     dimension_def_t* pDimDef = pDimensionDefinitions + i;
1070     if (pDimDef->dimension == dimension_velocity) {
1071     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {
1072     // no custom defined ranges
1073     pDimDef->split_type = split_type_normal;
1074     pDimDef->ranges = NULL;
1075     }
1076     else { // custom defined ranges
1077     pDimDef->split_type = split_type_customvelocity;
1078     pDimDef->ranges = new range_t[pDimDef->zones];
1079     unsigned int bits[5] = {0,0,0,0,0};
1080     int previousUpperLimit = -1;
1081     for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1082     bits[i] = velocityZone;
1083     DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
1084    
1085     pDimDef->ranges[velocityZone].low = previousUpperLimit + 1;
1086     pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
1087     previousUpperLimit = pDimDef->ranges[velocityZone].high;
1088     // fill velocity table
1089     for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
1090     VelocityTable[i] = velocityZone;
1091     }
1092     }
1093     }
1094     }
1095     }
1096    
1097     // load sample references
1098     _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)
1099     for (uint i = 0; i < DimensionRegions; i++) {
1100     uint32_t wavepoolindex = _3lnk->ReadUint32();
1101     pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
1102     }
1103     }
1104     else throw gig::Exception("Mandatory <3lnk> chunk not found.");
1105     }
1106    
1107     void Region::LoadDimensionRegions(RIFF::List* rgn) {
1108     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
1109     if (_3prg) {
1110     int dimensionRegionNr = 0;
1111     RIFF::List* _3ewl = _3prg->GetFirstSubList();
1112     while (_3ewl) {
1113     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
1114     pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
1115     dimensionRegionNr++;
1116     }
1117     _3ewl = _3prg->GetNextSubList();
1118     }
1119     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
1120     }
1121     }
1122    
1123     Region::~Region() {
1124     for (uint i = 0; i < Dimensions; i++) {
1125     if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1126     }
1127     for (int i = 0; i < 32; i++) {
1128     if (pDimensionRegions[i]) delete pDimensionRegions[i];
1129     }
1130     }
1131    
1132     /**
1133     * Use this method in your audio engine to get the appropriate dimension
1134     * region with it's articulation data for the current situation. Just
1135     * call the method with the current MIDI controller values and you'll get
1136     * the DimensionRegion with the appropriate articulation data for the
1137     * current situation (for this Region of course only). To do that you'll
1138     * first have to look which dimensions with which controllers and in
1139     * which order are defined for this Region when you load the .gig file.
1140     * Special cases are e.g. layer or channel dimensions where you just put
1141     * in the index numbers instead of a MIDI controller value (means 0 for
1142     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
1143     * etc.).
1144     *
1145     * @param Dim4Val MIDI controller value (0-127) for dimension 4
1146     * @param Dim3Val MIDI controller value (0-127) for dimension 3
1147     * @param Dim2Val MIDI controller value (0-127) for dimension 2
1148     * @param Dim1Val MIDI controller value (0-127) for dimension 1
1149     * @param Dim0Val MIDI controller value (0-127) for dimension 0
1150     * @returns adress to the DimensionRegion for the given situation
1151     * @see pDimensionDefinitions
1152     * @see Dimensions
1153     */
1154     DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {
1155     unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};
1156     for (uint i = 0; i < Dimensions; i++) {
1157     switch (pDimensionDefinitions[i].split_type) {
1158     case split_type_normal:
1159     bits[i] /= pDimensionDefinitions[i].zone_size;
1160     break;
1161     case split_type_customvelocity:
1162     bits[i] = VelocityTable[bits[i]];
1163     break;
1164     // else the value is already the sought dimension bit number
1165     }
1166     }
1167     return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
1168     }
1169    
1170     /**
1171     * Returns the appropriate DimensionRegion for the given dimension bit
1172     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1173     * instead of calling this method directly!
1174     *
1175     * @param Dim4Bit Bit number for dimension 4
1176     * @param Dim3Bit Bit number for dimension 3
1177     * @param Dim2Bit Bit number for dimension 2
1178     * @param Dim1Bit Bit number for dimension 1
1179     * @param Dim0Bit Bit number for dimension 0
1180     * @returns adress to the DimensionRegion for the given dimension
1181     * bit numbers
1182     * @see GetDimensionRegionByValue()
1183     */
1184     DimensionRegion* Region::GetDimensionRegionByBit(uint8_t Dim4Bit, uint8_t Dim3Bit, uint8_t Dim2Bit, uint8_t Dim1Bit, uint8_t Dim0Bit) {
1185     return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)
1186     << pDimensionDefinitions[2].bits) | Dim2Bit)
1187     << pDimensionDefinitions[1].bits) | Dim1Bit)
1188     << pDimensionDefinitions[0].bits) | Dim0Bit) );
1189     }
1190    
1191     /**
1192     * Returns pointer address to the Sample referenced with this region.
1193     * This is the global Sample for the entire Region (not sure if this is
1194     * actually used by the Gigasampler engine - I would only use the Sample
1195     * referenced by the appropriate DimensionRegion instead of this sample).
1196     *
1197     * @returns address to Sample or NULL if there is no reference to a
1198     * sample saved in the .gig file
1199     */
1200     Sample* Region::GetSample() {
1201     if (pSample) return static_cast<gig::Sample*>(pSample);
1202     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1203     }
1204    
1205     Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
1206     File* file = (File*) GetParent()->GetParent();
1207     unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1208     Sample* sample = file->GetFirstSample();
1209     while (sample) {
1210     if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
1211     sample = file->GetNextSample();
1212     }
1213     return NULL;
1214     }
1215    
1216    
1217    
1218     // *************** Instrument ***************
1219     // *
1220    
1221     Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {
1222     // Initialization
1223     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1224     RegionIndex = -1;
1225    
1226     // Loading
1227     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
1228     if (lart) {
1229     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
1230     if (_3ewg) {
1231     EffectSend = _3ewg->ReadUint16();
1232     Attenuation = _3ewg->ReadInt32();
1233     FineTune = _3ewg->ReadInt16();
1234     PitchbendRange = _3ewg->ReadInt16();
1235     uint8_t dimkeystart = _3ewg->ReadUint8();
1236     PianoReleaseMode = dimkeystart & 0x01;
1237     DimensionKeyRange.low = dimkeystart >> 1;
1238     DimensionKeyRange.high = _3ewg->ReadUint8();
1239     }
1240     else throw gig::Exception("Mandatory <3ewg> chunk not found.");
1241     }
1242     else throw gig::Exception("Mandatory <lart> list chunk not found.");
1243    
1244     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1245     if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1246     pRegions = new Region*[Regions];
1247     RIFF::List* rgn = lrgn->GetFirstSubList();
1248     unsigned int iRegion = 0;
1249     while (rgn) {
1250     if (rgn->GetListType() == LIST_TYPE_RGN) {
1251     pRegions[iRegion] = new Region(this, rgn);
1252     iRegion++;
1253     }
1254     rgn = lrgn->GetNextSubList();
1255     }
1256    
1257     // Creating Region Key Table for fast lookup
1258     for (uint iReg = 0; iReg < Regions; iReg++) {
1259     for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {
1260     RegionKeyTable[iKey] = pRegions[iReg];
1261     }
1262     }
1263     }
1264    
1265     Instrument::~Instrument() {
1266     for (uint i = 0; i < Regions; i++) {
1267     if (pRegions) {
1268     if (pRegions[i]) delete (pRegions[i]);
1269     }
1270     delete[] pRegions;
1271     }
1272     }
1273    
1274     /**
1275     * Returns the appropriate Region for a triggered note.
1276     *
1277     * @param Key MIDI Key number of triggered note / key (0 - 127)
1278     * @returns pointer adress to the appropriate Region or NULL if there
1279     * there is no Region defined for the given \a Key
1280     */
1281     Region* Instrument::GetRegion(unsigned int Key) {
1282     if (!pRegions || Key > 127) return NULL;
1283     return RegionKeyTable[Key];
1284     /*for (int i = 0; i < Regions; i++) {
1285     if (Key <= pRegions[i]->KeyRange.high &&
1286     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
1287     }
1288     return NULL;*/
1289     }
1290    
1291     /**
1292     * Returns the first Region of the instrument. You have to call this
1293     * method once before you use GetNextRegion().
1294     *
1295     * @returns pointer address to first region or NULL if there is none
1296     * @see GetNextRegion()
1297     */
1298     Region* Instrument::GetFirstRegion() {
1299     if (!Regions) return NULL;
1300     RegionIndex = 1;
1301     return pRegions[0];
1302     }
1303    
1304     /**
1305     * Returns the next Region of the instrument. You have to call
1306     * GetFirstRegion() once before you can use this method. By calling this
1307     * method multiple times it iterates through the available Regions.
1308     *
1309     * @returns pointer address to the next region or NULL if end reached
1310     * @see GetFirstRegion()
1311     */
1312     Region* Instrument::GetNextRegion() {
1313     if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;
1314     return pRegions[RegionIndex++];
1315     }
1316    
1317    
1318    
1319     // *************** File ***************
1320     // *
1321    
1322     File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
1323     pSamples = NULL;
1324     pInstruments = NULL;
1325     }
1326    
1327     Sample* File::GetFirstSample() {
1328     if (!pSamples) LoadSamples();
1329     if (!pSamples) return NULL;
1330     SamplesIterator = pSamples->begin();
1331     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1332     }
1333    
1334     Sample* File::GetNextSample() {
1335     if (!pSamples) return NULL;
1336     SamplesIterator++;
1337     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1338     }
1339    
1340     void File::LoadSamples() {
1341     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1342     if (wvpl) {
1343     unsigned long wvplFileOffset = wvpl->GetFilePos();
1344     RIFF::List* wave = wvpl->GetFirstSubList();
1345     while (wave) {
1346     if (wave->GetListType() == LIST_TYPE_WAVE) {
1347     if (!pSamples) pSamples = new SampleList;
1348     unsigned long waveFileOffset = wave->GetFilePos();
1349     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1350     }
1351     wave = wvpl->GetNextSubList();
1352     }
1353     }
1354     else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1355     }
1356    
1357     Instrument* File::GetFirstInstrument() {
1358     if (!pInstruments) LoadInstruments();
1359     if (!pInstruments) return NULL;
1360     InstrumentsIterator = pInstruments->begin();
1361     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1362     }
1363    
1364     Instrument* File::GetNextInstrument() {
1365     if (!pInstruments) return NULL;
1366     InstrumentsIterator++;
1367     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1368     }
1369    
1370 schoenebeck 21 /**
1371     * Returns the instrument with the given index.
1372     *
1373     * @returns sought instrument or NULL if there's no such instrument
1374     */
1375     Instrument* File::GetInstrument(uint index) {
1376     if (!pInstruments) LoadInstruments();
1377     if (!pInstruments) return NULL;
1378     InstrumentsIterator = pInstruments->begin();
1379     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
1380     if (i == index) return *InstrumentsIterator;
1381     InstrumentsIterator++;
1382     }
1383     return NULL;
1384     }
1385    
1386 schoenebeck 2 void File::LoadInstruments() {
1387     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1388     if (lstInstruments) {
1389     RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1390     while (lstInstr) {
1391     if (lstInstr->GetListType() == LIST_TYPE_INS) {
1392     if (!pInstruments) pInstruments = new InstrumentList;
1393     pInstruments->push_back(new Instrument(this, lstInstr));
1394     }
1395     lstInstr = lstInstruments->GetNextSubList();
1396     }
1397     }
1398     else throw gig::Exception("Mandatory <lins> list chunk not found.");
1399     }
1400    
1401    
1402    
1403     // *************** Exception ***************
1404     // *
1405    
1406     Exception::Exception(String Message) : DLS::Exception(Message) {
1407     }
1408    
1409     void Exception::PrintMessage() {
1410     std::cout << "gig::Exception: " << Message << std::endl;
1411     }
1412    
1413     } // namespace gig

  ViewVC Help
Powered by ViewVC