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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 666 - (show annotations) (download)
Sun Jun 19 15:18:59 2005 UTC (18 years, 9 months ago) by persson
File size: 90221 byte(s)
* added support for gig v3 multi-file format

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

  ViewVC Help
Powered by ViewVC