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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 864 - (show annotations) (download)
Sun May 14 07:15:38 2006 UTC (17 years, 10 months ago) by persson
File size: 134077 byte(s)
* sample loop parameters are now taken from the DimensionRegion
  instead of the wave chunk
* keyswitching dimension is changed from split type "normal" to "bit"

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 "helper.h"
27
28 #include <math.h>
29 #include <iostream>
30
31 /// Initial size of the sample buffer which is used for decompression of
32 /// compressed sample wave streams - this value should always be bigger than
33 /// the biggest sample piece expected to be read by the sampler engine,
34 /// otherwise the buffer size will be raised at runtime and thus the buffer
35 /// reallocated which is time consuming and unefficient.
36 #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
37
38 /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39 #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
40 #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
41 #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
42 #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
43 #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
44 #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
45 #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
46 #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
47 #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48 #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
49 #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
50 #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
51
52 namespace gig {
53
54 // *************** progress_t ***************
55 // *
56
57 progress_t::progress_t() {
58 callback = NULL;
59 custom = NULL;
60 __range_min = 0.0f;
61 __range_max = 1.0f;
62 }
63
64 // private helper function to convert progress of a subprocess into the global progress
65 static void __notify_progress(progress_t* pProgress, float subprogress) {
66 if (pProgress && pProgress->callback) {
67 const float totalrange = pProgress->__range_max - pProgress->__range_min;
68 const float totalprogress = pProgress->__range_min + subprogress * totalrange;
69 pProgress->factor = totalprogress;
70 pProgress->callback(pProgress); // now actually notify about the progress
71 }
72 }
73
74 // private helper function to divide a progress into subprogresses
75 static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
76 if (pParentProgress && pParentProgress->callback) {
77 const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
78 pSubProgress->callback = pParentProgress->callback;
79 pSubProgress->custom = pParentProgress->custom;
80 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
81 pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
82 }
83 }
84
85
86 // *************** Internal functions for sample decompression ***************
87 // *
88
89 namespace {
90
91 inline int get12lo(const unsigned char* pSrc)
92 {
93 const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
94 return x & 0x800 ? x - 0x1000 : x;
95 }
96
97 inline int get12hi(const unsigned char* pSrc)
98 {
99 const int x = pSrc[1] >> 4 | pSrc[2] << 4;
100 return x & 0x800 ? x - 0x1000 : x;
101 }
102
103 inline int16_t get16(const unsigned char* pSrc)
104 {
105 return int16_t(pSrc[0] | pSrc[1] << 8);
106 }
107
108 inline int get24(const unsigned char* pSrc)
109 {
110 const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
111 return x & 0x800000 ? x - 0x1000000 : x;
112 }
113
114 void Decompress16(int compressionmode, const unsigned char* params,
115 int srcStep, int dstStep,
116 const unsigned char* pSrc, int16_t* pDst,
117 unsigned long currentframeoffset,
118 unsigned long copysamples)
119 {
120 switch (compressionmode) {
121 case 0: // 16 bit uncompressed
122 pSrc += currentframeoffset * srcStep;
123 while (copysamples) {
124 *pDst = get16(pSrc);
125 pDst += dstStep;
126 pSrc += srcStep;
127 copysamples--;
128 }
129 break;
130
131 case 1: // 16 bit compressed to 8 bit
132 int y = get16(params);
133 int dy = get16(params + 2);
134 while (currentframeoffset) {
135 dy -= int8_t(*pSrc);
136 y -= dy;
137 pSrc += srcStep;
138 currentframeoffset--;
139 }
140 while (copysamples) {
141 dy -= int8_t(*pSrc);
142 y -= dy;
143 *pDst = y;
144 pDst += dstStep;
145 pSrc += srcStep;
146 copysamples--;
147 }
148 break;
149 }
150 }
151
152 void Decompress24(int compressionmode, const unsigned char* params,
153 int dstStep, const unsigned char* pSrc, int16_t* pDst,
154 unsigned long currentframeoffset,
155 unsigned long copysamples, int truncatedBits)
156 {
157 // Note: The 24 bits are truncated to 16 bits for now.
158
159 int y, dy, ddy, dddy;
160 const int shift = 8 - truncatedBits;
161
162 #define GET_PARAMS(params) \
163 y = get24(params); \
164 dy = y - get24((params) + 3); \
165 ddy = get24((params) + 6); \
166 dddy = get24((params) + 9)
167
168 #define SKIP_ONE(x) \
169 dddy -= (x); \
170 ddy -= dddy; \
171 dy = -dy - ddy; \
172 y += dy
173
174 #define COPY_ONE(x) \
175 SKIP_ONE(x); \
176 *pDst = y >> shift; \
177 pDst += dstStep
178
179 switch (compressionmode) {
180 case 2: // 24 bit uncompressed
181 pSrc += currentframeoffset * 3;
182 while (copysamples) {
183 *pDst = get24(pSrc) >> shift;
184 pDst += dstStep;
185 pSrc += 3;
186 copysamples--;
187 }
188 break;
189
190 case 3: // 24 bit compressed to 16 bit
191 GET_PARAMS(params);
192 while (currentframeoffset) {
193 SKIP_ONE(get16(pSrc));
194 pSrc += 2;
195 currentframeoffset--;
196 }
197 while (copysamples) {
198 COPY_ONE(get16(pSrc));
199 pSrc += 2;
200 copysamples--;
201 }
202 break;
203
204 case 4: // 24 bit compressed to 12 bit
205 GET_PARAMS(params);
206 while (currentframeoffset > 1) {
207 SKIP_ONE(get12lo(pSrc));
208 SKIP_ONE(get12hi(pSrc));
209 pSrc += 3;
210 currentframeoffset -= 2;
211 }
212 if (currentframeoffset) {
213 SKIP_ONE(get12lo(pSrc));
214 currentframeoffset--;
215 if (copysamples) {
216 COPY_ONE(get12hi(pSrc));
217 pSrc += 3;
218 copysamples--;
219 }
220 }
221 while (copysamples > 1) {
222 COPY_ONE(get12lo(pSrc));
223 COPY_ONE(get12hi(pSrc));
224 pSrc += 3;
225 copysamples -= 2;
226 }
227 if (copysamples) {
228 COPY_ONE(get12lo(pSrc));
229 }
230 break;
231
232 case 5: // 24 bit compressed to 8 bit
233 GET_PARAMS(params);
234 while (currentframeoffset) {
235 SKIP_ONE(int8_t(*pSrc++));
236 currentframeoffset--;
237 }
238 while (copysamples) {
239 COPY_ONE(int8_t(*pSrc++));
240 copysamples--;
241 }
242 break;
243 }
244 }
245
246 const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
247 const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
248 const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
249 const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
250 }
251
252
253 // *************** Sample ***************
254 // *
255
256 unsigned int Sample::Instances = 0;
257 buffer_t Sample::InternalDecompressionBuffer;
258
259 /** @brief Constructor.
260 *
261 * Load an existing sample or create a new one. A 'wave' list chunk must
262 * be given to this constructor. In case the given 'wave' list chunk
263 * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
264 * format and sample data will be loaded from there, otherwise default
265 * values will be used and those chunks will be created when
266 * File::Save() will be called later on.
267 *
268 * @param pFile - pointer to gig::File where this sample is
269 * located (or will be located)
270 * @param waveList - pointer to 'wave' list chunk which is (or
271 * will be) associated with this sample
272 * @param WavePoolOffset - offset of this sample data from wave pool
273 * ('wvpl') list chunk
274 * @param fileNo - number of an extension file where this sample
275 * is located, 0 otherwise
276 */
277 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
278 Instances++;
279 FileNo = fileNo;
280
281 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
282 if (pCk3gix) {
283 SampleGroup = pCk3gix->ReadInt16();
284 } else { // '3gix' chunk missing
285 // use default value(s)
286 SampleGroup = 0;
287 }
288
289 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
290 if (pCkSmpl) {
291 Manufacturer = pCkSmpl->ReadInt32();
292 Product = pCkSmpl->ReadInt32();
293 SamplePeriod = pCkSmpl->ReadInt32();
294 MIDIUnityNote = pCkSmpl->ReadInt32();
295 FineTune = pCkSmpl->ReadInt32();
296 pCkSmpl->Read(&SMPTEFormat, 1, 4);
297 SMPTEOffset = pCkSmpl->ReadInt32();
298 Loops = pCkSmpl->ReadInt32();
299 pCkSmpl->ReadInt32(); // manufByt
300 LoopID = pCkSmpl->ReadInt32();
301 pCkSmpl->Read(&LoopType, 1, 4);
302 LoopStart = pCkSmpl->ReadInt32();
303 LoopEnd = pCkSmpl->ReadInt32();
304 LoopFraction = pCkSmpl->ReadInt32();
305 LoopPlayCount = pCkSmpl->ReadInt32();
306 } else { // 'smpl' chunk missing
307 // use default values
308 Manufacturer = 0;
309 Product = 0;
310 SamplePeriod = 1 / SamplesPerSecond;
311 MIDIUnityNote = 64;
312 FineTune = 0;
313 SMPTEOffset = 0;
314 Loops = 0;
315 LoopID = 0;
316 LoopStart = 0;
317 LoopEnd = 0;
318 LoopFraction = 0;
319 LoopPlayCount = 0;
320 }
321
322 FrameTable = NULL;
323 SamplePos = 0;
324 RAMCache.Size = 0;
325 RAMCache.pStart = NULL;
326 RAMCache.NullExtensionSize = 0;
327
328 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
329
330 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
331 Compressed = ewav;
332 Dithered = false;
333 TruncatedBits = 0;
334 if (Compressed) {
335 uint32_t version = ewav->ReadInt32();
336 if (version == 3 && BitDepth == 24) {
337 Dithered = ewav->ReadInt32();
338 ewav->SetPos(Channels == 2 ? 84 : 64);
339 TruncatedBits = ewav->ReadInt32();
340 }
341 ScanCompressedSample();
342 }
343
344 // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
345 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
346 InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
347 InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
348 }
349 FrameOffset = 0; // just for streaming compressed samples
350
351 LoopSize = LoopEnd - LoopStart + 1;
352 }
353
354 /**
355 * Apply sample and its settings to the respective RIFF chunks. You have
356 * to call File::Save() to make changes persistent.
357 *
358 * Usually there is absolutely no need to call this method explicitly.
359 * It will be called automatically when File::Save() was called.
360 *
361 * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
362 * was provided yet
363 * @throws gig::Exception if there is any invalid sample setting
364 */
365 void Sample::UpdateChunks() {
366 // first update base class's chunks
367 DLS::Sample::UpdateChunks();
368
369 // make sure 'smpl' chunk exists
370 pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
371 if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
372 // update 'smpl' chunk
373 uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
374 SamplePeriod = 1 / SamplesPerSecond;
375 memcpy(&pData[0], &Manufacturer, 4);
376 memcpy(&pData[4], &Product, 4);
377 memcpy(&pData[8], &SamplePeriod, 4);
378 memcpy(&pData[12], &MIDIUnityNote, 4);
379 memcpy(&pData[16], &FineTune, 4);
380 memcpy(&pData[20], &SMPTEFormat, 4);
381 memcpy(&pData[24], &SMPTEOffset, 4);
382 memcpy(&pData[28], &Loops, 4);
383
384 // we skip 'manufByt' for now (4 bytes)
385
386 memcpy(&pData[36], &LoopID, 4);
387 memcpy(&pData[40], &LoopType, 4);
388 memcpy(&pData[44], &LoopStart, 4);
389 memcpy(&pData[48], &LoopEnd, 4);
390 memcpy(&pData[52], &LoopFraction, 4);
391 memcpy(&pData[56], &LoopPlayCount, 4);
392
393 // make sure '3gix' chunk exists
394 pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
395 if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
396 // update '3gix' chunk
397 pData = (uint8_t*) pCk3gix->LoadChunkData();
398 memcpy(&pData[0], &SampleGroup, 2);
399 }
400
401 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
402 void Sample::ScanCompressedSample() {
403 //TODO: we have to add some more scans here (e.g. determine compression rate)
404 this->SamplesTotal = 0;
405 std::list<unsigned long> frameOffsets;
406
407 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
408 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
409
410 // Scanning
411 pCkData->SetPos(0);
412 if (Channels == 2) { // Stereo
413 for (int i = 0 ; ; i++) {
414 // for 24 bit samples every 8:th frame offset is
415 // stored, to save some memory
416 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
417
418 const int mode_l = pCkData->ReadUint8();
419 const int mode_r = pCkData->ReadUint8();
420 if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
421 const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
422
423 if (pCkData->RemainingBytes() <= frameSize) {
424 SamplesInLastFrame =
425 ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
426 (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
427 SamplesTotal += SamplesInLastFrame;
428 break;
429 }
430 SamplesTotal += SamplesPerFrame;
431 pCkData->SetPos(frameSize, RIFF::stream_curpos);
432 }
433 }
434 else { // Mono
435 for (int i = 0 ; ; i++) {
436 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
437
438 const int mode = pCkData->ReadUint8();
439 if (mode > 5) throw gig::Exception("Unknown compression mode");
440 const unsigned long frameSize = bytesPerFrame[mode];
441
442 if (pCkData->RemainingBytes() <= frameSize) {
443 SamplesInLastFrame =
444 ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
445 SamplesTotal += SamplesInLastFrame;
446 break;
447 }
448 SamplesTotal += SamplesPerFrame;
449 pCkData->SetPos(frameSize, RIFF::stream_curpos);
450 }
451 }
452 pCkData->SetPos(0);
453
454 // Build the frames table (which is used for fast resolving of a frame's chunk offset)
455 if (FrameTable) delete[] FrameTable;
456 FrameTable = new unsigned long[frameOffsets.size()];
457 std::list<unsigned long>::iterator end = frameOffsets.end();
458 std::list<unsigned long>::iterator iter = frameOffsets.begin();
459 for (int i = 0; iter != end; i++, iter++) {
460 FrameTable[i] = *iter;
461 }
462 }
463
464 /**
465 * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
466 * ReleaseSampleData() to free the memory if you don't need the cached
467 * sample data anymore.
468 *
469 * @returns buffer_t structure with start address and size of the buffer
470 * in bytes
471 * @see ReleaseSampleData(), Read(), SetPos()
472 */
473 buffer_t Sample::LoadSampleData() {
474 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
475 }
476
477 /**
478 * Reads (uncompresses if needed) and caches the first \a SampleCount
479 * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
480 * memory space if you don't need the cached samples anymore. There is no
481 * guarantee that exactly \a SampleCount samples will be cached; this is
482 * not an error. The size will be eventually truncated e.g. to the
483 * beginning of a frame of a compressed sample. This is done for
484 * efficiency reasons while streaming the wave by your sampler engine
485 * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
486 * that will be returned to determine the actual cached samples, but note
487 * that the size is given in bytes! You get the number of actually cached
488 * samples by dividing it by the frame size of the sample:
489 * @code
490 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
491 * long cachedsamples = buf.Size / pSample->FrameSize;
492 * @endcode
493 *
494 * @param SampleCount - number of sample points to load into RAM
495 * @returns buffer_t structure with start address and size of
496 * the cached sample data in bytes
497 * @see ReleaseSampleData(), Read(), SetPos()
498 */
499 buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
500 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
501 }
502
503 /**
504 * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
505 * ReleaseSampleData() to free the memory if you don't need the cached
506 * sample data anymore.
507 * The method will add \a NullSamplesCount silence samples past the
508 * official buffer end (this won't affect the 'Size' member of the
509 * buffer_t structure, that means 'Size' always reflects the size of the
510 * actual sample data, the buffer might be bigger though). Silence
511 * samples past the official buffer are needed for differential
512 * algorithms that always have to take subsequent samples into account
513 * (resampling/interpolation would be an important example) and avoids
514 * memory access faults in such cases.
515 *
516 * @param NullSamplesCount - number of silence samples the buffer should
517 * be extended past it's data end
518 * @returns buffer_t structure with start address and
519 * size of the buffer in bytes
520 * @see ReleaseSampleData(), Read(), SetPos()
521 */
522 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
523 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
524 }
525
526 /**
527 * Reads (uncompresses if needed) and caches the first \a SampleCount
528 * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
529 * memory space if you don't need the cached samples anymore. There is no
530 * guarantee that exactly \a SampleCount samples will be cached; this is
531 * not an error. The size will be eventually truncated e.g. to the
532 * beginning of a frame of a compressed sample. This is done for
533 * efficiency reasons while streaming the wave by your sampler engine
534 * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
535 * that will be returned to determine the actual cached samples, but note
536 * that the size is given in bytes! You get the number of actually cached
537 * samples by dividing it by the frame size of the sample:
538 * @code
539 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
540 * long cachedsamples = buf.Size / pSample->FrameSize;
541 * @endcode
542 * The method will add \a NullSamplesCount silence samples past the
543 * official buffer end (this won't affect the 'Size' member of the
544 * buffer_t structure, that means 'Size' always reflects the size of the
545 * actual sample data, the buffer might be bigger though). Silence
546 * samples past the official buffer are needed for differential
547 * algorithms that always have to take subsequent samples into account
548 * (resampling/interpolation would be an important example) and avoids
549 * memory access faults in such cases.
550 *
551 * @param SampleCount - number of sample points to load into RAM
552 * @param NullSamplesCount - number of silence samples the buffer should
553 * be extended past it's data end
554 * @returns buffer_t structure with start address and
555 * size of the cached sample data in bytes
556 * @see ReleaseSampleData(), Read(), SetPos()
557 */
558 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
559 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
560 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
561 unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
562 RAMCache.pStart = new int8_t[allocationsize];
563 RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
564 RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
565 // fill the remaining buffer space with silence samples
566 memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
567 return GetCache();
568 }
569
570 /**
571 * Returns current cached sample points. A buffer_t structure will be
572 * returned which contains address pointer to the begin of the cache and
573 * the size of the cached sample data in bytes. Use
574 * <i>LoadSampleData()</i> to cache a specific amount of sample points in
575 * RAM.
576 *
577 * @returns buffer_t structure with current cached sample points
578 * @see LoadSampleData();
579 */
580 buffer_t Sample::GetCache() {
581 // return a copy of the buffer_t structure
582 buffer_t result;
583 result.Size = this->RAMCache.Size;
584 result.pStart = this->RAMCache.pStart;
585 result.NullExtensionSize = this->RAMCache.NullExtensionSize;
586 return result;
587 }
588
589 /**
590 * Frees the cached sample from RAM if loaded with
591 * <i>LoadSampleData()</i> previously.
592 *
593 * @see LoadSampleData();
594 */
595 void Sample::ReleaseSampleData() {
596 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
597 RAMCache.pStart = NULL;
598 RAMCache.Size = 0;
599 }
600
601 /** @brief Resize sample.
602 *
603 * Resizes the sample's wave form data, that is the actual size of
604 * sample wave data possible to be written for this sample. This call
605 * will return immediately and just schedule the resize operation. You
606 * should call File::Save() to actually perform the resize operation(s)
607 * "physically" to the file. As this can take a while on large files, it
608 * is recommended to call Resize() first on all samples which have to be
609 * resized and finally to call File::Save() to perform all those resize
610 * operations in one rush.
611 *
612 * The actual size (in bytes) is dependant to the current FrameSize
613 * value. You may want to set FrameSize before calling Resize().
614 *
615 * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
616 * enlarged samples before calling File::Save() as this might exceed the
617 * current sample's boundary!
618 *
619 * Also note: only WAVE_FORMAT_PCM is currently supported, that is
620 * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
621 * other formats will fail!
622 *
623 * @param iNewSize - new sample wave data size in sample points (must be
624 * greater than zero)
625 * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
626 * or if \a iNewSize is less than 1
627 * @throws gig::Exception if existing sample is compressed
628 * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
629 * DLS::Sample::FormatTag, File::Save()
630 */
631 void Sample::Resize(int iNewSize) {
632 if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
633 DLS::Sample::Resize(iNewSize);
634 }
635
636 /**
637 * Sets the position within the sample (in sample points, not in
638 * bytes). Use this method and <i>Read()</i> if you don't want to load
639 * the sample into RAM, thus for disk streaming.
640 *
641 * Although the original Gigasampler engine doesn't allow positioning
642 * within compressed samples, I decided to implement it. Even though
643 * the Gigasampler format doesn't allow to define loops for compressed
644 * samples at the moment, positioning within compressed samples might be
645 * interesting for some sampler engines though. The only drawback about
646 * my decision is that it takes longer to load compressed gig Files on
647 * startup, because it's neccessary to scan the samples for some
648 * mandatory informations. But I think as it doesn't affect the runtime
649 * efficiency, nobody will have a problem with that.
650 *
651 * @param SampleCount number of sample points to jump
652 * @param Whence optional: to which relation \a SampleCount refers
653 * to, if omited <i>RIFF::stream_start</i> is assumed
654 * @returns the new sample position
655 * @see Read()
656 */
657 unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
658 if (Compressed) {
659 switch (Whence) {
660 case RIFF::stream_curpos:
661 this->SamplePos += SampleCount;
662 break;
663 case RIFF::stream_end:
664 this->SamplePos = this->SamplesTotal - 1 - SampleCount;
665 break;
666 case RIFF::stream_backward:
667 this->SamplePos -= SampleCount;
668 break;
669 case RIFF::stream_start: default:
670 this->SamplePos = SampleCount;
671 break;
672 }
673 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
674
675 unsigned long frame = this->SamplePos / 2048; // to which frame to jump
676 this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
677 pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
678 return this->SamplePos;
679 }
680 else { // not compressed
681 unsigned long orderedBytes = SampleCount * this->FrameSize;
682 unsigned long result = pCkData->SetPos(orderedBytes, Whence);
683 return (result == orderedBytes) ? SampleCount
684 : result / this->FrameSize;
685 }
686 }
687
688 /**
689 * Returns the current position in the sample (in sample points).
690 */
691 unsigned long Sample::GetPos() {
692 if (Compressed) return SamplePos;
693 else return pCkData->GetPos() / FrameSize;
694 }
695
696 /**
697 * Reads \a SampleCount number of sample points from the position stored
698 * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
699 * the position within the sample respectively, this method honors the
700 * looping informations of the sample (if any). The sample wave stream
701 * will be decompressed on the fly if using a compressed sample. Use this
702 * method if you don't want to load the sample into RAM, thus for disk
703 * streaming. All this methods needs to know to proceed with streaming
704 * for the next time you call this method is stored in \a pPlaybackState.
705 * You have to allocate and initialize the playback_state_t structure by
706 * yourself before you use it to stream a sample:
707 * @code
708 * gig::playback_state_t playbackstate;
709 * playbackstate.position = 0;
710 * playbackstate.reverse = false;
711 * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
712 * @endcode
713 * You don't have to take care of things like if there is actually a loop
714 * defined or if the current read position is located within a loop area.
715 * The method already handles such cases by itself.
716 *
717 * <b>Caution:</b> If you are using more than one streaming thread, you
718 * have to use an external decompression buffer for <b>EACH</b>
719 * streaming thread to avoid race conditions and crashes!
720 *
721 * @param pBuffer destination buffer
722 * @param SampleCount number of sample points to read
723 * @param pPlaybackState will be used to store and reload the playback
724 * state for the next ReadAndLoop() call
725 * @param pDimRgn dimension region with looping information
726 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
727 * @returns number of successfully read sample points
728 * @see CreateDecompressionBuffer()
729 */
730 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
731 DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
732 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
733 uint8_t* pDst = (uint8_t*) pBuffer;
734
735 SetPos(pPlaybackState->position); // recover position from the last time
736
737 if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
738
739 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
740 const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
741
742 if (GetPos() <= loopEnd) {
743 switch (loop.LoopType) {
744
745 case loop_type_bidirectional: { //TODO: not tested yet!
746 do {
747 // if not endless loop check if max. number of loop cycles have been passed
748 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
749
750 if (!pPlaybackState->reverse) { // forward playback
751 do {
752 samplestoloopend = loopEnd - GetPos();
753 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
754 samplestoread -= readsamples;
755 totalreadsamples += readsamples;
756 if (readsamples == samplestoloopend) {
757 pPlaybackState->reverse = true;
758 break;
759 }
760 } while (samplestoread && readsamples);
761 }
762 else { // backward playback
763
764 // as we can only read forward from disk, we have to
765 // determine the end position within the loop first,
766 // read forward from that 'end' and finally after
767 // reading, swap all sample frames so it reflects
768 // backward playback
769
770 unsigned long swapareastart = totalreadsamples;
771 unsigned long loopoffset = GetPos() - loop.LoopStart;
772 unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
773 unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
774
775 SetPos(reverseplaybackend);
776
777 // read samples for backward playback
778 do {
779 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
780 samplestoreadinloop -= readsamples;
781 samplestoread -= readsamples;
782 totalreadsamples += readsamples;
783 } while (samplestoreadinloop && readsamples);
784
785 SetPos(reverseplaybackend); // pretend we really read backwards
786
787 if (reverseplaybackend == loop.LoopStart) {
788 pPlaybackState->loop_cycles_left--;
789 pPlaybackState->reverse = false;
790 }
791
792 // reverse the sample frames for backward playback
793 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
794 }
795 } while (samplestoread && readsamples);
796 break;
797 }
798
799 case loop_type_backward: { // TODO: not tested yet!
800 // forward playback (not entered the loop yet)
801 if (!pPlaybackState->reverse) do {
802 samplestoloopend = loopEnd - GetPos();
803 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
804 samplestoread -= readsamples;
805 totalreadsamples += readsamples;
806 if (readsamples == samplestoloopend) {
807 pPlaybackState->reverse = true;
808 break;
809 }
810 } while (samplestoread && readsamples);
811
812 if (!samplestoread) break;
813
814 // as we can only read forward from disk, we have to
815 // determine the end position within the loop first,
816 // read forward from that 'end' and finally after
817 // reading, swap all sample frames so it reflects
818 // backward playback
819
820 unsigned long swapareastart = totalreadsamples;
821 unsigned long loopoffset = GetPos() - loop.LoopStart;
822 unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
823 : samplestoread;
824 unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
825
826 SetPos(reverseplaybackend);
827
828 // read samples for backward playback
829 do {
830 // if not endless loop check if max. number of loop cycles have been passed
831 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
832 samplestoloopend = loopEnd - GetPos();
833 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
834 samplestoreadinloop -= readsamples;
835 samplestoread -= readsamples;
836 totalreadsamples += readsamples;
837 if (readsamples == samplestoloopend) {
838 pPlaybackState->loop_cycles_left--;
839 SetPos(loop.LoopStart);
840 }
841 } while (samplestoreadinloop && readsamples);
842
843 SetPos(reverseplaybackend); // pretend we really read backwards
844
845 // reverse the sample frames for backward playback
846 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
847 break;
848 }
849
850 default: case loop_type_normal: {
851 do {
852 // if not endless loop check if max. number of loop cycles have been passed
853 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
854 samplestoloopend = loopEnd - GetPos();
855 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
856 samplestoread -= readsamples;
857 totalreadsamples += readsamples;
858 if (readsamples == samplestoloopend) {
859 pPlaybackState->loop_cycles_left--;
860 SetPos(loop.LoopStart);
861 }
862 } while (samplestoread && readsamples);
863 break;
864 }
865 }
866 }
867 }
868
869 // read on without looping
870 if (samplestoread) do {
871 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
872 samplestoread -= readsamples;
873 totalreadsamples += readsamples;
874 } while (readsamples && samplestoread);
875
876 // store current position
877 pPlaybackState->position = GetPos();
878
879 return totalreadsamples;
880 }
881
882 /**
883 * Reads \a SampleCount number of sample points from the current
884 * position into the buffer pointed by \a pBuffer and increments the
885 * position within the sample. The sample wave stream will be
886 * decompressed on the fly if using a compressed sample. Use this method
887 * and <i>SetPos()</i> if you don't want to load the sample into RAM,
888 * thus for disk streaming.
889 *
890 * <b>Caution:</b> If you are using more than one streaming thread, you
891 * have to use an external decompression buffer for <b>EACH</b>
892 * streaming thread to avoid race conditions and crashes!
893 *
894 * @param pBuffer destination buffer
895 * @param SampleCount number of sample points to read
896 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
897 * @returns number of successfully read sample points
898 * @see SetPos(), CreateDecompressionBuffer()
899 */
900 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
901 if (SampleCount == 0) return 0;
902 if (!Compressed) {
903 if (BitDepth == 24) {
904 // 24 bit sample. For now just truncate to 16 bit.
905 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
906 int16_t* pDst = static_cast<int16_t*>(pBuffer);
907 if (Channels == 2) { // Stereo
908 unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
909 pSrc++;
910 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
911 *pDst++ = get16(pSrc);
912 pSrc += 3;
913 }
914 return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
915 }
916 else { // Mono
917 unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
918 pSrc++;
919 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
920 *pDst++ = get16(pSrc);
921 pSrc += 3;
922 }
923 return pDst - static_cast<int16_t*>(pBuffer);
924 }
925 }
926 else { // 16 bit
927 // (pCkData->Read does endian correction)
928 return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
929 : pCkData->Read(pBuffer, SampleCount, 2);
930 }
931 }
932 else {
933 if (this->SamplePos >= this->SamplesTotal) return 0;
934 //TODO: efficiency: maybe we should test for an average compression rate
935 unsigned long assumedsize = GuessSize(SampleCount),
936 remainingbytes = 0, // remaining bytes in the local buffer
937 remainingsamples = SampleCount,
938 copysamples, skipsamples,
939 currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
940 this->FrameOffset = 0;
941
942 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
943
944 // if decompression buffer too small, then reduce amount of samples to read
945 if (pDecompressionBuffer->Size < assumedsize) {
946 std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
947 SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
948 remainingsamples = SampleCount;
949 assumedsize = GuessSize(SampleCount);
950 }
951
952 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
953 int16_t* pDst = static_cast<int16_t*>(pBuffer);
954 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
955
956 while (remainingsamples && remainingbytes) {
957 unsigned long framesamples = SamplesPerFrame;
958 unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
959
960 int mode_l = *pSrc++, mode_r = 0;
961
962 if (Channels == 2) {
963 mode_r = *pSrc++;
964 framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
965 rightChannelOffset = bytesPerFrameNoHdr[mode_l];
966 nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
967 if (remainingbytes < framebytes) { // last frame in sample
968 framesamples = SamplesInLastFrame;
969 if (mode_l == 4 && (framesamples & 1)) {
970 rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
971 }
972 else {
973 rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
974 }
975 }
976 }
977 else {
978 framebytes = bytesPerFrame[mode_l] + 1;
979 nextFrameOffset = bytesPerFrameNoHdr[mode_l];
980 if (remainingbytes < framebytes) {
981 framesamples = SamplesInLastFrame;
982 }
983 }
984
985 // determine how many samples in this frame to skip and read
986 if (currentframeoffset + remainingsamples >= framesamples) {
987 if (currentframeoffset <= framesamples) {
988 copysamples = framesamples - currentframeoffset;
989 skipsamples = currentframeoffset;
990 }
991 else {
992 copysamples = 0;
993 skipsamples = framesamples;
994 }
995 }
996 else {
997 // This frame has enough data for pBuffer, but not
998 // all of the frame is needed. Set file position
999 // to start of this frame for next call to Read.
1000 copysamples = remainingsamples;
1001 skipsamples = currentframeoffset;
1002 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1003 this->FrameOffset = currentframeoffset + copysamples;
1004 }
1005 remainingsamples -= copysamples;
1006
1007 if (remainingbytes > framebytes) {
1008 remainingbytes -= framebytes;
1009 if (remainingsamples == 0 &&
1010 currentframeoffset + copysamples == framesamples) {
1011 // This frame has enough data for pBuffer, and
1012 // all of the frame is needed. Set file
1013 // position to start of next frame for next
1014 // call to Read. FrameOffset is 0.
1015 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1016 }
1017 }
1018 else remainingbytes = 0;
1019
1020 currentframeoffset -= skipsamples;
1021
1022 if (copysamples == 0) {
1023 // skip this frame
1024 pSrc += framebytes - Channels;
1025 }
1026 else {
1027 const unsigned char* const param_l = pSrc;
1028 if (BitDepth == 24) {
1029 if (mode_l != 2) pSrc += 12;
1030
1031 if (Channels == 2) { // Stereo
1032 const unsigned char* const param_r = pSrc;
1033 if (mode_r != 2) pSrc += 12;
1034
1035 Decompress24(mode_l, param_l, 2, pSrc, pDst,
1036 skipsamples, copysamples, TruncatedBits);
1037 Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
1038 skipsamples, copysamples, TruncatedBits);
1039 pDst += copysamples << 1;
1040 }
1041 else { // Mono
1042 Decompress24(mode_l, param_l, 1, pSrc, pDst,
1043 skipsamples, copysamples, TruncatedBits);
1044 pDst += copysamples;
1045 }
1046 }
1047 else { // 16 bit
1048 if (mode_l) pSrc += 4;
1049
1050 int step;
1051 if (Channels == 2) { // Stereo
1052 const unsigned char* const param_r = pSrc;
1053 if (mode_r) pSrc += 4;
1054
1055 step = (2 - mode_l) + (2 - mode_r);
1056 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1057 Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1058 skipsamples, copysamples);
1059 pDst += copysamples << 1;
1060 }
1061 else { // Mono
1062 step = 2 - mode_l;
1063 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1064 pDst += copysamples;
1065 }
1066 }
1067 pSrc += nextFrameOffset;
1068 }
1069
1070 // reload from disk to local buffer if needed
1071 if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1072 assumedsize = GuessSize(remainingsamples);
1073 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1074 if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1075 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1076 pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1077 }
1078 } // while
1079
1080 this->SamplePos += (SampleCount - remainingsamples);
1081 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1082 return (SampleCount - remainingsamples);
1083 }
1084 }
1085
1086 /** @brief Write sample wave data.
1087 *
1088 * Writes \a SampleCount number of sample points from the buffer pointed
1089 * by \a pBuffer and increments the position within the sample. Use this
1090 * method to directly write the sample data to disk, i.e. if you don't
1091 * want or cannot load the whole sample data into RAM.
1092 *
1093 * You have to Resize() the sample to the desired size and call
1094 * File::Save() <b>before</b> using Write().
1095 *
1096 * Note: there is currently no support for writing compressed samples.
1097 *
1098 * @param pBuffer - source buffer
1099 * @param SampleCount - number of sample points to write
1100 * @throws DLS::Exception if current sample size is too small
1101 * @throws gig::Exception if sample is compressed
1102 * @see DLS::LoadSampleData()
1103 */
1104 unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1105 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1106 return DLS::Sample::Write(pBuffer, SampleCount);
1107 }
1108
1109 /**
1110 * Allocates a decompression buffer for streaming (compressed) samples
1111 * with Sample::Read(). If you are using more than one streaming thread
1112 * in your application you <b>HAVE</b> to create a decompression buffer
1113 * for <b>EACH</b> of your streaming threads and provide it with the
1114 * Sample::Read() call in order to avoid race conditions and crashes.
1115 *
1116 * You should free the memory occupied by the allocated buffer(s) once
1117 * you don't need one of your streaming threads anymore by calling
1118 * DestroyDecompressionBuffer().
1119 *
1120 * @param MaxReadSize - the maximum size (in sample points) you ever
1121 * expect to read with one Read() call
1122 * @returns allocated decompression buffer
1123 * @see DestroyDecompressionBuffer()
1124 */
1125 buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1126 buffer_t result;
1127 const double worstCaseHeaderOverhead =
1128 (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1129 result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1130 result.pStart = new int8_t[result.Size];
1131 result.NullExtensionSize = 0;
1132 return result;
1133 }
1134
1135 /**
1136 * Free decompression buffer, previously created with
1137 * CreateDecompressionBuffer().
1138 *
1139 * @param DecompressionBuffer - previously allocated decompression
1140 * buffer to free
1141 */
1142 void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1143 if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1144 delete[] (int8_t*) DecompressionBuffer.pStart;
1145 DecompressionBuffer.pStart = NULL;
1146 DecompressionBuffer.Size = 0;
1147 DecompressionBuffer.NullExtensionSize = 0;
1148 }
1149 }
1150
1151 Sample::~Sample() {
1152 Instances--;
1153 if (!Instances && InternalDecompressionBuffer.Size) {
1154 delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1155 InternalDecompressionBuffer.pStart = NULL;
1156 InternalDecompressionBuffer.Size = 0;
1157 }
1158 if (FrameTable) delete[] FrameTable;
1159 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1160 }
1161
1162
1163
1164 // *************** DimensionRegion ***************
1165 // *
1166
1167 uint DimensionRegion::Instances = 0;
1168 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1169
1170 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1171 Instances++;
1172
1173 pSample = NULL;
1174
1175 memcpy(&Crossfade, &SamplerOptions, 4);
1176 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1177
1178 RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1179 if (_3ewa) { // if '3ewa' chunk exists
1180 _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1181 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1182 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1183 _3ewa->ReadInt16(); // unknown
1184 LFO1InternalDepth = _3ewa->ReadUint16();
1185 _3ewa->ReadInt16(); // unknown
1186 LFO3InternalDepth = _3ewa->ReadInt16();
1187 _3ewa->ReadInt16(); // unknown
1188 LFO1ControlDepth = _3ewa->ReadUint16();
1189 _3ewa->ReadInt16(); // unknown
1190 LFO3ControlDepth = _3ewa->ReadInt16();
1191 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1192 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1193 _3ewa->ReadInt16(); // unknown
1194 EG1Sustain = _3ewa->ReadUint16();
1195 EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1196 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1197 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1198 EG1ControllerInvert = eg1ctrloptions & 0x01;
1199 EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1200 EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1201 EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1202 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1203 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1204 EG2ControllerInvert = eg2ctrloptions & 0x01;
1205 EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1206 EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1207 EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1208 LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209 EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1210 EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1211 _3ewa->ReadInt16(); // unknown
1212 EG2Sustain = _3ewa->ReadUint16();
1213 EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1214 _3ewa->ReadInt16(); // unknown
1215 LFO2ControlDepth = _3ewa->ReadUint16();
1216 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1217 _3ewa->ReadInt16(); // unknown
1218 LFO2InternalDepth = _3ewa->ReadUint16();
1219 int32_t eg1decay2 = _3ewa->ReadInt32();
1220 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1221 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1222 _3ewa->ReadInt16(); // unknown
1223 EG1PreAttack = _3ewa->ReadUint16();
1224 int32_t eg2decay2 = _3ewa->ReadInt32();
1225 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1226 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1227 _3ewa->ReadInt16(); // unknown
1228 EG2PreAttack = _3ewa->ReadUint16();
1229 uint8_t velocityresponse = _3ewa->ReadUint8();
1230 if (velocityresponse < 5) {
1231 VelocityResponseCurve = curve_type_nonlinear;
1232 VelocityResponseDepth = velocityresponse;
1233 } else if (velocityresponse < 10) {
1234 VelocityResponseCurve = curve_type_linear;
1235 VelocityResponseDepth = velocityresponse - 5;
1236 } else if (velocityresponse < 15) {
1237 VelocityResponseCurve = curve_type_special;
1238 VelocityResponseDepth = velocityresponse - 10;
1239 } else {
1240 VelocityResponseCurve = curve_type_unknown;
1241 VelocityResponseDepth = 0;
1242 }
1243 uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1244 if (releasevelocityresponse < 5) {
1245 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1246 ReleaseVelocityResponseDepth = releasevelocityresponse;
1247 } else if (releasevelocityresponse < 10) {
1248 ReleaseVelocityResponseCurve = curve_type_linear;
1249 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1250 } else if (releasevelocityresponse < 15) {
1251 ReleaseVelocityResponseCurve = curve_type_special;
1252 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1253 } else {
1254 ReleaseVelocityResponseCurve = curve_type_unknown;
1255 ReleaseVelocityResponseDepth = 0;
1256 }
1257 VelocityResponseCurveScaling = _3ewa->ReadUint8();
1258 AttenuationControllerThreshold = _3ewa->ReadInt8();
1259 _3ewa->ReadInt32(); // unknown
1260 SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1261 _3ewa->ReadInt16(); // unknown
1262 uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1263 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1264 if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1265 else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1266 else DimensionBypass = dim_bypass_ctrl_none;
1267 uint8_t pan = _3ewa->ReadUint8();
1268 Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1269 SelfMask = _3ewa->ReadInt8() & 0x01;
1270 _3ewa->ReadInt8(); // unknown
1271 uint8_t lfo3ctrl = _3ewa->ReadUint8();
1272 LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1273 LFO3Sync = lfo3ctrl & 0x20; // bit 5
1274 InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1275 AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1276 uint8_t lfo2ctrl = _3ewa->ReadUint8();
1277 LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1278 LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1279 LFO2Sync = lfo2ctrl & 0x20; // bit 5
1280 bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1281 uint8_t lfo1ctrl = _3ewa->ReadUint8();
1282 LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1283 LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1284 LFO1Sync = lfo1ctrl & 0x40; // bit 6
1285 VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1286 : vcf_res_ctrl_none;
1287 uint16_t eg3depth = _3ewa->ReadUint16();
1288 EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1289 : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1290 _3ewa->ReadInt16(); // unknown
1291 ChannelOffset = _3ewa->ReadUint8() / 4;
1292 uint8_t regoptions = _3ewa->ReadUint8();
1293 MSDecode = regoptions & 0x01; // bit 0
1294 SustainDefeat = regoptions & 0x02; // bit 1
1295 _3ewa->ReadInt16(); // unknown
1296 VelocityUpperLimit = _3ewa->ReadInt8();
1297 _3ewa->ReadInt8(); // unknown
1298 _3ewa->ReadInt16(); // unknown
1299 ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1300 _3ewa->ReadInt8(); // unknown
1301 _3ewa->ReadInt8(); // unknown
1302 EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1303 uint8_t vcfcutoff = _3ewa->ReadUint8();
1304 VCFEnabled = vcfcutoff & 0x80; // bit 7
1305 VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1306 VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1307 uint8_t vcfvelscale = _3ewa->ReadUint8();
1308 VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1309 VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1310 _3ewa->ReadInt8(); // unknown
1311 uint8_t vcfresonance = _3ewa->ReadUint8();
1312 VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1313 VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1314 uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1315 VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1316 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1317 uint8_t vcfvelocity = _3ewa->ReadUint8();
1318 VCFVelocityDynamicRange = vcfvelocity % 5;
1319 VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1320 VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1321 if (VCFType == vcf_type_lowpass) {
1322 if (lfo3ctrl & 0x40) // bit 6
1323 VCFType = vcf_type_lowpassturbo;
1324 }
1325 } else { // '3ewa' chunk does not exist yet
1326 // use default values
1327 LFO3Frequency = 1.0;
1328 EG3Attack = 0.0;
1329 LFO1InternalDepth = 0;
1330 LFO3InternalDepth = 0;
1331 LFO1ControlDepth = 0;
1332 LFO3ControlDepth = 0;
1333 EG1Attack = 0.0;
1334 EG1Decay1 = 0.0;
1335 EG1Sustain = 0;
1336 EG1Release = 0.0;
1337 EG1Controller.type = eg1_ctrl_t::type_none;
1338 EG1Controller.controller_number = 0;
1339 EG1ControllerInvert = false;
1340 EG1ControllerAttackInfluence = 0;
1341 EG1ControllerDecayInfluence = 0;
1342 EG1ControllerReleaseInfluence = 0;
1343 EG2Controller.type = eg2_ctrl_t::type_none;
1344 EG2Controller.controller_number = 0;
1345 EG2ControllerInvert = false;
1346 EG2ControllerAttackInfluence = 0;
1347 EG2ControllerDecayInfluence = 0;
1348 EG2ControllerReleaseInfluence = 0;
1349 LFO1Frequency = 1.0;
1350 EG2Attack = 0.0;
1351 EG2Decay1 = 0.0;
1352 EG2Sustain = 0;
1353 EG2Release = 0.0;
1354 LFO2ControlDepth = 0;
1355 LFO2Frequency = 1.0;
1356 LFO2InternalDepth = 0;
1357 EG1Decay2 = 0.0;
1358 EG1InfiniteSustain = false;
1359 EG1PreAttack = 1000;
1360 EG2Decay2 = 0.0;
1361 EG2InfiniteSustain = false;
1362 EG2PreAttack = 1000;
1363 VelocityResponseCurve = curve_type_nonlinear;
1364 VelocityResponseDepth = 3;
1365 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1366 ReleaseVelocityResponseDepth = 3;
1367 VelocityResponseCurveScaling = 32;
1368 AttenuationControllerThreshold = 0;
1369 SampleStartOffset = 0;
1370 PitchTrack = true;
1371 DimensionBypass = dim_bypass_ctrl_none;
1372 Pan = 0;
1373 SelfMask = true;
1374 LFO3Controller = lfo3_ctrl_modwheel;
1375 LFO3Sync = false;
1376 InvertAttenuationController = false;
1377 AttenuationController.type = attenuation_ctrl_t::type_none;
1378 AttenuationController.controller_number = 0;
1379 LFO2Controller = lfo2_ctrl_internal;
1380 LFO2FlipPhase = false;
1381 LFO2Sync = false;
1382 LFO1Controller = lfo1_ctrl_internal;
1383 LFO1FlipPhase = false;
1384 LFO1Sync = false;
1385 VCFResonanceController = vcf_res_ctrl_none;
1386 EG3Depth = 0;
1387 ChannelOffset = 0;
1388 MSDecode = false;
1389 SustainDefeat = false;
1390 VelocityUpperLimit = 0;
1391 ReleaseTriggerDecay = 0;
1392 EG1Hold = false;
1393 VCFEnabled = false;
1394 VCFCutoff = 0;
1395 VCFCutoffController = vcf_cutoff_ctrl_none;
1396 VCFCutoffControllerInvert = false;
1397 VCFVelocityScale = 0;
1398 VCFResonance = 0;
1399 VCFResonanceDynamic = false;
1400 VCFKeyboardTracking = false;
1401 VCFKeyboardTrackingBreakpoint = 0;
1402 VCFVelocityDynamicRange = 0x04;
1403 VCFVelocityCurve = curve_type_linear;
1404 VCFType = vcf_type_lowpass;
1405 }
1406
1407 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1408 VelocityResponseDepth,
1409 VelocityResponseCurveScaling);
1410
1411 curve_type_t curveType = ReleaseVelocityResponseCurve;
1412 uint8_t depth = ReleaseVelocityResponseDepth;
1413
1414 // this models a strange behaviour or bug in GSt: two of the
1415 // velocity response curves for release time are not used even
1416 // if specified, instead another curve is chosen.
1417 if ((curveType == curve_type_nonlinear && depth == 0) ||
1418 (curveType == curve_type_special && depth == 4)) {
1419 curveType = curve_type_nonlinear;
1420 depth = 3;
1421 }
1422 pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1423
1424 curveType = VCFVelocityCurve;
1425 depth = VCFVelocityDynamicRange;
1426
1427 // even stranger GSt: two of the velocity response curves for
1428 // filter cutoff are not used, instead another special curve
1429 // is chosen. This curve is not used anywhere else.
1430 if ((curveType == curve_type_nonlinear && depth == 0) ||
1431 (curveType == curve_type_special && depth == 4)) {
1432 curveType = curve_type_special;
1433 depth = 5;
1434 }
1435 pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1436 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1437
1438 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1439 VelocityTable = 0;
1440 }
1441
1442 /**
1443 * Apply dimension region settings to the respective RIFF chunks. You
1444 * have to call File::Save() to make changes persistent.
1445 *
1446 * Usually there is absolutely no need to call this method explicitly.
1447 * It will be called automatically when File::Save() was called.
1448 */
1449 void DimensionRegion::UpdateChunks() {
1450 // first update base class's chunk
1451 DLS::Sampler::UpdateChunks();
1452
1453 // make sure '3ewa' chunk exists
1454 RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1455 if (!_3ewa) _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1456 uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1457
1458 // update '3ewa' chunk with DimensionRegion's current settings
1459
1460 const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1461 memcpy(&pData[0], &unknown, 4);
1462
1463 const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1464 memcpy(&pData[4], &lfo3freq, 4);
1465
1466 const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1467 memcpy(&pData[4], &eg3attack, 4);
1468
1469 // next 2 bytes unknown
1470
1471 memcpy(&pData[10], &LFO1InternalDepth, 2);
1472
1473 // next 2 bytes unknown
1474
1475 memcpy(&pData[14], &LFO3InternalDepth, 2);
1476
1477 // next 2 bytes unknown
1478
1479 memcpy(&pData[18], &LFO1ControlDepth, 2);
1480
1481 // next 2 bytes unknown
1482
1483 memcpy(&pData[22], &LFO3ControlDepth, 2);
1484
1485 const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1486 memcpy(&pData[24], &eg1attack, 4);
1487
1488 const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1489 memcpy(&pData[28], &eg1decay1, 4);
1490
1491 // next 2 bytes unknown
1492
1493 memcpy(&pData[34], &EG1Sustain, 2);
1494
1495 const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1496 memcpy(&pData[36], &eg1release, 4);
1497
1498 const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1499 memcpy(&pData[40], &eg1ctl, 1);
1500
1501 const uint8_t eg1ctrloptions =
1502 (EG1ControllerInvert) ? 0x01 : 0x00 |
1503 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1504 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1505 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1506 memcpy(&pData[41], &eg1ctrloptions, 1);
1507
1508 const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1509 memcpy(&pData[42], &eg2ctl, 1);
1510
1511 const uint8_t eg2ctrloptions =
1512 (EG2ControllerInvert) ? 0x01 : 0x00 |
1513 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1514 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1515 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1516 memcpy(&pData[43], &eg2ctrloptions, 1);
1517
1518 const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1519 memcpy(&pData[44], &lfo1freq, 4);
1520
1521 const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1522 memcpy(&pData[48], &eg2attack, 4);
1523
1524 const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1525 memcpy(&pData[52], &eg2decay1, 4);
1526
1527 // next 2 bytes unknown
1528
1529 memcpy(&pData[58], &EG2Sustain, 2);
1530
1531 const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1532 memcpy(&pData[60], &eg2release, 4);
1533
1534 // next 2 bytes unknown
1535
1536 memcpy(&pData[66], &LFO2ControlDepth, 2);
1537
1538 const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1539 memcpy(&pData[68], &lfo2freq, 4);
1540
1541 // next 2 bytes unknown
1542
1543 memcpy(&pData[72], &LFO2InternalDepth, 2);
1544
1545 const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1546 memcpy(&pData[74], &eg1decay2, 4);
1547
1548 // next 2 bytes unknown
1549
1550 memcpy(&pData[80], &EG1PreAttack, 2);
1551
1552 const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1553 memcpy(&pData[82], &eg2decay2, 4);
1554
1555 // next 2 bytes unknown
1556
1557 memcpy(&pData[88], &EG2PreAttack, 2);
1558
1559 {
1560 if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1561 uint8_t velocityresponse = VelocityResponseDepth;
1562 switch (VelocityResponseCurve) {
1563 case curve_type_nonlinear:
1564 break;
1565 case curve_type_linear:
1566 velocityresponse += 5;
1567 break;
1568 case curve_type_special:
1569 velocityresponse += 10;
1570 break;
1571 case curve_type_unknown:
1572 default:
1573 throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1574 }
1575 memcpy(&pData[90], &velocityresponse, 1);
1576 }
1577
1578 {
1579 if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1580 uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1581 switch (ReleaseVelocityResponseCurve) {
1582 case curve_type_nonlinear:
1583 break;
1584 case curve_type_linear:
1585 releasevelocityresponse += 5;
1586 break;
1587 case curve_type_special:
1588 releasevelocityresponse += 10;
1589 break;
1590 case curve_type_unknown:
1591 default:
1592 throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1593 }
1594 memcpy(&pData[91], &releasevelocityresponse, 1);
1595 }
1596
1597 memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1598
1599 memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1600
1601 // next 4 bytes unknown
1602
1603 memcpy(&pData[98], &SampleStartOffset, 2);
1604
1605 // next 2 bytes unknown
1606
1607 {
1608 uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1609 switch (DimensionBypass) {
1610 case dim_bypass_ctrl_94:
1611 pitchTrackDimensionBypass |= 0x10;
1612 break;
1613 case dim_bypass_ctrl_95:
1614 pitchTrackDimensionBypass |= 0x20;
1615 break;
1616 case dim_bypass_ctrl_none:
1617 //FIXME: should we set anything here?
1618 break;
1619 default:
1620 throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1621 }
1622 memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1623 }
1624
1625 const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1626 memcpy(&pData[103], &pan, 1);
1627
1628 const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1629 memcpy(&pData[104], &selfmask, 1);
1630
1631 // next byte unknown
1632
1633 {
1634 uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1635 if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1636 if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1637 if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1638 memcpy(&pData[106], &lfo3ctrl, 1);
1639 }
1640
1641 const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1642 memcpy(&pData[107], &attenctl, 1);
1643
1644 {
1645 uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1646 if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1647 if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1648 if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1649 memcpy(&pData[108], &lfo2ctrl, 1);
1650 }
1651
1652 {
1653 uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1654 if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1655 if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1656 if (VCFResonanceController != vcf_res_ctrl_none)
1657 lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1658 memcpy(&pData[109], &lfo1ctrl, 1);
1659 }
1660
1661 const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1662 : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1663 memcpy(&pData[110], &eg3depth, 1);
1664
1665 // next 2 bytes unknown
1666
1667 const uint8_t channeloffset = ChannelOffset * 4;
1668 memcpy(&pData[113], &channeloffset, 1);
1669
1670 {
1671 uint8_t regoptions = 0;
1672 if (MSDecode) regoptions |= 0x01; // bit 0
1673 if (SustainDefeat) regoptions |= 0x02; // bit 1
1674 memcpy(&pData[114], &regoptions, 1);
1675 }
1676
1677 // next 2 bytes unknown
1678
1679 memcpy(&pData[117], &VelocityUpperLimit, 1);
1680
1681 // next 3 bytes unknown
1682
1683 memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1684
1685 // next 2 bytes unknown
1686
1687 const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1688 memcpy(&pData[124], &eg1hold, 1);
1689
1690 const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 | /* bit 7 */
1691 (VCFCutoff) ? 0x7f : 0x00; /* lower 7 bits */
1692 memcpy(&pData[125], &vcfcutoff, 1);
1693
1694 memcpy(&pData[126], &VCFCutoffController, 1);
1695
1696 const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1697 (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1698 memcpy(&pData[127], &vcfvelscale, 1);
1699
1700 // next byte unknown
1701
1702 const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1703 (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1704 memcpy(&pData[129], &vcfresonance, 1);
1705
1706 const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1707 (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1708 memcpy(&pData[130], &vcfbreakpoint, 1);
1709
1710 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1711 VCFVelocityCurve * 5;
1712 memcpy(&pData[131], &vcfvelocity, 1);
1713
1714 const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1715 memcpy(&pData[132], &vcftype, 1);
1716 }
1717
1718 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1719 double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1720 {
1721 double* table;
1722 uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1723 if (pVelocityTables->count(tableKey)) { // if key exists
1724 table = (*pVelocityTables)[tableKey];
1725 }
1726 else {
1727 table = CreateVelocityTable(curveType, depth, scaling);
1728 (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
1729 }
1730 return table;
1731 }
1732
1733 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1734 leverage_ctrl_t decodedcontroller;
1735 switch (EncodedController) {
1736 // special controller
1737 case _lev_ctrl_none:
1738 decodedcontroller.type = leverage_ctrl_t::type_none;
1739 decodedcontroller.controller_number = 0;
1740 break;
1741 case _lev_ctrl_velocity:
1742 decodedcontroller.type = leverage_ctrl_t::type_velocity;
1743 decodedcontroller.controller_number = 0;
1744 break;
1745 case _lev_ctrl_channelaftertouch:
1746 decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1747 decodedcontroller.controller_number = 0;
1748 break;
1749
1750 // ordinary MIDI control change controller
1751 case _lev_ctrl_modwheel:
1752 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1753 decodedcontroller.controller_number = 1;
1754 break;
1755 case _lev_ctrl_breath:
1756 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1757 decodedcontroller.controller_number = 2;
1758 break;
1759 case _lev_ctrl_foot:
1760 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1761 decodedcontroller.controller_number = 4;
1762 break;
1763 case _lev_ctrl_effect1:
1764 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1765 decodedcontroller.controller_number = 12;
1766 break;
1767 case _lev_ctrl_effect2:
1768 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1769 decodedcontroller.controller_number = 13;
1770 break;
1771 case _lev_ctrl_genpurpose1:
1772 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1773 decodedcontroller.controller_number = 16;
1774 break;
1775 case _lev_ctrl_genpurpose2:
1776 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1777 decodedcontroller.controller_number = 17;
1778 break;
1779 case _lev_ctrl_genpurpose3:
1780 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1781 decodedcontroller.controller_number = 18;
1782 break;
1783 case _lev_ctrl_genpurpose4:
1784 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1785 decodedcontroller.controller_number = 19;
1786 break;
1787 case _lev_ctrl_portamentotime:
1788 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1789 decodedcontroller.controller_number = 5;
1790 break;
1791 case _lev_ctrl_sustainpedal:
1792 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1793 decodedcontroller.controller_number = 64;
1794 break;
1795 case _lev_ctrl_portamento:
1796 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1797 decodedcontroller.controller_number = 65;
1798 break;
1799 case _lev_ctrl_sostenutopedal:
1800 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1801 decodedcontroller.controller_number = 66;
1802 break;
1803 case _lev_ctrl_softpedal:
1804 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1805 decodedcontroller.controller_number = 67;
1806 break;
1807 case _lev_ctrl_genpurpose5:
1808 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1809 decodedcontroller.controller_number = 80;
1810 break;
1811 case _lev_ctrl_genpurpose6:
1812 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1813 decodedcontroller.controller_number = 81;
1814 break;
1815 case _lev_ctrl_genpurpose7:
1816 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1817 decodedcontroller.controller_number = 82;
1818 break;
1819 case _lev_ctrl_genpurpose8:
1820 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1821 decodedcontroller.controller_number = 83;
1822 break;
1823 case _lev_ctrl_effect1depth:
1824 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1825 decodedcontroller.controller_number = 91;
1826 break;
1827 case _lev_ctrl_effect2depth:
1828 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1829 decodedcontroller.controller_number = 92;
1830 break;
1831 case _lev_ctrl_effect3depth:
1832 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1833 decodedcontroller.controller_number = 93;
1834 break;
1835 case _lev_ctrl_effect4depth:
1836 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1837 decodedcontroller.controller_number = 94;
1838 break;
1839 case _lev_ctrl_effect5depth:
1840 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1841 decodedcontroller.controller_number = 95;
1842 break;
1843
1844 // unknown controller type
1845 default:
1846 throw gig::Exception("Unknown leverage controller type.");
1847 }
1848 return decodedcontroller;
1849 }
1850
1851 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1852 _lev_ctrl_t encodedcontroller;
1853 switch (DecodedController.type) {
1854 // special controller
1855 case leverage_ctrl_t::type_none:
1856 encodedcontroller = _lev_ctrl_none;
1857 break;
1858 case leverage_ctrl_t::type_velocity:
1859 encodedcontroller = _lev_ctrl_velocity;
1860 break;
1861 case leverage_ctrl_t::type_channelaftertouch:
1862 encodedcontroller = _lev_ctrl_channelaftertouch;
1863 break;
1864
1865 // ordinary MIDI control change controller
1866 case leverage_ctrl_t::type_controlchange:
1867 switch (DecodedController.controller_number) {
1868 case 1:
1869 encodedcontroller = _lev_ctrl_modwheel;
1870 break;
1871 case 2:
1872 encodedcontroller = _lev_ctrl_breath;
1873 break;
1874 case 4:
1875 encodedcontroller = _lev_ctrl_foot;
1876 break;
1877 case 12:
1878 encodedcontroller = _lev_ctrl_effect1;
1879 break;
1880 case 13:
1881 encodedcontroller = _lev_ctrl_effect2;
1882 break;
1883 case 16:
1884 encodedcontroller = _lev_ctrl_genpurpose1;
1885 break;
1886 case 17:
1887 encodedcontroller = _lev_ctrl_genpurpose2;
1888 break;
1889 case 18:
1890 encodedcontroller = _lev_ctrl_genpurpose3;
1891 break;
1892 case 19:
1893 encodedcontroller = _lev_ctrl_genpurpose4;
1894 break;
1895 case 5:
1896 encodedcontroller = _lev_ctrl_portamentotime;
1897 break;
1898 case 64:
1899 encodedcontroller = _lev_ctrl_sustainpedal;
1900 break;
1901 case 65:
1902 encodedcontroller = _lev_ctrl_portamento;
1903 break;
1904 case 66:
1905 encodedcontroller = _lev_ctrl_sostenutopedal;
1906 break;
1907 case 67:
1908 encodedcontroller = _lev_ctrl_softpedal;
1909 break;
1910 case 80:
1911 encodedcontroller = _lev_ctrl_genpurpose5;
1912 break;
1913 case 81:
1914 encodedcontroller = _lev_ctrl_genpurpose6;
1915 break;
1916 case 82:
1917 encodedcontroller = _lev_ctrl_genpurpose7;
1918 break;
1919 case 83:
1920 encodedcontroller = _lev_ctrl_genpurpose8;
1921 break;
1922 case 91:
1923 encodedcontroller = _lev_ctrl_effect1depth;
1924 break;
1925 case 92:
1926 encodedcontroller = _lev_ctrl_effect2depth;
1927 break;
1928 case 93:
1929 encodedcontroller = _lev_ctrl_effect3depth;
1930 break;
1931 case 94:
1932 encodedcontroller = _lev_ctrl_effect4depth;
1933 break;
1934 case 95:
1935 encodedcontroller = _lev_ctrl_effect5depth;
1936 break;
1937 default:
1938 throw gig::Exception("leverage controller number is not supported by the gig format");
1939 }
1940 default:
1941 throw gig::Exception("Unknown leverage controller type.");
1942 }
1943 return encodedcontroller;
1944 }
1945
1946 DimensionRegion::~DimensionRegion() {
1947 Instances--;
1948 if (!Instances) {
1949 // delete the velocity->volume tables
1950 VelocityTableMap::iterator iter;
1951 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
1952 double* pTable = iter->second;
1953 if (pTable) delete[] pTable;
1954 }
1955 pVelocityTables->clear();
1956 delete pVelocityTables;
1957 pVelocityTables = NULL;
1958 }
1959 if (VelocityTable) delete[] VelocityTable;
1960 }
1961
1962 /**
1963 * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1964 * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1965 * and VelocityResponseCurveScaling) involved are taken into account to
1966 * calculate the amplitude factor. Use this method when a key was
1967 * triggered to get the volume with which the sample should be played
1968 * back.
1969 *
1970 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
1971 * @returns amplitude factor (between 0.0 and 1.0)
1972 */
1973 double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1974 return pVelocityAttenuationTable[MIDIKeyVelocity];
1975 }
1976
1977 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1978 return pVelocityReleaseTable[MIDIKeyVelocity];
1979 }
1980
1981 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1982 return pVelocityCutoffTable[MIDIKeyVelocity];
1983 }
1984
1985 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1986
1987 // line-segment approximations of the 15 velocity curves
1988
1989 // linear
1990 const int lin0[] = { 1, 1, 127, 127 };
1991 const int lin1[] = { 1, 21, 127, 127 };
1992 const int lin2[] = { 1, 45, 127, 127 };
1993 const int lin3[] = { 1, 74, 127, 127 };
1994 const int lin4[] = { 1, 127, 127, 127 };
1995
1996 // non-linear
1997 const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1998 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1999 127, 127 };
2000 const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2001 127, 127 };
2002 const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2003 127, 127 };
2004 const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2005
2006 // special
2007 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2008 113, 127, 127, 127 };
2009 const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2010 118, 127, 127, 127 };
2011 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2012 85, 90, 91, 127, 127, 127 };
2013 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2014 117, 127, 127, 127 };
2015 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2016 127, 127 };
2017
2018 // this is only used by the VCF velocity curve
2019 const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2020 91, 127, 127, 127 };
2021
2022 const int* const curves[] = { non0, non1, non2, non3, non4,
2023 lin0, lin1, lin2, lin3, lin4,
2024 spe0, spe1, spe2, spe3, spe4, spe5 };
2025
2026 double* const table = new double[128];
2027
2028 const int* curve = curves[curveType * 5 + depth];
2029 const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2030
2031 table[0] = 0;
2032 for (int x = 1 ; x < 128 ; x++) {
2033
2034 if (x > curve[2]) curve += 2;
2035 double y = curve[1] + (x - curve[0]) *
2036 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2037 y = y / 127;
2038
2039 // Scale up for s > 20, down for s < 20. When
2040 // down-scaling, the curve still ends at 1.0.
2041 if (s < 20 && y >= 0.5)
2042 y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2043 else
2044 y = y * (s / 20.0);
2045 if (y > 1) y = 1;
2046
2047 table[x] = y;
2048 }
2049 return table;
2050 }
2051
2052
2053 // *************** Region ***************
2054 // *
2055
2056 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2057 // Initialization
2058 Dimensions = 0;
2059 for (int i = 0; i < 256; i++) {
2060 pDimensionRegions[i] = NULL;
2061 }
2062 Layers = 1;
2063 File* file = (File*) GetParent()->GetParent();
2064 int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2065
2066 // Actual Loading
2067
2068 LoadDimensionRegions(rgnList);
2069
2070 RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2071 if (_3lnk) {
2072 DimensionRegions = _3lnk->ReadUint32();
2073 for (int i = 0; i < dimensionBits; i++) {
2074 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2075 uint8_t bits = _3lnk->ReadUint8();
2076 _3lnk->ReadUint8(); // probably the position of the dimension
2077 _3lnk->ReadUint8(); // unknown
2078 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2079 if (dimension == dimension_none) { // inactive dimension
2080 pDimensionDefinitions[i].dimension = dimension_none;
2081 pDimensionDefinitions[i].bits = 0;
2082 pDimensionDefinitions[i].zones = 0;
2083 pDimensionDefinitions[i].split_type = split_type_bit;
2084 pDimensionDefinitions[i].zone_size = 0;
2085 }
2086 else { // active dimension
2087 pDimensionDefinitions[i].dimension = dimension;
2088 pDimensionDefinitions[i].bits = bits;
2089 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2090 pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2091 dimension == dimension_samplechannel ||
2092 dimension == dimension_releasetrigger ||
2093 dimension == dimension_keyboard ||
2094 dimension == dimension_roundrobin ||
2095 dimension == dimension_random) ? split_type_bit
2096 : split_type_normal;
2097 pDimensionDefinitions[i].zone_size =
2098 (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2099 : 0;
2100 Dimensions++;
2101
2102 // if this is a layer dimension, remember the amount of layers
2103 if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2104 }
2105 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2106 }
2107 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2108
2109 // if there's a velocity dimension and custom velocity zone splits are used,
2110 // update the VelocityTables in the dimension regions
2111 UpdateVelocityTable();
2112
2113 // jump to start of the wave pool indices (if not already there)
2114 if (file->pVersion && file->pVersion->major == 3)
2115 _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2116 else
2117 _3lnk->SetPos(44);
2118
2119 // load sample references
2120 for (uint i = 0; i < DimensionRegions; i++) {
2121 uint32_t wavepoolindex = _3lnk->ReadUint32();
2122 pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2123 }
2124 }
2125
2126 // make sure there is at least one dimension region
2127 if (!DimensionRegions) {
2128 RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2129 if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2130 RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2131 pDimensionRegions[0] = new DimensionRegion(_3ewl);
2132 DimensionRegions = 1;
2133 }
2134 }
2135
2136 /**
2137 * Apply Region settings and all its DimensionRegions to the respective
2138 * RIFF chunks. You have to call File::Save() to make changes persistent.
2139 *
2140 * Usually there is absolutely no need to call this method explicitly.
2141 * It will be called automatically when File::Save() was called.
2142 *
2143 * @throws gig::Exception if samples cannot be dereferenced
2144 */
2145 void Region::UpdateChunks() {
2146 // first update base class's chunks
2147 DLS::Region::UpdateChunks();
2148
2149 // update dimension region's chunks
2150 for (int i = 0; i < DimensionRegions; i++) {
2151 pDimensionRegions[i]->UpdateChunks();
2152 }
2153
2154 File* pFile = (File*) GetParent()->GetParent();
2155 const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2156 const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2157
2158 // make sure '3lnk' chunk exists
2159 RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2160 if (!_3lnk) {
2161 const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2162 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2163 }
2164
2165 // update dimension definitions in '3lnk' chunk
2166 uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2167 for (int i = 0; i < iMaxDimensions; i++) {
2168 pData[i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2169 pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2170 // next 2 bytes unknown
2171 pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2172 // next 3 bytes unknown
2173 }
2174
2175 // update wave pool table in '3lnk' chunk
2176 const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2177 for (uint i = 0; i < iMaxDimensionRegions; i++) {
2178 int iWaveIndex = -1;
2179 if (i < DimensionRegions) {
2180 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2181 File::SampleList::iterator iter = pFile->pSamples->begin();
2182 File::SampleList::iterator end = pFile->pSamples->end();
2183 for (int index = 0; iter != end; ++iter, ++index) {
2184 if (*iter == pDimensionRegions[i]->pSample) {
2185 iWaveIndex = index;
2186 break;
2187 }
2188 }
2189 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2190 }
2191 memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2192 }
2193 }
2194
2195 void Region::LoadDimensionRegions(RIFF::List* rgn) {
2196 RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
2197 if (_3prg) {
2198 int dimensionRegionNr = 0;
2199 RIFF::List* _3ewl = _3prg->GetFirstSubList();
2200 while (_3ewl) {
2201 if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2202 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
2203 dimensionRegionNr++;
2204 }
2205 _3ewl = _3prg->GetNextSubList();
2206 }
2207 if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
2208 }
2209 }
2210
2211 void Region::UpdateVelocityTable() {
2212 // get velocity dimension's index
2213 int veldim = -1;
2214 for (int i = 0 ; i < Dimensions ; i++) {
2215 if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2216 veldim = i;
2217 break;
2218 }
2219 }
2220 if (veldim == -1) return;
2221
2222 int step = 1;
2223 for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2224 int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2225 int end = step * pDimensionDefinitions[veldim].zones;
2226
2227 // loop through all dimension regions for all dimensions except the velocity dimension
2228 int dim[8] = { 0 };
2229 for (int i = 0 ; i < DimensionRegions ; i++) {
2230
2231 if (pDimensionRegions[i]->VelocityUpperLimit) {
2232 // create the velocity table
2233 uint8_t* table = pDimensionRegions[i]->VelocityTable;
2234 if (!table) {
2235 table = new uint8_t[128];
2236 pDimensionRegions[i]->VelocityTable = table;
2237 }
2238 int tableidx = 0;
2239 int velocityZone = 0;
2240 for (int k = i ; k < end ; k += step) {
2241 DimensionRegion *d = pDimensionRegions[k];
2242 for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2243 velocityZone++;
2244 }
2245 } else {
2246 if (pDimensionRegions[i]->VelocityTable) {
2247 delete[] pDimensionRegions[i]->VelocityTable;
2248 pDimensionRegions[i]->VelocityTable = 0;
2249 }
2250 }
2251
2252 int j;
2253 int shift = 0;
2254 for (j = 0 ; j < Dimensions ; j++) {
2255 if (j == veldim) i += skipveldim; // skip velocity dimension
2256 else {
2257 dim[j]++;
2258 if (dim[j] < pDimensionDefinitions[j].zones) break;
2259 else {
2260 // skip unused dimension regions
2261 dim[j] = 0;
2262 i += ((1 << pDimensionDefinitions[j].bits) -
2263 pDimensionDefinitions[j].zones) << shift;
2264 }
2265 }
2266 shift += pDimensionDefinitions[j].bits;
2267 }
2268 if (j == Dimensions) break;
2269 }
2270 }
2271
2272 /** @brief Einstein would have dreamed of it - create a new dimension.
2273 *
2274 * Creates a new dimension with the dimension definition given by
2275 * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2276 * There is a hard limit of dimensions and total amount of "bits" all
2277 * dimensions can have. This limit is dependant to what gig file format
2278 * version this file refers to. The gig v2 (and lower) format has a
2279 * dimension limit and total amount of bits limit of 5, whereas the gig v3
2280 * format has a limit of 8.
2281 *
2282 * @param pDimDef - defintion of the new dimension
2283 * @throws gig::Exception if dimension of the same type exists already
2284 * @throws gig::Exception if amount of dimensions or total amount of
2285 * dimension bits limit is violated
2286 */
2287 void Region::AddDimension(dimension_def_t* pDimDef) {
2288 // check if max. amount of dimensions reached
2289 File* file = (File*) GetParent()->GetParent();
2290 const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2291 if (Dimensions >= iMaxDimensions)
2292 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2293 // check if max. amount of dimension bits reached
2294 int iCurrentBits = 0;
2295 for (int i = 0; i < Dimensions; i++)
2296 iCurrentBits += pDimensionDefinitions[i].bits;
2297 if (iCurrentBits >= iMaxDimensions)
2298 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2299 const int iNewBits = iCurrentBits + pDimDef->bits;
2300 if (iNewBits > iMaxDimensions)
2301 throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2302 // check if there's already a dimensions of the same type
2303 for (int i = 0; i < Dimensions; i++)
2304 if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2305 throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2306
2307 // assign definition of new dimension
2308 pDimensionDefinitions[Dimensions] = *pDimDef;
2309
2310 // create new dimension region(s) for this new dimension
2311 for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2312 //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2313 RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2314 pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2315 DimensionRegions++;
2316 }
2317
2318 Dimensions++;
2319
2320 // if this is a layer dimension, update 'Layers' attribute
2321 if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2322
2323 UpdateVelocityTable();
2324 }
2325
2326 /** @brief Delete an existing dimension.
2327 *
2328 * Deletes the dimension given by \a pDimDef and deletes all respective
2329 * dimension regions, that is all dimension regions where the dimension's
2330 * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2331 * for example this would delete all dimension regions for the case(s)
2332 * where the sustain pedal is pressed down.
2333 *
2334 * @param pDimDef - dimension to delete
2335 * @throws gig::Exception if given dimension cannot be found
2336 */
2337 void Region::DeleteDimension(dimension_def_t* pDimDef) {
2338 // get dimension's index
2339 int iDimensionNr = -1;
2340 for (int i = 0; i < Dimensions; i++) {
2341 if (&pDimensionDefinitions[i] == pDimDef) {
2342 iDimensionNr = i;
2343 break;
2344 }
2345 }
2346 if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2347
2348 // get amount of bits below the dimension to delete
2349 int iLowerBits = 0;
2350 for (int i = 0; i < iDimensionNr; i++)
2351 iLowerBits += pDimensionDefinitions[i].bits;
2352
2353 // get amount ot bits above the dimension to delete
2354 int iUpperBits = 0;
2355 for (int i = iDimensionNr + 1; i < Dimensions; i++)
2356 iUpperBits += pDimensionDefinitions[i].bits;
2357
2358 // delete dimension regions which belong to the given dimension
2359 // (that is where the dimension's bit > 0)
2360 for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2361 for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2362 for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2363 int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2364 iObsoleteBit << iLowerBits |
2365 iLowerBit;
2366 delete pDimensionRegions[iToDelete];
2367 pDimensionRegions[iToDelete] = NULL;
2368 DimensionRegions--;
2369 }
2370 }
2371 }
2372
2373 // defrag pDimensionRegions array
2374 // (that is remove the NULL spaces within the pDimensionRegions array)
2375 for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2376 if (!pDimensionRegions[iTo]) {
2377 if (iFrom <= iTo) iFrom = iTo + 1;
2378 while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2379 if (iFrom < 256 && pDimensionRegions[iFrom]) {
2380 pDimensionRegions[iTo] = pDimensionRegions[iFrom];
2381 pDimensionRegions[iFrom] = NULL;
2382 }
2383 }
2384 }
2385
2386 // 'remove' dimension definition
2387 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2388 pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2389 }
2390 pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2391 pDimensionDefinitions[Dimensions - 1].bits = 0;
2392 pDimensionDefinitions[Dimensions - 1].zones = 0;
2393
2394 Dimensions--;
2395
2396 // if this was a layer dimension, update 'Layers' attribute
2397 if (pDimDef->dimension == dimension_layer) Layers = 1;
2398 }
2399
2400 Region::~Region() {
2401 for (int i = 0; i < 256; i++) {
2402 if (pDimensionRegions[i]) delete pDimensionRegions[i];
2403 }
2404 }
2405
2406 /**
2407 * Use this method in your audio engine to get the appropriate dimension
2408 * region with it's articulation data for the current situation. Just
2409 * call the method with the current MIDI controller values and you'll get
2410 * the DimensionRegion with the appropriate articulation data for the
2411 * current situation (for this Region of course only). To do that you'll
2412 * first have to look which dimensions with which controllers and in
2413 * which order are defined for this Region when you load the .gig file.
2414 * Special cases are e.g. layer or channel dimensions where you just put
2415 * in the index numbers instead of a MIDI controller value (means 0 for
2416 * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
2417 * etc.).
2418 *
2419 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
2420 * @returns adress to the DimensionRegion for the given situation
2421 * @see pDimensionDefinitions
2422 * @see Dimensions
2423 */
2424 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2425 uint8_t bits;
2426 int veldim = -1;
2427 int velbitpos;
2428 int bitpos = 0;
2429 int dimregidx = 0;
2430 for (uint i = 0; i < Dimensions; i++) {
2431 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2432 // the velocity dimension must be handled after the other dimensions
2433 veldim = i;
2434 velbitpos = bitpos;
2435 } else {
2436 switch (pDimensionDefinitions[i].split_type) {
2437 case split_type_normal:
2438 bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2439 break;
2440 case split_type_bit: // the value is already the sought dimension bit number
2441 const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2442 bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2443 break;
2444 }
2445 dimregidx |= bits << bitpos;
2446 }
2447 bitpos += pDimensionDefinitions[i].bits;
2448 }
2449 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2450 if (veldim != -1) {
2451 // (dimreg is now the dimension region for the lowest velocity)
2452 if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2453 bits = dimreg->VelocityTable[DimValues[veldim]];
2454 else // normal split type
2455 bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2456
2457 dimregidx |= bits << velbitpos;
2458 dimreg = pDimensionRegions[dimregidx];
2459 }
2460 return dimreg;
2461 }
2462
2463 /**
2464 * Returns the appropriate DimensionRegion for the given dimension bit
2465 * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
2466 * instead of calling this method directly!
2467 *
2468 * @param DimBits Bit numbers for dimension 0 to 7
2469 * @returns adress to the DimensionRegion for the given dimension
2470 * bit numbers
2471 * @see GetDimensionRegionByValue()
2472 */
2473 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
2474 return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
2475 << pDimensionDefinitions[5].bits | DimBits[5])
2476 << pDimensionDefinitions[4].bits | DimBits[4])
2477 << pDimensionDefinitions[3].bits | DimBits[3])
2478 << pDimensionDefinitions[2].bits | DimBits[2])
2479 << pDimensionDefinitions[1].bits | DimBits[1])
2480 << pDimensionDefinitions[0].bits | DimBits[0]];
2481 }
2482
2483 /**
2484 * Returns pointer address to the Sample referenced with this region.
2485 * This is the global Sample for the entire Region (not sure if this is
2486 * actually used by the Gigasampler engine - I would only use the Sample
2487 * referenced by the appropriate DimensionRegion instead of this sample).
2488 *
2489 * @returns address to Sample or NULL if there is no reference to a
2490 * sample saved in the .gig file
2491 */
2492 Sample* Region::GetSample() {
2493 if (pSample) return static_cast<gig::Sample*>(pSample);
2494 else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2495 }
2496
2497 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2498 if ((int32_t)WavePoolTableIndex == -1) return NULL;
2499 File* file = (File*) GetParent()->GetParent();
2500 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2501 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2502 Sample* sample = file->GetFirstSample(pProgress);
2503 while (sample) {
2504 if (sample->ulWavePoolOffset == soughtoffset &&
2505 sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2506 sample = file->GetNextSample();
2507 }
2508 return NULL;
2509 }
2510
2511
2512
2513 // *************** Instrument ***************
2514 // *
2515
2516 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2517 // Initialization
2518 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2519
2520 // Loading
2521 RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
2522 if (lart) {
2523 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2524 if (_3ewg) {
2525 EffectSend = _3ewg->ReadUint16();
2526 Attenuation = _3ewg->ReadInt32();
2527 FineTune = _3ewg->ReadInt16();
2528 PitchbendRange = _3ewg->ReadInt16();
2529 uint8_t dimkeystart = _3ewg->ReadUint8();
2530 PianoReleaseMode = dimkeystart & 0x01;
2531 DimensionKeyRange.low = dimkeystart >> 1;
2532 DimensionKeyRange.high = _3ewg->ReadUint8();
2533 }
2534 }
2535
2536 if (!pRegions) pRegions = new RegionList;
2537 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2538 if (lrgn) {
2539 RIFF::List* rgn = lrgn->GetFirstSubList();
2540 while (rgn) {
2541 if (rgn->GetListType() == LIST_TYPE_RGN) {
2542 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2543 pRegions->push_back(new Region(this, rgn));
2544 }
2545 rgn = lrgn->GetNextSubList();
2546 }
2547 // Creating Region Key Table for fast lookup
2548 UpdateRegionKeyTable();
2549 }
2550
2551 __notify_progress(pProgress, 1.0f); // notify done
2552 }
2553
2554 void Instrument::UpdateRegionKeyTable() {
2555 RegionList::iterator iter = pRegions->begin();
2556 RegionList::iterator end = pRegions->end();
2557 for (; iter != end; ++iter) {
2558 gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2559 for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2560 RegionKeyTable[iKey] = pRegion;
2561 }
2562 }
2563 }
2564
2565 Instrument::~Instrument() {
2566 }
2567
2568 /**
2569 * Apply Instrument with all its Regions to the respective RIFF chunks.
2570 * You have to call File::Save() to make changes persistent.
2571 *
2572 * Usually there is absolutely no need to call this method explicitly.
2573 * It will be called automatically when File::Save() was called.
2574 *
2575 * @throws gig::Exception if samples cannot be dereferenced
2576 */
2577 void Instrument::UpdateChunks() {
2578 // first update base classes' chunks
2579 DLS::Instrument::UpdateChunks();
2580
2581 // update Regions' chunks
2582 {
2583 RegionList::iterator iter = pRegions->begin();
2584 RegionList::iterator end = pRegions->end();
2585 for (; iter != end; ++iter)
2586 (*iter)->UpdateChunks();
2587 }
2588
2589 // make sure 'lart' RIFF list chunk exists
2590 RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2591 if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2592 // make sure '3ewg' RIFF chunk exists
2593 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2594 if (!_3ewg) _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2595 // update '3ewg' RIFF chunk
2596 uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2597 memcpy(&pData[0], &EffectSend, 2);
2598 memcpy(&pData[2], &Attenuation, 4);
2599 memcpy(&pData[6], &FineTune, 2);
2600 memcpy(&pData[8], &PitchbendRange, 2);
2601 const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2602 DimensionKeyRange.low << 1;
2603 memcpy(&pData[10], &dimkeystart, 1);
2604 memcpy(&pData[11], &DimensionKeyRange.high, 1);
2605 }
2606
2607 /**
2608 * Returns the appropriate Region for a triggered note.
2609 *
2610 * @param Key MIDI Key number of triggered note / key (0 - 127)
2611 * @returns pointer adress to the appropriate Region or NULL if there
2612 * there is no Region defined for the given \a Key
2613 */
2614 Region* Instrument::GetRegion(unsigned int Key) {
2615 if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2616 return RegionKeyTable[Key];
2617
2618 /*for (int i = 0; i < Regions; i++) {
2619 if (Key <= pRegions[i]->KeyRange.high &&
2620 Key >= pRegions[i]->KeyRange.low) return pRegions[i];
2621 }
2622 return NULL;*/
2623 }
2624
2625 /**
2626 * Returns the first Region of the instrument. You have to call this
2627 * method once before you use GetNextRegion().
2628 *
2629 * @returns pointer address to first region or NULL if there is none
2630 * @see GetNextRegion()
2631 */
2632 Region* Instrument::GetFirstRegion() {
2633 if (!pRegions) return NULL;
2634 RegionsIterator = pRegions->begin();
2635 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2636 }
2637
2638 /**
2639 * Returns the next Region of the instrument. You have to call
2640 * GetFirstRegion() once before you can use this method. By calling this
2641 * method multiple times it iterates through the available Regions.
2642 *
2643 * @returns pointer address to the next region or NULL if end reached
2644 * @see GetFirstRegion()
2645 */
2646 Region* Instrument::GetNextRegion() {
2647 if (!pRegions) return NULL;
2648 RegionsIterator++;
2649 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2650 }
2651
2652 Region* Instrument::AddRegion() {
2653 // create new Region object (and its RIFF chunks)
2654 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2655 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2656 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2657 Region* pNewRegion = new Region(this, rgn);
2658 pRegions->push_back(pNewRegion);
2659 Regions = pRegions->size();
2660 // update Region key table for fast lookup
2661 UpdateRegionKeyTable();
2662 // done
2663 return pNewRegion;
2664 }
2665
2666 void Instrument::DeleteRegion(Region* pRegion) {
2667 if (!pRegions) return;
2668 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2669 // update Region key table for fast lookup
2670 UpdateRegionKeyTable();
2671 }
2672
2673
2674
2675 // *************** File ***************
2676 // *
2677
2678 File::File() : DLS::File() {
2679 }
2680
2681 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2682 }
2683
2684 Sample* File::GetFirstSample(progress_t* pProgress) {
2685 if (!pSamples) LoadSamples(pProgress);
2686 if (!pSamples) return NULL;
2687 SamplesIterator = pSamples->begin();
2688 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2689 }
2690
2691 Sample* File::GetNextSample() {
2692 if (!pSamples) return NULL;
2693 SamplesIterator++;
2694 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2695 }
2696
2697 /** @brief Add a new sample.
2698 *
2699 * This will create a new Sample object for the gig file. You have to
2700 * call Save() to make this persistent to the file.
2701 *
2702 * @returns pointer to new Sample object
2703 */
2704 Sample* File::AddSample() {
2705 if (!pSamples) LoadSamples();
2706 __ensureMandatoryChunksExist();
2707 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2708 // create new Sample object and its respective 'wave' list chunk
2709 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2710 Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2711 pSamples->push_back(pSample);
2712 return pSample;
2713 }
2714
2715 /** @brief Delete a sample.
2716 *
2717 * This will delete the given Sample object from the gig file. You have
2718 * to call Save() to make this persistent to the file.
2719 *
2720 * @param pSample - sample to delete
2721 * @throws gig::Exception if given sample could not be found
2722 */
2723 void File::DeleteSample(Sample* pSample) {
2724 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2725 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2726 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2727 pSamples->erase(iter);
2728 delete pSample;
2729 }
2730
2731 void File::LoadSamples() {
2732 LoadSamples(NULL);
2733 }
2734
2735 void File::LoadSamples(progress_t* pProgress) {
2736 if (!pSamples) pSamples = new SampleList;
2737
2738 RIFF::File* file = pRIFF;
2739
2740 // just for progress calculation
2741 int iSampleIndex = 0;
2742 int iTotalSamples = WavePoolCount;
2743
2744 // check if samples should be loaded from extension files
2745 int lastFileNo = 0;
2746 for (int i = 0 ; i < WavePoolCount ; i++) {
2747 if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2748 }
2749 String name(pRIFF->GetFileName());
2750 int nameLen = name.length();
2751 char suffix[6];
2752 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2753
2754 for (int fileNo = 0 ; ; ) {
2755 RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2756 if (wvpl) {
2757 unsigned long wvplFileOffset = wvpl->GetFilePos();
2758 RIFF::List* wave = wvpl->GetFirstSubList();
2759 while (wave) {
2760 if (wave->GetListType() == LIST_TYPE_WAVE) {
2761 // notify current progress
2762 const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2763 __notify_progress(pProgress, subprogress);
2764
2765 unsigned long waveFileOffset = wave->GetFilePos();
2766 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2767
2768 iSampleIndex++;
2769 }
2770 wave = wvpl->GetNextSubList();
2771 }
2772
2773 if (fileNo == lastFileNo) break;
2774
2775 // open extension file (*.gx01, *.gx02, ...)
2776 fileNo++;
2777 sprintf(suffix, ".gx%02d", fileNo);
2778 name.replace(nameLen, 5, suffix);
2779 file = new RIFF::File(name);
2780 ExtensionFiles.push_back(file);
2781 } else break;
2782 }
2783
2784 __notify_progress(pProgress, 1.0); // notify done
2785 }
2786
2787 Instrument* File::GetFirstInstrument() {
2788 if (!pInstruments) LoadInstruments();
2789 if (!pInstruments) return NULL;
2790 InstrumentsIterator = pInstruments->begin();
2791 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2792 }
2793
2794 Instrument* File::GetNextInstrument() {
2795 if (!pInstruments) return NULL;
2796 InstrumentsIterator++;
2797 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2798 }
2799
2800 /**
2801 * Returns the instrument with the given index.
2802 *
2803 * @param index - number of the sought instrument (0..n)
2804 * @param pProgress - optional: callback function for progress notification
2805 * @returns sought instrument or NULL if there's no such instrument
2806 */
2807 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2808 if (!pInstruments) {
2809 // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2810
2811 // sample loading subtask
2812 progress_t subprogress;
2813 __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2814 __notify_progress(&subprogress, 0.0f);
2815 GetFirstSample(&subprogress); // now force all samples to be loaded
2816 __notify_progress(&subprogress, 1.0f);
2817
2818 // instrument loading subtask
2819 if (pProgress && pProgress->callback) {
2820 subprogress.__range_min = subprogress.__range_max;
2821 subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2822 }
2823 __notify_progress(&subprogress, 0.0f);
2824 LoadInstruments(&subprogress);
2825 __notify_progress(&subprogress, 1.0f);
2826 }
2827 if (!pInstruments) return NULL;
2828 InstrumentsIterator = pInstruments->begin();
2829 for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2830 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2831 InstrumentsIterator++;
2832 }
2833 return NULL;
2834 }
2835
2836 /** @brief Add a new instrument definition.
2837 *
2838 * This will create a new Instrument object for the gig file. You have
2839 * to call Save() to make this persistent to the file.
2840 *
2841 * @returns pointer to new Instrument object
2842 */
2843 Instrument* File::AddInstrument() {
2844 if (!pInstruments) LoadInstruments();
2845 __ensureMandatoryChunksExist();
2846 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2847 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2848 Instrument* pInstrument = new Instrument(this, lstInstr);
2849 pInstruments->push_back(pInstrument);
2850 return pInstrument;
2851 }
2852
2853 /** @brief Delete an instrument.
2854 *
2855 * This will delete the given Instrument object from the gig file. You
2856 * have to call Save() to make this persistent to the file.
2857 *
2858 * @param pInstrument - instrument to delete
2859 * @throws gig::Excption if given instrument could not be found
2860 */
2861 void File::DeleteInstrument(Instrument* pInstrument) {
2862 if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2863 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2864 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2865 pInstruments->erase(iter);
2866 delete pInstrument;
2867 }
2868
2869 void File::LoadInstruments() {
2870 LoadInstruments(NULL);
2871 }
2872
2873 void File::LoadInstruments(progress_t* pProgress) {
2874 if (!pInstruments) pInstruments = new InstrumentList;
2875 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2876 if (lstInstruments) {
2877 int iInstrumentIndex = 0;
2878 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2879 while (lstInstr) {
2880 if (lstInstr->GetListType() == LIST_TYPE_INS) {
2881 // notify current progress
2882 const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2883 __notify_progress(pProgress, localProgress);
2884
2885 // divide local progress into subprogress for loading current Instrument
2886 progress_t subprogress;
2887 __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2888
2889 pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2890
2891 iInstrumentIndex++;
2892 }
2893 lstInstr = lstInstruments->GetNextSubList();
2894 }
2895 __notify_progress(pProgress, 1.0); // notify done
2896 }
2897 }
2898
2899
2900
2901 // *************** Exception ***************
2902 // *
2903
2904 Exception::Exception(String Message) : DLS::Exception(Message) {
2905 }
2906
2907 void Exception::PrintMessage() {
2908 std::cout << "gig::Exception: " << Message << std::endl;
2909 }
2910
2911
2912 // *************** functions ***************
2913 // *
2914
2915 /**
2916 * Returns the name of this C++ library. This is usually "libgig" of
2917 * course. This call is equivalent to RIFF::libraryName() and
2918 * DLS::libraryName().
2919 */
2920 String libraryName() {
2921 return PACKAGE;
2922 }
2923
2924 /**
2925 * Returns version of this C++ library. This call is equivalent to
2926 * RIFF::libraryVersion() and DLS::libraryVersion().
2927 */
2928 String libraryVersion() {
2929 return VERSION;
2930 }
2931
2932 } // namespace gig

  ViewVC Help
Powered by ViewVC