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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 365 - (show annotations) (download)
Thu Feb 10 19:16:31 2005 UTC (19 years, 2 months ago) by persson
File size: 79522 byte(s)
* src/gig.cpp, src/gig.h, src/gigextract.cpp: Support for compressed
  mono samples. Experimental support for compressed 24 bit
  samples. Fixes for decompression on big-endian CPUs. Fix for bug
  that truncated end of compressed samples.

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

  ViewVC Help
Powered by ViewVC