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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 27 - (hide annotations) (download)
Thu Jan 1 23:46:41 2004 UTC (20 years, 3 months ago) by schoenebeck
File size: 64188 byte(s)
* src/gig.cpp: attributes 'LoopStart', 'LoopEnd' and 'LoopSize' in class
  'Sample' reflected wrong values
* updated Make files (autoconf 2.58, automake 1.6.3)

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

  ViewVC Help
Powered by ViewVC