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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 515 - (show annotations) (download)
Sat May 7 20:19:10 2005 UTC (18 years, 10 months ago) by schoenebeck
File size: 87472 byte(s)
* src/gig.h, src/gig.cpp: implemented progress indicator callback mechanism
  for loading instruments and samples
* src/DLS.cpp: fixed File constructor which caused variable
  File::Instruments always to be zero
* src/RIFF.cpp: fixed method List::LoadSubChunks() which did not restore
  the original position within the body of the given list chunk

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

  ViewVC Help
Powered by ViewVC