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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 355 - (hide annotations) (download)
Fri Feb 4 00:21:30 2005 UTC (19 years, 1 month ago) by schoenebeck
File size: 73117 byte(s)
* src/gig.cpp:
  - another memory leak fix
  - duplicated memory free fix
  - tiny fix in decompression buffer reallocation
(patch by "Gene" a.k.a Anders Alm)

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

  ViewVC Help
Powered by ViewVC