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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 613 - (show annotations) (download)
Mon Jun 6 16:50:58 2005 UTC (18 years, 9 months ago) by persson
File size: 88985 byte(s)
* added DimensionRegion::GetVelocityRelease function

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

  ViewVC Help
Powered by ViewVC