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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 308 - (hide annotations) (download)
Sun Nov 21 18:02:21 2004 UTC (19 years, 4 months ago) by schoenebeck
File size: 71211 byte(s)
* src/gig.cpp, src/gig.h: applied patch by Andreas Persson which improves
  accuracy of all three velocity response curves

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 schoenebeck 241 _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
684 schoenebeck 2 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 schoenebeck 269 Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
778 schoenebeck 2 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 schoenebeck 308 pVelocityAttenuationTable =
840     CreateVelocityTable(VelocityResponseCurve,
841     VelocityResponseDepth,
842     VelocityResponseCurveScaling);
843 schoenebeck 16 (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
844     }
845 schoenebeck 2 }
846 schoenebeck 55
847 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
848     leverage_ctrl_t decodedcontroller;
849     switch (EncodedController) {
850     // special controller
851     case _lev_ctrl_none:
852     decodedcontroller.type = leverage_ctrl_t::type_none;
853     decodedcontroller.controller_number = 0;
854     break;
855     case _lev_ctrl_velocity:
856     decodedcontroller.type = leverage_ctrl_t::type_velocity;
857     decodedcontroller.controller_number = 0;
858     break;
859     case _lev_ctrl_channelaftertouch:
860     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
861     decodedcontroller.controller_number = 0;
862     break;
863 schoenebeck 55
864 schoenebeck 36 // ordinary MIDI control change controller
865     case _lev_ctrl_modwheel:
866     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
867     decodedcontroller.controller_number = 1;
868     break;
869     case _lev_ctrl_breath:
870     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
871     decodedcontroller.controller_number = 2;
872     break;
873     case _lev_ctrl_foot:
874     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
875     decodedcontroller.controller_number = 4;
876     break;
877     case _lev_ctrl_effect1:
878     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
879     decodedcontroller.controller_number = 12;
880     break;
881     case _lev_ctrl_effect2:
882     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
883     decodedcontroller.controller_number = 13;
884     break;
885     case _lev_ctrl_genpurpose1:
886     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
887     decodedcontroller.controller_number = 16;
888     break;
889     case _lev_ctrl_genpurpose2:
890     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
891     decodedcontroller.controller_number = 17;
892     break;
893     case _lev_ctrl_genpurpose3:
894     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
895     decodedcontroller.controller_number = 18;
896     break;
897     case _lev_ctrl_genpurpose4:
898     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
899     decodedcontroller.controller_number = 19;
900     break;
901     case _lev_ctrl_portamentotime:
902     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
903     decodedcontroller.controller_number = 5;
904     break;
905     case _lev_ctrl_sustainpedal:
906     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
907     decodedcontroller.controller_number = 64;
908     break;
909     case _lev_ctrl_portamento:
910     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
911     decodedcontroller.controller_number = 65;
912     break;
913     case _lev_ctrl_sostenutopedal:
914     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
915     decodedcontroller.controller_number = 66;
916     break;
917     case _lev_ctrl_softpedal:
918     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
919     decodedcontroller.controller_number = 67;
920     break;
921     case _lev_ctrl_genpurpose5:
922     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
923     decodedcontroller.controller_number = 80;
924     break;
925     case _lev_ctrl_genpurpose6:
926     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
927     decodedcontroller.controller_number = 81;
928     break;
929     case _lev_ctrl_genpurpose7:
930     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
931     decodedcontroller.controller_number = 82;
932     break;
933     case _lev_ctrl_genpurpose8:
934     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
935     decodedcontroller.controller_number = 83;
936     break;
937     case _lev_ctrl_effect1depth:
938     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
939     decodedcontroller.controller_number = 91;
940     break;
941     case _lev_ctrl_effect2depth:
942     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
943     decodedcontroller.controller_number = 92;
944     break;
945     case _lev_ctrl_effect3depth:
946     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
947     decodedcontroller.controller_number = 93;
948     break;
949     case _lev_ctrl_effect4depth:
950     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
951     decodedcontroller.controller_number = 94;
952     break;
953     case _lev_ctrl_effect5depth:
954     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
955     decodedcontroller.controller_number = 95;
956     break;
957 schoenebeck 55
958 schoenebeck 36 // unknown controller type
959     default:
960     throw gig::Exception("Unknown leverage controller type.");
961     }
962     return decodedcontroller;
963     }
964 schoenebeck 2
965 schoenebeck 16 DimensionRegion::~DimensionRegion() {
966     Instances--;
967     if (!Instances) {
968     // delete the velocity->volume tables
969     VelocityTableMap::iterator iter;
970     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
971     double* pTable = iter->second;
972     if (pTable) delete[] pTable;
973     }
974     pVelocityTables->clear();
975     delete pVelocityTables;
976     pVelocityTables = NULL;
977     }
978     }
979 schoenebeck 2
980 schoenebeck 16 /**
981     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
982     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
983     * and VelocityResponseCurveScaling) involved are taken into account to
984     * calculate the amplitude factor. Use this method when a key was
985     * triggered to get the volume with which the sample should be played
986     * back.
987     *
988 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
989     * @returns amplitude factor (between 0.0 and 1.0)
990 schoenebeck 16 */
991     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
992     return pVelocityAttenuationTable[MIDIKeyVelocity];
993     }
994 schoenebeck 2
995 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
996    
997     // line-segment approximations of the 15 velocity curves
998 schoenebeck 16
999 schoenebeck 308 // linear
1000     const int lin0[] = { 1, 1, 127, 127 };
1001     const int lin1[] = { 1, 21, 127, 127 };
1002     const int lin2[] = { 1, 45, 127, 127 };
1003     const int lin3[] = { 1, 74, 127, 127 };
1004     const int lin4[] = { 1, 127, 127, 127 };
1005 schoenebeck 16
1006 schoenebeck 308 // non-linear
1007     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1008     const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1009     127, 127 };
1010     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1011     127, 127 };
1012     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1013     127, 127 };
1014     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1015    
1016     // special
1017     const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
1018     113, 127, 127, 127 };
1019     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
1020     118, 127, 127, 127 };
1021     const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
1022     85, 90, 91, 127, 127, 127 };
1023     const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
1024     117, 127, 127, 127 };
1025     const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
1026     127, 127 };
1027    
1028     const int* const curves[] = { non0, non1, non2, non3, non4,
1029     lin0, lin1, lin2, lin3, lin4,
1030     spe0, spe1, spe2, spe3, spe4 };
1031    
1032     double* const table = new double[128];
1033    
1034     const int* curve = curves[curveType * 5 + depth];
1035     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
1036    
1037     table[0] = 0;
1038     for (int x = 1 ; x < 128 ; x++) {
1039    
1040     if (x > curve[2]) curve += 2;
1041     double y = curve[1] + (x - curve[0]) *
1042     (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
1043     y = y / 127;
1044    
1045     // Scale up for s > 20, down for s < 20. When
1046     // down-scaling, the curve still ends at 1.0.
1047     if (s < 20 && y >= 0.5)
1048     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
1049     else
1050     y = y * (s / 20.0);
1051     if (y > 1) y = 1;
1052    
1053     table[x] = y;
1054     }
1055     return table;
1056     }
1057    
1058    
1059 schoenebeck 2 // *************** Region ***************
1060     // *
1061    
1062     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
1063     // Initialization
1064     Dimensions = 0;
1065     for (int i = 0; i < 32; i++) {
1066     pDimensionRegions[i] = NULL;
1067     }
1068 schoenebeck 282 Layers = 1;
1069 schoenebeck 2
1070     // Actual Loading
1071    
1072     LoadDimensionRegions(rgnList);
1073    
1074     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
1075     if (_3lnk) {
1076     DimensionRegions = _3lnk->ReadUint32();
1077     for (int i = 0; i < 5; i++) {
1078     dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
1079     uint8_t bits = _3lnk->ReadUint8();
1080     if (dimension == dimension_none) { // inactive dimension
1081     pDimensionDefinitions[i].dimension = dimension_none;
1082     pDimensionDefinitions[i].bits = 0;
1083     pDimensionDefinitions[i].zones = 0;
1084     pDimensionDefinitions[i].split_type = split_type_bit;
1085     pDimensionDefinitions[i].ranges = NULL;
1086     pDimensionDefinitions[i].zone_size = 0;
1087     }
1088     else { // active dimension
1089     pDimensionDefinitions[i].dimension = dimension;
1090     pDimensionDefinitions[i].bits = bits;
1091     pDimensionDefinitions[i].zones = 0x01 << bits; // = pow(2,bits)
1092     pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
1093 schoenebeck 241 dimension == dimension_samplechannel ||
1094     dimension == dimension_releasetrigger) ? split_type_bit
1095     : split_type_normal;
1096 schoenebeck 2 pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
1097     pDimensionDefinitions[i].zone_size =
1098     (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
1099     : 0;
1100     Dimensions++;
1101 schoenebeck 282
1102     // if this is a layer dimension, remember the amount of layers
1103     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
1104 schoenebeck 2 }
1105     _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
1106     }
1107    
1108     // check velocity dimension (if there is one) for custom defined zone ranges
1109     for (uint i = 0; i < Dimensions; i++) {
1110     dimension_def_t* pDimDef = pDimensionDefinitions + i;
1111     if (pDimDef->dimension == dimension_velocity) {
1112     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {
1113     // no custom defined ranges
1114     pDimDef->split_type = split_type_normal;
1115     pDimDef->ranges = NULL;
1116     }
1117     else { // custom defined ranges
1118     pDimDef->split_type = split_type_customvelocity;
1119     pDimDef->ranges = new range_t[pDimDef->zones];
1120     unsigned int bits[5] = {0,0,0,0,0};
1121     int previousUpperLimit = -1;
1122     for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
1123     bits[i] = velocityZone;
1124     DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
1125    
1126     pDimDef->ranges[velocityZone].low = previousUpperLimit + 1;
1127     pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
1128     previousUpperLimit = pDimDef->ranges[velocityZone].high;
1129     // fill velocity table
1130     for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
1131     VelocityTable[i] = velocityZone;
1132     }
1133     }
1134     }
1135     }
1136     }
1137    
1138     // load sample references
1139     _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)
1140     for (uint i = 0; i < DimensionRegions; i++) {
1141     uint32_t wavepoolindex = _3lnk->ReadUint32();
1142     pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
1143     }
1144     }
1145     else throw gig::Exception("Mandatory <3lnk> chunk not found.");
1146     }
1147    
1148     void Region::LoadDimensionRegions(RIFF::List* rgn) {
1149     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
1150     if (_3prg) {
1151     int dimensionRegionNr = 0;
1152     RIFF::List* _3ewl = _3prg->GetFirstSubList();
1153     while (_3ewl) {
1154     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
1155     pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
1156     dimensionRegionNr++;
1157     }
1158     _3ewl = _3prg->GetNextSubList();
1159     }
1160     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
1161     }
1162     }
1163    
1164     Region::~Region() {
1165     for (uint i = 0; i < Dimensions; i++) {
1166     if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
1167     }
1168     for (int i = 0; i < 32; i++) {
1169     if (pDimensionRegions[i]) delete pDimensionRegions[i];
1170     }
1171     }
1172    
1173     /**
1174     * Use this method in your audio engine to get the appropriate dimension
1175     * region with it's articulation data for the current situation. Just
1176     * call the method with the current MIDI controller values and you'll get
1177     * the DimensionRegion with the appropriate articulation data for the
1178     * current situation (for this Region of course only). To do that you'll
1179     * first have to look which dimensions with which controllers and in
1180     * which order are defined for this Region when you load the .gig file.
1181     * Special cases are e.g. layer or channel dimensions where you just put
1182     * in the index numbers instead of a MIDI controller value (means 0 for
1183     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
1184     * etc.).
1185     *
1186     * @param Dim4Val MIDI controller value (0-127) for dimension 4
1187     * @param Dim3Val MIDI controller value (0-127) for dimension 3
1188     * @param Dim2Val MIDI controller value (0-127) for dimension 2
1189     * @param Dim1Val MIDI controller value (0-127) for dimension 1
1190     * @param Dim0Val MIDI controller value (0-127) for dimension 0
1191     * @returns adress to the DimensionRegion for the given situation
1192     * @see pDimensionDefinitions
1193     * @see Dimensions
1194     */
1195     DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {
1196 schoenebeck 241 uint8_t bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};
1197 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
1198     switch (pDimensionDefinitions[i].split_type) {
1199     case split_type_normal:
1200     bits[i] /= pDimensionDefinitions[i].zone_size;
1201     break;
1202     case split_type_customvelocity:
1203     bits[i] = VelocityTable[bits[i]];
1204     break;
1205 schoenebeck 241 case split_type_bit: // the value is already the sought dimension bit number
1206     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
1207     bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
1208     break;
1209 schoenebeck 2 }
1210     }
1211     return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
1212     }
1213    
1214     /**
1215     * Returns the appropriate DimensionRegion for the given dimension bit
1216     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
1217     * instead of calling this method directly!
1218     *
1219     * @param Dim4Bit Bit number for dimension 4
1220     * @param Dim3Bit Bit number for dimension 3
1221     * @param Dim2Bit Bit number for dimension 2
1222     * @param Dim1Bit Bit number for dimension 1
1223     * @param Dim0Bit Bit number for dimension 0
1224     * @returns adress to the DimensionRegion for the given dimension
1225     * bit numbers
1226     * @see GetDimensionRegionByValue()
1227     */
1228     DimensionRegion* Region::GetDimensionRegionByBit(uint8_t Dim4Bit, uint8_t Dim3Bit, uint8_t Dim2Bit, uint8_t Dim1Bit, uint8_t Dim0Bit) {
1229     return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)
1230     << pDimensionDefinitions[2].bits) | Dim2Bit)
1231     << pDimensionDefinitions[1].bits) | Dim1Bit)
1232     << pDimensionDefinitions[0].bits) | Dim0Bit) );
1233     }
1234    
1235     /**
1236     * Returns pointer address to the Sample referenced with this region.
1237     * This is the global Sample for the entire Region (not sure if this is
1238     * actually used by the Gigasampler engine - I would only use the Sample
1239     * referenced by the appropriate DimensionRegion instead of this sample).
1240     *
1241     * @returns address to Sample or NULL if there is no reference to a
1242     * sample saved in the .gig file
1243     */
1244     Sample* Region::GetSample() {
1245     if (pSample) return static_cast<gig::Sample*>(pSample);
1246     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
1247     }
1248    
1249     Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
1250     File* file = (File*) GetParent()->GetParent();
1251     unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1252     Sample* sample = file->GetFirstSample();
1253     while (sample) {
1254     if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
1255     sample = file->GetNextSample();
1256     }
1257     return NULL;
1258     }
1259    
1260    
1261    
1262     // *************** Instrument ***************
1263     // *
1264    
1265     Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {
1266     // Initialization
1267     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
1268     RegionIndex = -1;
1269    
1270     // Loading
1271     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
1272     if (lart) {
1273     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
1274     if (_3ewg) {
1275     EffectSend = _3ewg->ReadUint16();
1276     Attenuation = _3ewg->ReadInt32();
1277     FineTune = _3ewg->ReadInt16();
1278     PitchbendRange = _3ewg->ReadInt16();
1279     uint8_t dimkeystart = _3ewg->ReadUint8();
1280     PianoReleaseMode = dimkeystart & 0x01;
1281     DimensionKeyRange.low = dimkeystart >> 1;
1282     DimensionKeyRange.high = _3ewg->ReadUint8();
1283     }
1284     else throw gig::Exception("Mandatory <3ewg> chunk not found.");
1285     }
1286     else throw gig::Exception("Mandatory <lart> list chunk not found.");
1287    
1288     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
1289     if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
1290     pRegions = new Region*[Regions];
1291     RIFF::List* rgn = lrgn->GetFirstSubList();
1292     unsigned int iRegion = 0;
1293     while (rgn) {
1294     if (rgn->GetListType() == LIST_TYPE_RGN) {
1295     pRegions[iRegion] = new Region(this, rgn);
1296     iRegion++;
1297     }
1298     rgn = lrgn->GetNextSubList();
1299     }
1300    
1301     // Creating Region Key Table for fast lookup
1302     for (uint iReg = 0; iReg < Regions; iReg++) {
1303     for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {
1304     RegionKeyTable[iKey] = pRegions[iReg];
1305     }
1306     }
1307     }
1308    
1309     Instrument::~Instrument() {
1310     for (uint i = 0; i < Regions; i++) {
1311     if (pRegions) {
1312     if (pRegions[i]) delete (pRegions[i]);
1313     }
1314     delete[] pRegions;
1315     }
1316     }
1317    
1318     /**
1319     * Returns the appropriate Region for a triggered note.
1320     *
1321     * @param Key MIDI Key number of triggered note / key (0 - 127)
1322     * @returns pointer adress to the appropriate Region or NULL if there
1323     * there is no Region defined for the given \a Key
1324     */
1325     Region* Instrument::GetRegion(unsigned int Key) {
1326     if (!pRegions || Key > 127) return NULL;
1327     return RegionKeyTable[Key];
1328     /*for (int i = 0; i < Regions; i++) {
1329     if (Key <= pRegions[i]->KeyRange.high &&
1330     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
1331     }
1332     return NULL;*/
1333     }
1334    
1335     /**
1336     * Returns the first Region of the instrument. You have to call this
1337     * method once before you use GetNextRegion().
1338     *
1339     * @returns pointer address to first region or NULL if there is none
1340     * @see GetNextRegion()
1341     */
1342     Region* Instrument::GetFirstRegion() {
1343     if (!Regions) return NULL;
1344     RegionIndex = 1;
1345     return pRegions[0];
1346     }
1347    
1348     /**
1349     * Returns the next Region of the instrument. You have to call
1350     * GetFirstRegion() once before you can use this method. By calling this
1351     * method multiple times it iterates through the available Regions.
1352     *
1353     * @returns pointer address to the next region or NULL if end reached
1354     * @see GetFirstRegion()
1355     */
1356     Region* Instrument::GetNextRegion() {
1357     if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;
1358     return pRegions[RegionIndex++];
1359     }
1360    
1361    
1362    
1363     // *************** File ***************
1364     // *
1365    
1366     File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
1367     pSamples = NULL;
1368     pInstruments = NULL;
1369     }
1370    
1371     Sample* File::GetFirstSample() {
1372     if (!pSamples) LoadSamples();
1373     if (!pSamples) return NULL;
1374     SamplesIterator = pSamples->begin();
1375     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1376     }
1377    
1378     Sample* File::GetNextSample() {
1379     if (!pSamples) return NULL;
1380     SamplesIterator++;
1381     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1382     }
1383    
1384     void File::LoadSamples() {
1385     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1386     if (wvpl) {
1387     unsigned long wvplFileOffset = wvpl->GetFilePos();
1388     RIFF::List* wave = wvpl->GetFirstSubList();
1389     while (wave) {
1390     if (wave->GetListType() == LIST_TYPE_WAVE) {
1391     if (!pSamples) pSamples = new SampleList;
1392     unsigned long waveFileOffset = wave->GetFilePos();
1393     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1394     }
1395     wave = wvpl->GetNextSubList();
1396     }
1397     }
1398     else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1399     }
1400    
1401     Instrument* File::GetFirstInstrument() {
1402     if (!pInstruments) LoadInstruments();
1403     if (!pInstruments) return NULL;
1404     InstrumentsIterator = pInstruments->begin();
1405     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1406     }
1407    
1408     Instrument* File::GetNextInstrument() {
1409     if (!pInstruments) return NULL;
1410     InstrumentsIterator++;
1411     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1412     }
1413    
1414 schoenebeck 21 /**
1415     * Returns the instrument with the given index.
1416     *
1417     * @returns sought instrument or NULL if there's no such instrument
1418     */
1419     Instrument* File::GetInstrument(uint index) {
1420     if (!pInstruments) LoadInstruments();
1421     if (!pInstruments) return NULL;
1422     InstrumentsIterator = pInstruments->begin();
1423     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
1424     if (i == index) return *InstrumentsIterator;
1425     InstrumentsIterator++;
1426     }
1427     return NULL;
1428     }
1429    
1430 schoenebeck 2 void File::LoadInstruments() {
1431     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1432     if (lstInstruments) {
1433     RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1434     while (lstInstr) {
1435     if (lstInstr->GetListType() == LIST_TYPE_INS) {
1436     if (!pInstruments) pInstruments = new InstrumentList;
1437     pInstruments->push_back(new Instrument(this, lstInstr));
1438     }
1439     lstInstr = lstInstruments->GetNextSubList();
1440     }
1441     }
1442     else throw gig::Exception("Mandatory <lins> list chunk not found.");
1443     }
1444    
1445    
1446    
1447     // *************** Exception ***************
1448     // *
1449    
1450     Exception::Exception(String Message) : DLS::Exception(Message) {
1451     }
1452    
1453     void Exception::PrintMessage() {
1454     std::cout << "gig::Exception: " << Message << std::endl;
1455     }
1456    
1457     } // namespace gig

  ViewVC Help
Powered by ViewVC