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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 858 - (show annotations) (download)
Sat May 6 11:29:29 2006 UTC (17 years, 10 months ago) by persson
File size: 133269 byte(s)
* added support for more than one custom velocity split inside a
  region

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;
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 pExternalDecompressionBuffer (optional) external buffer to use for decompression
726 * @returns number of successfully read sample points
727 * @see CreateDecompressionBuffer()
728 */
729 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {
730 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
731 uint8_t* pDst = (uint8_t*) pBuffer;
732
733 SetPos(pPlaybackState->position); // recover position from the last time
734
735 if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined
736
737 switch (this->LoopType) {
738
739 case loop_type_bidirectional: { //TODO: not tested yet!
740 do {
741 // if not endless loop check if max. number of loop cycles have been passed
742 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
743
744 if (!pPlaybackState->reverse) { // forward playback
745 do {
746 samplestoloopend = this->LoopEnd - GetPos();
747 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
748 samplestoread -= readsamples;
749 totalreadsamples += readsamples;
750 if (readsamples == samplestoloopend) {
751 pPlaybackState->reverse = true;
752 break;
753 }
754 } while (samplestoread && readsamples);
755 }
756 else { // backward playback
757
758 // as we can only read forward from disk, we have to
759 // determine the end position within the loop first,
760 // read forward from that 'end' and finally after
761 // reading, swap all sample frames so it reflects
762 // backward playback
763
764 unsigned long swapareastart = totalreadsamples;
765 unsigned long loopoffset = GetPos() - this->LoopStart;
766 unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
767 unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
768
769 SetPos(reverseplaybackend);
770
771 // read samples for backward playback
772 do {
773 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
774 samplestoreadinloop -= readsamples;
775 samplestoread -= readsamples;
776 totalreadsamples += readsamples;
777 } while (samplestoreadinloop && readsamples);
778
779 SetPos(reverseplaybackend); // pretend we really read backwards
780
781 if (reverseplaybackend == this->LoopStart) {
782 pPlaybackState->loop_cycles_left--;
783 pPlaybackState->reverse = false;
784 }
785
786 // reverse the sample frames for backward playback
787 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
788 }
789 } while (samplestoread && readsamples);
790 break;
791 }
792
793 case loop_type_backward: { // TODO: not tested yet!
794 // forward playback (not entered the loop yet)
795 if (!pPlaybackState->reverse) do {
796 samplestoloopend = this->LoopEnd - GetPos();
797 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
798 samplestoread -= readsamples;
799 totalreadsamples += readsamples;
800 if (readsamples == samplestoloopend) {
801 pPlaybackState->reverse = true;
802 break;
803 }
804 } while (samplestoread && readsamples);
805
806 if (!samplestoread) break;
807
808 // as we can only read forward from disk, we have to
809 // determine the end position within the loop first,
810 // read forward from that 'end' and finally after
811 // reading, swap all sample frames so it reflects
812 // backward playback
813
814 unsigned long swapareastart = totalreadsamples;
815 unsigned long loopoffset = GetPos() - this->LoopStart;
816 unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)
817 : samplestoread;
818 unsigned long reverseplaybackend = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);
819
820 SetPos(reverseplaybackend);
821
822 // read samples for backward playback
823 do {
824 // if not endless loop check if max. number of loop cycles have been passed
825 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
826 samplestoloopend = this->LoopEnd - GetPos();
827 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
828 samplestoreadinloop -= readsamples;
829 samplestoread -= readsamples;
830 totalreadsamples += readsamples;
831 if (readsamples == samplestoloopend) {
832 pPlaybackState->loop_cycles_left--;
833 SetPos(this->LoopStart);
834 }
835 } while (samplestoreadinloop && readsamples);
836
837 SetPos(reverseplaybackend); // pretend we really read backwards
838
839 // reverse the sample frames for backward playback
840 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
841 break;
842 }
843
844 default: case loop_type_normal: {
845 do {
846 // if not endless loop check if max. number of loop cycles have been passed
847 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
848 samplestoloopend = this->LoopEnd - GetPos();
849 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
850 samplestoread -= readsamples;
851 totalreadsamples += readsamples;
852 if (readsamples == samplestoloopend) {
853 pPlaybackState->loop_cycles_left--;
854 SetPos(this->LoopStart);
855 }
856 } while (samplestoread && readsamples);
857 break;
858 }
859 }
860 }
861
862 // read on without looping
863 if (samplestoread) do {
864 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
865 samplestoread -= readsamples;
866 totalreadsamples += readsamples;
867 } while (readsamples && samplestoread);
868
869 // store current position
870 pPlaybackState->position = GetPos();
871
872 return totalreadsamples;
873 }
874
875 /**
876 * Reads \a SampleCount number of sample points from the current
877 * position into the buffer pointed by \a pBuffer and increments the
878 * position within the sample. The sample wave stream will be
879 * decompressed on the fly if using a compressed sample. Use this method
880 * and <i>SetPos()</i> if you don't want to load the sample into RAM,
881 * thus for disk streaming.
882 *
883 * <b>Caution:</b> If you are using more than one streaming thread, you
884 * have to use an external decompression buffer for <b>EACH</b>
885 * streaming thread to avoid race conditions and crashes!
886 *
887 * @param pBuffer destination buffer
888 * @param SampleCount number of sample points to read
889 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
890 * @returns number of successfully read sample points
891 * @see SetPos(), CreateDecompressionBuffer()
892 */
893 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
894 if (SampleCount == 0) return 0;
895 if (!Compressed) {
896 if (BitDepth == 24) {
897 // 24 bit sample. For now just truncate to 16 bit.
898 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
899 int16_t* pDst = static_cast<int16_t*>(pBuffer);
900 if (Channels == 2) { // Stereo
901 unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
902 pSrc++;
903 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
904 *pDst++ = get16(pSrc);
905 pSrc += 3;
906 }
907 return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
908 }
909 else { // Mono
910 unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
911 pSrc++;
912 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
913 *pDst++ = get16(pSrc);
914 pSrc += 3;
915 }
916 return pDst - static_cast<int16_t*>(pBuffer);
917 }
918 }
919 else { // 16 bit
920 // (pCkData->Read does endian correction)
921 return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
922 : pCkData->Read(pBuffer, SampleCount, 2);
923 }
924 }
925 else {
926 if (this->SamplePos >= this->SamplesTotal) return 0;
927 //TODO: efficiency: maybe we should test for an average compression rate
928 unsigned long assumedsize = GuessSize(SampleCount),
929 remainingbytes = 0, // remaining bytes in the local buffer
930 remainingsamples = SampleCount,
931 copysamples, skipsamples,
932 currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
933 this->FrameOffset = 0;
934
935 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
936
937 // if decompression buffer too small, then reduce amount of samples to read
938 if (pDecompressionBuffer->Size < assumedsize) {
939 std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
940 SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
941 remainingsamples = SampleCount;
942 assumedsize = GuessSize(SampleCount);
943 }
944
945 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
946 int16_t* pDst = static_cast<int16_t*>(pBuffer);
947 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
948
949 while (remainingsamples && remainingbytes) {
950 unsigned long framesamples = SamplesPerFrame;
951 unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
952
953 int mode_l = *pSrc++, mode_r = 0;
954
955 if (Channels == 2) {
956 mode_r = *pSrc++;
957 framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
958 rightChannelOffset = bytesPerFrameNoHdr[mode_l];
959 nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
960 if (remainingbytes < framebytes) { // last frame in sample
961 framesamples = SamplesInLastFrame;
962 if (mode_l == 4 && (framesamples & 1)) {
963 rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
964 }
965 else {
966 rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
967 }
968 }
969 }
970 else {
971 framebytes = bytesPerFrame[mode_l] + 1;
972 nextFrameOffset = bytesPerFrameNoHdr[mode_l];
973 if (remainingbytes < framebytes) {
974 framesamples = SamplesInLastFrame;
975 }
976 }
977
978 // determine how many samples in this frame to skip and read
979 if (currentframeoffset + remainingsamples >= framesamples) {
980 if (currentframeoffset <= framesamples) {
981 copysamples = framesamples - currentframeoffset;
982 skipsamples = currentframeoffset;
983 }
984 else {
985 copysamples = 0;
986 skipsamples = framesamples;
987 }
988 }
989 else {
990 // This frame has enough data for pBuffer, but not
991 // all of the frame is needed. Set file position
992 // to start of this frame for next call to Read.
993 copysamples = remainingsamples;
994 skipsamples = currentframeoffset;
995 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
996 this->FrameOffset = currentframeoffset + copysamples;
997 }
998 remainingsamples -= copysamples;
999
1000 if (remainingbytes > framebytes) {
1001 remainingbytes -= framebytes;
1002 if (remainingsamples == 0 &&
1003 currentframeoffset + copysamples == framesamples) {
1004 // This frame has enough data for pBuffer, and
1005 // all of the frame is needed. Set file
1006 // position to start of next frame for next
1007 // call to Read. FrameOffset is 0.
1008 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1009 }
1010 }
1011 else remainingbytes = 0;
1012
1013 currentframeoffset -= skipsamples;
1014
1015 if (copysamples == 0) {
1016 // skip this frame
1017 pSrc += framebytes - Channels;
1018 }
1019 else {
1020 const unsigned char* const param_l = pSrc;
1021 if (BitDepth == 24) {
1022 if (mode_l != 2) pSrc += 12;
1023
1024 if (Channels == 2) { // Stereo
1025 const unsigned char* const param_r = pSrc;
1026 if (mode_r != 2) pSrc += 12;
1027
1028 Decompress24(mode_l, param_l, 2, pSrc, pDst,
1029 skipsamples, copysamples, TruncatedBits);
1030 Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
1031 skipsamples, copysamples, TruncatedBits);
1032 pDst += copysamples << 1;
1033 }
1034 else { // Mono
1035 Decompress24(mode_l, param_l, 1, pSrc, pDst,
1036 skipsamples, copysamples, TruncatedBits);
1037 pDst += copysamples;
1038 }
1039 }
1040 else { // 16 bit
1041 if (mode_l) pSrc += 4;
1042
1043 int step;
1044 if (Channels == 2) { // Stereo
1045 const unsigned char* const param_r = pSrc;
1046 if (mode_r) pSrc += 4;
1047
1048 step = (2 - mode_l) + (2 - mode_r);
1049 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1050 Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1051 skipsamples, copysamples);
1052 pDst += copysamples << 1;
1053 }
1054 else { // Mono
1055 step = 2 - mode_l;
1056 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1057 pDst += copysamples;
1058 }
1059 }
1060 pSrc += nextFrameOffset;
1061 }
1062
1063 // reload from disk to local buffer if needed
1064 if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1065 assumedsize = GuessSize(remainingsamples);
1066 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1067 if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1068 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1069 pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1070 }
1071 } // while
1072
1073 this->SamplePos += (SampleCount - remainingsamples);
1074 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1075 return (SampleCount - remainingsamples);
1076 }
1077 }
1078
1079 /** @brief Write sample wave data.
1080 *
1081 * Writes \a SampleCount number of sample points from the buffer pointed
1082 * by \a pBuffer and increments the position within the sample. Use this
1083 * method to directly write the sample data to disk, i.e. if you don't
1084 * want or cannot load the whole sample data into RAM.
1085 *
1086 * You have to Resize() the sample to the desired size and call
1087 * File::Save() <b>before</b> using Write().
1088 *
1089 * Note: there is currently no support for writing compressed samples.
1090 *
1091 * @param pBuffer - source buffer
1092 * @param SampleCount - number of sample points to write
1093 * @throws DLS::Exception if current sample size is too small
1094 * @throws gig::Exception if sample is compressed
1095 * @see DLS::LoadSampleData()
1096 */
1097 unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1098 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1099 return DLS::Sample::Write(pBuffer, SampleCount);
1100 }
1101
1102 /**
1103 * Allocates a decompression buffer for streaming (compressed) samples
1104 * with Sample::Read(). If you are using more than one streaming thread
1105 * in your application you <b>HAVE</b> to create a decompression buffer
1106 * for <b>EACH</b> of your streaming threads and provide it with the
1107 * Sample::Read() call in order to avoid race conditions and crashes.
1108 *
1109 * You should free the memory occupied by the allocated buffer(s) once
1110 * you don't need one of your streaming threads anymore by calling
1111 * DestroyDecompressionBuffer().
1112 *
1113 * @param MaxReadSize - the maximum size (in sample points) you ever
1114 * expect to read with one Read() call
1115 * @returns allocated decompression buffer
1116 * @see DestroyDecompressionBuffer()
1117 */
1118 buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1119 buffer_t result;
1120 const double worstCaseHeaderOverhead =
1121 (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1122 result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1123 result.pStart = new int8_t[result.Size];
1124 result.NullExtensionSize = 0;
1125 return result;
1126 }
1127
1128 /**
1129 * Free decompression buffer, previously created with
1130 * CreateDecompressionBuffer().
1131 *
1132 * @param DecompressionBuffer - previously allocated decompression
1133 * buffer to free
1134 */
1135 void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1136 if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1137 delete[] (int8_t*) DecompressionBuffer.pStart;
1138 DecompressionBuffer.pStart = NULL;
1139 DecompressionBuffer.Size = 0;
1140 DecompressionBuffer.NullExtensionSize = 0;
1141 }
1142 }
1143
1144 Sample::~Sample() {
1145 Instances--;
1146 if (!Instances && InternalDecompressionBuffer.Size) {
1147 delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1148 InternalDecompressionBuffer.pStart = NULL;
1149 InternalDecompressionBuffer.Size = 0;
1150 }
1151 if (FrameTable) delete[] FrameTable;
1152 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1153 }
1154
1155
1156
1157 // *************** DimensionRegion ***************
1158 // *
1159
1160 uint DimensionRegion::Instances = 0;
1161 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1162
1163 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1164 Instances++;
1165
1166 pSample = NULL;
1167
1168 memcpy(&Crossfade, &SamplerOptions, 4);
1169 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1170
1171 RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1172 if (_3ewa) { // if '3ewa' chunk exists
1173 _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1174 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1175 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1176 _3ewa->ReadInt16(); // unknown
1177 LFO1InternalDepth = _3ewa->ReadUint16();
1178 _3ewa->ReadInt16(); // unknown
1179 LFO3InternalDepth = _3ewa->ReadInt16();
1180 _3ewa->ReadInt16(); // unknown
1181 LFO1ControlDepth = _3ewa->ReadUint16();
1182 _3ewa->ReadInt16(); // unknown
1183 LFO3ControlDepth = _3ewa->ReadInt16();
1184 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1185 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1186 _3ewa->ReadInt16(); // unknown
1187 EG1Sustain = _3ewa->ReadUint16();
1188 EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1189 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1190 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1191 EG1ControllerInvert = eg1ctrloptions & 0x01;
1192 EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1193 EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1194 EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1195 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1196 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1197 EG2ControllerInvert = eg2ctrloptions & 0x01;
1198 EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1199 EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1200 EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1201 LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1202 EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1203 EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1204 _3ewa->ReadInt16(); // unknown
1205 EG2Sustain = _3ewa->ReadUint16();
1206 EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1207 _3ewa->ReadInt16(); // unknown
1208 LFO2ControlDepth = _3ewa->ReadUint16();
1209 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1210 _3ewa->ReadInt16(); // unknown
1211 LFO2InternalDepth = _3ewa->ReadUint16();
1212 int32_t eg1decay2 = _3ewa->ReadInt32();
1213 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1214 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1215 _3ewa->ReadInt16(); // unknown
1216 EG1PreAttack = _3ewa->ReadUint16();
1217 int32_t eg2decay2 = _3ewa->ReadInt32();
1218 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1219 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1220 _3ewa->ReadInt16(); // unknown
1221 EG2PreAttack = _3ewa->ReadUint16();
1222 uint8_t velocityresponse = _3ewa->ReadUint8();
1223 if (velocityresponse < 5) {
1224 VelocityResponseCurve = curve_type_nonlinear;
1225 VelocityResponseDepth = velocityresponse;
1226 } else if (velocityresponse < 10) {
1227 VelocityResponseCurve = curve_type_linear;
1228 VelocityResponseDepth = velocityresponse - 5;
1229 } else if (velocityresponse < 15) {
1230 VelocityResponseCurve = curve_type_special;
1231 VelocityResponseDepth = velocityresponse - 10;
1232 } else {
1233 VelocityResponseCurve = curve_type_unknown;
1234 VelocityResponseDepth = 0;
1235 }
1236 uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1237 if (releasevelocityresponse < 5) {
1238 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1239 ReleaseVelocityResponseDepth = releasevelocityresponse;
1240 } else if (releasevelocityresponse < 10) {
1241 ReleaseVelocityResponseCurve = curve_type_linear;
1242 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1243 } else if (releasevelocityresponse < 15) {
1244 ReleaseVelocityResponseCurve = curve_type_special;
1245 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1246 } else {
1247 ReleaseVelocityResponseCurve = curve_type_unknown;
1248 ReleaseVelocityResponseDepth = 0;
1249 }
1250 VelocityResponseCurveScaling = _3ewa->ReadUint8();
1251 AttenuationControllerThreshold = _3ewa->ReadInt8();
1252 _3ewa->ReadInt32(); // unknown
1253 SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1254 _3ewa->ReadInt16(); // unknown
1255 uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1256 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1257 if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1258 else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1259 else DimensionBypass = dim_bypass_ctrl_none;
1260 uint8_t pan = _3ewa->ReadUint8();
1261 Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1262 SelfMask = _3ewa->ReadInt8() & 0x01;
1263 _3ewa->ReadInt8(); // unknown
1264 uint8_t lfo3ctrl = _3ewa->ReadUint8();
1265 LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1266 LFO3Sync = lfo3ctrl & 0x20; // bit 5
1267 InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1268 AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1269 uint8_t lfo2ctrl = _3ewa->ReadUint8();
1270 LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1271 LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1272 LFO2Sync = lfo2ctrl & 0x20; // bit 5
1273 bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1274 uint8_t lfo1ctrl = _3ewa->ReadUint8();
1275 LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1276 LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1277 LFO1Sync = lfo1ctrl & 0x40; // bit 6
1278 VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1279 : vcf_res_ctrl_none;
1280 uint16_t eg3depth = _3ewa->ReadUint16();
1281 EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1282 : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1283 _3ewa->ReadInt16(); // unknown
1284 ChannelOffset = _3ewa->ReadUint8() / 4;
1285 uint8_t regoptions = _3ewa->ReadUint8();
1286 MSDecode = regoptions & 0x01; // bit 0
1287 SustainDefeat = regoptions & 0x02; // bit 1
1288 _3ewa->ReadInt16(); // unknown
1289 VelocityUpperLimit = _3ewa->ReadInt8();
1290 _3ewa->ReadInt8(); // unknown
1291 _3ewa->ReadInt16(); // unknown
1292 ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1293 _3ewa->ReadInt8(); // unknown
1294 _3ewa->ReadInt8(); // unknown
1295 EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1296 uint8_t vcfcutoff = _3ewa->ReadUint8();
1297 VCFEnabled = vcfcutoff & 0x80; // bit 7
1298 VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1299 VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1300 uint8_t vcfvelscale = _3ewa->ReadUint8();
1301 VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1302 VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1303 _3ewa->ReadInt8(); // unknown
1304 uint8_t vcfresonance = _3ewa->ReadUint8();
1305 VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1306 VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1307 uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1308 VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1309 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1310 uint8_t vcfvelocity = _3ewa->ReadUint8();
1311 VCFVelocityDynamicRange = vcfvelocity % 5;
1312 VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1313 VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1314 if (VCFType == vcf_type_lowpass) {
1315 if (lfo3ctrl & 0x40) // bit 6
1316 VCFType = vcf_type_lowpassturbo;
1317 }
1318 } else { // '3ewa' chunk does not exist yet
1319 // use default values
1320 LFO3Frequency = 1.0;
1321 EG3Attack = 0.0;
1322 LFO1InternalDepth = 0;
1323 LFO3InternalDepth = 0;
1324 LFO1ControlDepth = 0;
1325 LFO3ControlDepth = 0;
1326 EG1Attack = 0.0;
1327 EG1Decay1 = 0.0;
1328 EG1Sustain = 0;
1329 EG1Release = 0.0;
1330 EG1Controller.type = eg1_ctrl_t::type_none;
1331 EG1Controller.controller_number = 0;
1332 EG1ControllerInvert = false;
1333 EG1ControllerAttackInfluence = 0;
1334 EG1ControllerDecayInfluence = 0;
1335 EG1ControllerReleaseInfluence = 0;
1336 EG2Controller.type = eg2_ctrl_t::type_none;
1337 EG2Controller.controller_number = 0;
1338 EG2ControllerInvert = false;
1339 EG2ControllerAttackInfluence = 0;
1340 EG2ControllerDecayInfluence = 0;
1341 EG2ControllerReleaseInfluence = 0;
1342 LFO1Frequency = 1.0;
1343 EG2Attack = 0.0;
1344 EG2Decay1 = 0.0;
1345 EG2Sustain = 0;
1346 EG2Release = 0.0;
1347 LFO2ControlDepth = 0;
1348 LFO2Frequency = 1.0;
1349 LFO2InternalDepth = 0;
1350 EG1Decay2 = 0.0;
1351 EG1InfiniteSustain = false;
1352 EG1PreAttack = 1000;
1353 EG2Decay2 = 0.0;
1354 EG2InfiniteSustain = false;
1355 EG2PreAttack = 1000;
1356 VelocityResponseCurve = curve_type_nonlinear;
1357 VelocityResponseDepth = 3;
1358 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1359 ReleaseVelocityResponseDepth = 3;
1360 VelocityResponseCurveScaling = 32;
1361 AttenuationControllerThreshold = 0;
1362 SampleStartOffset = 0;
1363 PitchTrack = true;
1364 DimensionBypass = dim_bypass_ctrl_none;
1365 Pan = 0;
1366 SelfMask = true;
1367 LFO3Controller = lfo3_ctrl_modwheel;
1368 LFO3Sync = false;
1369 InvertAttenuationController = false;
1370 AttenuationController.type = attenuation_ctrl_t::type_none;
1371 AttenuationController.controller_number = 0;
1372 LFO2Controller = lfo2_ctrl_internal;
1373 LFO2FlipPhase = false;
1374 LFO2Sync = false;
1375 LFO1Controller = lfo1_ctrl_internal;
1376 LFO1FlipPhase = false;
1377 LFO1Sync = false;
1378 VCFResonanceController = vcf_res_ctrl_none;
1379 EG3Depth = 0;
1380 ChannelOffset = 0;
1381 MSDecode = false;
1382 SustainDefeat = false;
1383 VelocityUpperLimit = 0;
1384 ReleaseTriggerDecay = 0;
1385 EG1Hold = false;
1386 VCFEnabled = false;
1387 VCFCutoff = 0;
1388 VCFCutoffController = vcf_cutoff_ctrl_none;
1389 VCFCutoffControllerInvert = false;
1390 VCFVelocityScale = 0;
1391 VCFResonance = 0;
1392 VCFResonanceDynamic = false;
1393 VCFKeyboardTracking = false;
1394 VCFKeyboardTrackingBreakpoint = 0;
1395 VCFVelocityDynamicRange = 0x04;
1396 VCFVelocityCurve = curve_type_linear;
1397 VCFType = vcf_type_lowpass;
1398 }
1399
1400 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1401 VelocityResponseDepth,
1402 VelocityResponseCurveScaling);
1403
1404 curve_type_t curveType = ReleaseVelocityResponseCurve;
1405 uint8_t depth = ReleaseVelocityResponseDepth;
1406
1407 // this models a strange behaviour or bug in GSt: two of the
1408 // velocity response curves for release time are not used even
1409 // if specified, instead another curve is chosen.
1410 if ((curveType == curve_type_nonlinear && depth == 0) ||
1411 (curveType == curve_type_special && depth == 4)) {
1412 curveType = curve_type_nonlinear;
1413 depth = 3;
1414 }
1415 pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1416
1417 curveType = VCFVelocityCurve;
1418 depth = VCFVelocityDynamicRange;
1419
1420 // even stranger GSt: two of the velocity response curves for
1421 // filter cutoff are not used, instead another special curve
1422 // is chosen. This curve is not used anywhere else.
1423 if ((curveType == curve_type_nonlinear && depth == 0) ||
1424 (curveType == curve_type_special && depth == 4)) {
1425 curveType = curve_type_special;
1426 depth = 5;
1427 }
1428 pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1429 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1430
1431 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1432 VelocityTable = 0;
1433 }
1434
1435 /**
1436 * Apply dimension region settings to the respective RIFF chunks. You
1437 * have to call File::Save() to make changes persistent.
1438 *
1439 * Usually there is absolutely no need to call this method explicitly.
1440 * It will be called automatically when File::Save() was called.
1441 */
1442 void DimensionRegion::UpdateChunks() {
1443 // first update base class's chunk
1444 DLS::Sampler::UpdateChunks();
1445
1446 // make sure '3ewa' chunk exists
1447 RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1448 if (!_3ewa) _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1449 uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1450
1451 // update '3ewa' chunk with DimensionRegion's current settings
1452
1453 const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1454 memcpy(&pData[0], &unknown, 4);
1455
1456 const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1457 memcpy(&pData[4], &lfo3freq, 4);
1458
1459 const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1460 memcpy(&pData[4], &eg3attack, 4);
1461
1462 // next 2 bytes unknown
1463
1464 memcpy(&pData[10], &LFO1InternalDepth, 2);
1465
1466 // next 2 bytes unknown
1467
1468 memcpy(&pData[14], &LFO3InternalDepth, 2);
1469
1470 // next 2 bytes unknown
1471
1472 memcpy(&pData[18], &LFO1ControlDepth, 2);
1473
1474 // next 2 bytes unknown
1475
1476 memcpy(&pData[22], &LFO3ControlDepth, 2);
1477
1478 const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1479 memcpy(&pData[24], &eg1attack, 4);
1480
1481 const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1482 memcpy(&pData[28], &eg1decay1, 4);
1483
1484 // next 2 bytes unknown
1485
1486 memcpy(&pData[34], &EG1Sustain, 2);
1487
1488 const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1489 memcpy(&pData[36], &eg1release, 4);
1490
1491 const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1492 memcpy(&pData[40], &eg1ctl, 1);
1493
1494 const uint8_t eg1ctrloptions =
1495 (EG1ControllerInvert) ? 0x01 : 0x00 |
1496 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1497 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1498 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1499 memcpy(&pData[41], &eg1ctrloptions, 1);
1500
1501 const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1502 memcpy(&pData[42], &eg2ctl, 1);
1503
1504 const uint8_t eg2ctrloptions =
1505 (EG2ControllerInvert) ? 0x01 : 0x00 |
1506 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1507 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1508 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1509 memcpy(&pData[43], &eg2ctrloptions, 1);
1510
1511 const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1512 memcpy(&pData[44], &lfo1freq, 4);
1513
1514 const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1515 memcpy(&pData[48], &eg2attack, 4);
1516
1517 const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1518 memcpy(&pData[52], &eg2decay1, 4);
1519
1520 // next 2 bytes unknown
1521
1522 memcpy(&pData[58], &EG2Sustain, 2);
1523
1524 const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1525 memcpy(&pData[60], &eg2release, 4);
1526
1527 // next 2 bytes unknown
1528
1529 memcpy(&pData[66], &LFO2ControlDepth, 2);
1530
1531 const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1532 memcpy(&pData[68], &lfo2freq, 4);
1533
1534 // next 2 bytes unknown
1535
1536 memcpy(&pData[72], &LFO2InternalDepth, 2);
1537
1538 const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1539 memcpy(&pData[74], &eg1decay2, 4);
1540
1541 // next 2 bytes unknown
1542
1543 memcpy(&pData[80], &EG1PreAttack, 2);
1544
1545 const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1546 memcpy(&pData[82], &eg2decay2, 4);
1547
1548 // next 2 bytes unknown
1549
1550 memcpy(&pData[88], &EG2PreAttack, 2);
1551
1552 {
1553 if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1554 uint8_t velocityresponse = VelocityResponseDepth;
1555 switch (VelocityResponseCurve) {
1556 case curve_type_nonlinear:
1557 break;
1558 case curve_type_linear:
1559 velocityresponse += 5;
1560 break;
1561 case curve_type_special:
1562 velocityresponse += 10;
1563 break;
1564 case curve_type_unknown:
1565 default:
1566 throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1567 }
1568 memcpy(&pData[90], &velocityresponse, 1);
1569 }
1570
1571 {
1572 if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1573 uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1574 switch (ReleaseVelocityResponseCurve) {
1575 case curve_type_nonlinear:
1576 break;
1577 case curve_type_linear:
1578 releasevelocityresponse += 5;
1579 break;
1580 case curve_type_special:
1581 releasevelocityresponse += 10;
1582 break;
1583 case curve_type_unknown:
1584 default:
1585 throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1586 }
1587 memcpy(&pData[91], &releasevelocityresponse, 1);
1588 }
1589
1590 memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1591
1592 memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1593
1594 // next 4 bytes unknown
1595
1596 memcpy(&pData[98], &SampleStartOffset, 2);
1597
1598 // next 2 bytes unknown
1599
1600 {
1601 uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1602 switch (DimensionBypass) {
1603 case dim_bypass_ctrl_94:
1604 pitchTrackDimensionBypass |= 0x10;
1605 break;
1606 case dim_bypass_ctrl_95:
1607 pitchTrackDimensionBypass |= 0x20;
1608 break;
1609 case dim_bypass_ctrl_none:
1610 //FIXME: should we set anything here?
1611 break;
1612 default:
1613 throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1614 }
1615 memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1616 }
1617
1618 const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1619 memcpy(&pData[103], &pan, 1);
1620
1621 const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1622 memcpy(&pData[104], &selfmask, 1);
1623
1624 // next byte unknown
1625
1626 {
1627 uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1628 if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1629 if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1630 if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1631 memcpy(&pData[106], &lfo3ctrl, 1);
1632 }
1633
1634 const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1635 memcpy(&pData[107], &attenctl, 1);
1636
1637 {
1638 uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1639 if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1640 if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1641 if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1642 memcpy(&pData[108], &lfo2ctrl, 1);
1643 }
1644
1645 {
1646 uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1647 if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1648 if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1649 if (VCFResonanceController != vcf_res_ctrl_none)
1650 lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1651 memcpy(&pData[109], &lfo1ctrl, 1);
1652 }
1653
1654 const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1655 : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1656 memcpy(&pData[110], &eg3depth, 1);
1657
1658 // next 2 bytes unknown
1659
1660 const uint8_t channeloffset = ChannelOffset * 4;
1661 memcpy(&pData[113], &channeloffset, 1);
1662
1663 {
1664 uint8_t regoptions = 0;
1665 if (MSDecode) regoptions |= 0x01; // bit 0
1666 if (SustainDefeat) regoptions |= 0x02; // bit 1
1667 memcpy(&pData[114], &regoptions, 1);
1668 }
1669
1670 // next 2 bytes unknown
1671
1672 memcpy(&pData[117], &VelocityUpperLimit, 1);
1673
1674 // next 3 bytes unknown
1675
1676 memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1677
1678 // next 2 bytes unknown
1679
1680 const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1681 memcpy(&pData[124], &eg1hold, 1);
1682
1683 const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 | /* bit 7 */
1684 (VCFCutoff) ? 0x7f : 0x00; /* lower 7 bits */
1685 memcpy(&pData[125], &vcfcutoff, 1);
1686
1687 memcpy(&pData[126], &VCFCutoffController, 1);
1688
1689 const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1690 (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1691 memcpy(&pData[127], &vcfvelscale, 1);
1692
1693 // next byte unknown
1694
1695 const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1696 (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1697 memcpy(&pData[129], &vcfresonance, 1);
1698
1699 const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1700 (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1701 memcpy(&pData[130], &vcfbreakpoint, 1);
1702
1703 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1704 VCFVelocityCurve * 5;
1705 memcpy(&pData[131], &vcfvelocity, 1);
1706
1707 const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1708 memcpy(&pData[132], &vcftype, 1);
1709 }
1710
1711 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1712 double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1713 {
1714 double* table;
1715 uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1716 if (pVelocityTables->count(tableKey)) { // if key exists
1717 table = (*pVelocityTables)[tableKey];
1718 }
1719 else {
1720 table = CreateVelocityTable(curveType, depth, scaling);
1721 (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
1722 }
1723 return table;
1724 }
1725
1726 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1727 leverage_ctrl_t decodedcontroller;
1728 switch (EncodedController) {
1729 // special controller
1730 case _lev_ctrl_none:
1731 decodedcontroller.type = leverage_ctrl_t::type_none;
1732 decodedcontroller.controller_number = 0;
1733 break;
1734 case _lev_ctrl_velocity:
1735 decodedcontroller.type = leverage_ctrl_t::type_velocity;
1736 decodedcontroller.controller_number = 0;
1737 break;
1738 case _lev_ctrl_channelaftertouch:
1739 decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1740 decodedcontroller.controller_number = 0;
1741 break;
1742
1743 // ordinary MIDI control change controller
1744 case _lev_ctrl_modwheel:
1745 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1746 decodedcontroller.controller_number = 1;
1747 break;
1748 case _lev_ctrl_breath:
1749 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1750 decodedcontroller.controller_number = 2;
1751 break;
1752 case _lev_ctrl_foot:
1753 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1754 decodedcontroller.controller_number = 4;
1755 break;
1756 case _lev_ctrl_effect1:
1757 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1758 decodedcontroller.controller_number = 12;
1759 break;
1760 case _lev_ctrl_effect2:
1761 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1762 decodedcontroller.controller_number = 13;
1763 break;
1764 case _lev_ctrl_genpurpose1:
1765 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1766 decodedcontroller.controller_number = 16;
1767 break;
1768 case _lev_ctrl_genpurpose2:
1769 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1770 decodedcontroller.controller_number = 17;
1771 break;
1772 case _lev_ctrl_genpurpose3:
1773 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1774 decodedcontroller.controller_number = 18;
1775 break;
1776 case _lev_ctrl_genpurpose4:
1777 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1778 decodedcontroller.controller_number = 19;
1779 break;
1780 case _lev_ctrl_portamentotime:
1781 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1782 decodedcontroller.controller_number = 5;
1783 break;
1784 case _lev_ctrl_sustainpedal:
1785 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1786 decodedcontroller.controller_number = 64;
1787 break;
1788 case _lev_ctrl_portamento:
1789 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1790 decodedcontroller.controller_number = 65;
1791 break;
1792 case _lev_ctrl_sostenutopedal:
1793 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1794 decodedcontroller.controller_number = 66;
1795 break;
1796 case _lev_ctrl_softpedal:
1797 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1798 decodedcontroller.controller_number = 67;
1799 break;
1800 case _lev_ctrl_genpurpose5:
1801 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1802 decodedcontroller.controller_number = 80;
1803 break;
1804 case _lev_ctrl_genpurpose6:
1805 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1806 decodedcontroller.controller_number = 81;
1807 break;
1808 case _lev_ctrl_genpurpose7:
1809 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1810 decodedcontroller.controller_number = 82;
1811 break;
1812 case _lev_ctrl_genpurpose8:
1813 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1814 decodedcontroller.controller_number = 83;
1815 break;
1816 case _lev_ctrl_effect1depth:
1817 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1818 decodedcontroller.controller_number = 91;
1819 break;
1820 case _lev_ctrl_effect2depth:
1821 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1822 decodedcontroller.controller_number = 92;
1823 break;
1824 case _lev_ctrl_effect3depth:
1825 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1826 decodedcontroller.controller_number = 93;
1827 break;
1828 case _lev_ctrl_effect4depth:
1829 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1830 decodedcontroller.controller_number = 94;
1831 break;
1832 case _lev_ctrl_effect5depth:
1833 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1834 decodedcontroller.controller_number = 95;
1835 break;
1836
1837 // unknown controller type
1838 default:
1839 throw gig::Exception("Unknown leverage controller type.");
1840 }
1841 return decodedcontroller;
1842 }
1843
1844 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1845 _lev_ctrl_t encodedcontroller;
1846 switch (DecodedController.type) {
1847 // special controller
1848 case leverage_ctrl_t::type_none:
1849 encodedcontroller = _lev_ctrl_none;
1850 break;
1851 case leverage_ctrl_t::type_velocity:
1852 encodedcontroller = _lev_ctrl_velocity;
1853 break;
1854 case leverage_ctrl_t::type_channelaftertouch:
1855 encodedcontroller = _lev_ctrl_channelaftertouch;
1856 break;
1857
1858 // ordinary MIDI control change controller
1859 case leverage_ctrl_t::type_controlchange:
1860 switch (DecodedController.controller_number) {
1861 case 1:
1862 encodedcontroller = _lev_ctrl_modwheel;
1863 break;
1864 case 2:
1865 encodedcontroller = _lev_ctrl_breath;
1866 break;
1867 case 4:
1868 encodedcontroller = _lev_ctrl_foot;
1869 break;
1870 case 12:
1871 encodedcontroller = _lev_ctrl_effect1;
1872 break;
1873 case 13:
1874 encodedcontroller = _lev_ctrl_effect2;
1875 break;
1876 case 16:
1877 encodedcontroller = _lev_ctrl_genpurpose1;
1878 break;
1879 case 17:
1880 encodedcontroller = _lev_ctrl_genpurpose2;
1881 break;
1882 case 18:
1883 encodedcontroller = _lev_ctrl_genpurpose3;
1884 break;
1885 case 19:
1886 encodedcontroller = _lev_ctrl_genpurpose4;
1887 break;
1888 case 5:
1889 encodedcontroller = _lev_ctrl_portamentotime;
1890 break;
1891 case 64:
1892 encodedcontroller = _lev_ctrl_sustainpedal;
1893 break;
1894 case 65:
1895 encodedcontroller = _lev_ctrl_portamento;
1896 break;
1897 case 66:
1898 encodedcontroller = _lev_ctrl_sostenutopedal;
1899 break;
1900 case 67:
1901 encodedcontroller = _lev_ctrl_softpedal;
1902 break;
1903 case 80:
1904 encodedcontroller = _lev_ctrl_genpurpose5;
1905 break;
1906 case 81:
1907 encodedcontroller = _lev_ctrl_genpurpose6;
1908 break;
1909 case 82:
1910 encodedcontroller = _lev_ctrl_genpurpose7;
1911 break;
1912 case 83:
1913 encodedcontroller = _lev_ctrl_genpurpose8;
1914 break;
1915 case 91:
1916 encodedcontroller = _lev_ctrl_effect1depth;
1917 break;
1918 case 92:
1919 encodedcontroller = _lev_ctrl_effect2depth;
1920 break;
1921 case 93:
1922 encodedcontroller = _lev_ctrl_effect3depth;
1923 break;
1924 case 94:
1925 encodedcontroller = _lev_ctrl_effect4depth;
1926 break;
1927 case 95:
1928 encodedcontroller = _lev_ctrl_effect5depth;
1929 break;
1930 default:
1931 throw gig::Exception("leverage controller number is not supported by the gig format");
1932 }
1933 default:
1934 throw gig::Exception("Unknown leverage controller type.");
1935 }
1936 return encodedcontroller;
1937 }
1938
1939 DimensionRegion::~DimensionRegion() {
1940 Instances--;
1941 if (!Instances) {
1942 // delete the velocity->volume tables
1943 VelocityTableMap::iterator iter;
1944 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
1945 double* pTable = iter->second;
1946 if (pTable) delete[] pTable;
1947 }
1948 pVelocityTables->clear();
1949 delete pVelocityTables;
1950 pVelocityTables = NULL;
1951 }
1952 if (VelocityTable) delete[] VelocityTable;
1953 }
1954
1955 /**
1956 * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1957 * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1958 * and VelocityResponseCurveScaling) involved are taken into account to
1959 * calculate the amplitude factor. Use this method when a key was
1960 * triggered to get the volume with which the sample should be played
1961 * back.
1962 *
1963 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
1964 * @returns amplitude factor (between 0.0 and 1.0)
1965 */
1966 double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1967 return pVelocityAttenuationTable[MIDIKeyVelocity];
1968 }
1969
1970 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1971 return pVelocityReleaseTable[MIDIKeyVelocity];
1972 }
1973
1974 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1975 return pVelocityCutoffTable[MIDIKeyVelocity];
1976 }
1977
1978 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1979
1980 // line-segment approximations of the 15 velocity curves
1981
1982 // linear
1983 const int lin0[] = { 1, 1, 127, 127 };
1984 const int lin1[] = { 1, 21, 127, 127 };
1985 const int lin2[] = { 1, 45, 127, 127 };
1986 const int lin3[] = { 1, 74, 127, 127 };
1987 const int lin4[] = { 1, 127, 127, 127 };
1988
1989 // non-linear
1990 const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
1991 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
1992 127, 127 };
1993 const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
1994 127, 127 };
1995 const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
1996 127, 127 };
1997 const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
1998
1999 // special
2000 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2001 113, 127, 127, 127 };
2002 const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2003 118, 127, 127, 127 };
2004 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2005 85, 90, 91, 127, 127, 127 };
2006 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2007 117, 127, 127, 127 };
2008 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2009 127, 127 };
2010
2011 // this is only used by the VCF velocity curve
2012 const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2013 91, 127, 127, 127 };
2014
2015 const int* const curves[] = { non0, non1, non2, non3, non4,
2016 lin0, lin1, lin2, lin3, lin4,
2017 spe0, spe1, spe2, spe3, spe4, spe5 };
2018
2019 double* const table = new double[128];
2020
2021 const int* curve = curves[curveType * 5 + depth];
2022 const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2023
2024 table[0] = 0;
2025 for (int x = 1 ; x < 128 ; x++) {
2026
2027 if (x > curve[2]) curve += 2;
2028 double y = curve[1] + (x - curve[0]) *
2029 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2030 y = y / 127;
2031
2032 // Scale up for s > 20, down for s < 20. When
2033 // down-scaling, the curve still ends at 1.0.
2034 if (s < 20 && y >= 0.5)
2035 y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2036 else
2037 y = y * (s / 20.0);
2038 if (y > 1) y = 1;
2039
2040 table[x] = y;
2041 }
2042 return table;
2043 }
2044
2045
2046 // *************** Region ***************
2047 // *
2048
2049 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2050 // Initialization
2051 Dimensions = 0;
2052 for (int i = 0; i < 256; i++) {
2053 pDimensionRegions[i] = NULL;
2054 }
2055 Layers = 1;
2056 File* file = (File*) GetParent()->GetParent();
2057 int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2058
2059 // Actual Loading
2060
2061 LoadDimensionRegions(rgnList);
2062
2063 RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2064 if (_3lnk) {
2065 DimensionRegions = _3lnk->ReadUint32();
2066 for (int i = 0; i < dimensionBits; i++) {
2067 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2068 uint8_t bits = _3lnk->ReadUint8();
2069 _3lnk->ReadUint8(); // probably the position of the dimension
2070 _3lnk->ReadUint8(); // unknown
2071 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2072 if (dimension == dimension_none) { // inactive dimension
2073 pDimensionDefinitions[i].dimension = dimension_none;
2074 pDimensionDefinitions[i].bits = 0;
2075 pDimensionDefinitions[i].zones = 0;
2076 pDimensionDefinitions[i].split_type = split_type_bit;
2077 pDimensionDefinitions[i].zone_size = 0;
2078 }
2079 else { // active dimension
2080 pDimensionDefinitions[i].dimension = dimension;
2081 pDimensionDefinitions[i].bits = bits;
2082 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2083 pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2084 dimension == dimension_samplechannel ||
2085 dimension == dimension_releasetrigger ||
2086 dimension == dimension_roundrobin ||
2087 dimension == dimension_random) ? split_type_bit
2088 : split_type_normal;
2089 pDimensionDefinitions[i].zone_size =
2090 (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2091 : 0;
2092 Dimensions++;
2093
2094 // if this is a layer dimension, remember the amount of layers
2095 if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2096 }
2097 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2098 }
2099 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2100
2101 // if there's a velocity dimension and custom velocity zone splits are used,
2102 // update the VelocityTables in the dimension regions
2103 UpdateVelocityTable();
2104
2105 // jump to start of the wave pool indices (if not already there)
2106 if (file->pVersion && file->pVersion->major == 3)
2107 _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2108 else
2109 _3lnk->SetPos(44);
2110
2111 // load sample references
2112 for (uint i = 0; i < DimensionRegions; i++) {
2113 uint32_t wavepoolindex = _3lnk->ReadUint32();
2114 pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2115 }
2116 }
2117
2118 // make sure there is at least one dimension region
2119 if (!DimensionRegions) {
2120 RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2121 if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2122 RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2123 pDimensionRegions[0] = new DimensionRegion(_3ewl);
2124 DimensionRegions = 1;
2125 }
2126 }
2127
2128 /**
2129 * Apply Region settings and all its DimensionRegions to the respective
2130 * RIFF chunks. You have to call File::Save() to make changes persistent.
2131 *
2132 * Usually there is absolutely no need to call this method explicitly.
2133 * It will be called automatically when File::Save() was called.
2134 *
2135 * @throws gig::Exception if samples cannot be dereferenced
2136 */
2137 void Region::UpdateChunks() {
2138 // first update base class's chunks
2139 DLS::Region::UpdateChunks();
2140
2141 // update dimension region's chunks
2142 for (int i = 0; i < DimensionRegions; i++) {
2143 pDimensionRegions[i]->UpdateChunks();
2144 }
2145
2146 File* pFile = (File*) GetParent()->GetParent();
2147 const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2148 const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2149
2150 // make sure '3lnk' chunk exists
2151 RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2152 if (!_3lnk) {
2153 const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2154 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2155 }
2156
2157 // update dimension definitions in '3lnk' chunk
2158 uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2159 for (int i = 0; i < iMaxDimensions; i++) {
2160 pData[i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2161 pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2162 // next 2 bytes unknown
2163 pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2164 // next 3 bytes unknown
2165 }
2166
2167 // update wave pool table in '3lnk' chunk
2168 const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2169 for (uint i = 0; i < iMaxDimensionRegions; i++) {
2170 int iWaveIndex = -1;
2171 if (i < DimensionRegions) {
2172 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2173 File::SampleList::iterator iter = pFile->pSamples->begin();
2174 File::SampleList::iterator end = pFile->pSamples->end();
2175 for (int index = 0; iter != end; ++iter, ++index) {
2176 if (*iter == pDimensionRegions[i]->pSample) {
2177 iWaveIndex = index;
2178 break;
2179 }
2180 }
2181 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2182 }
2183 memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2184 }
2185 }
2186
2187 void Region::LoadDimensionRegions(RIFF::List* rgn) {
2188 RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
2189 if (_3prg) {
2190 int dimensionRegionNr = 0;
2191 RIFF::List* _3ewl = _3prg->GetFirstSubList();
2192 while (_3ewl) {
2193 if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2194 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
2195 dimensionRegionNr++;
2196 }
2197 _3ewl = _3prg->GetNextSubList();
2198 }
2199 if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
2200 }
2201 }
2202
2203 void Region::UpdateVelocityTable() {
2204 // get velocity dimension's index
2205 int veldim = -1;
2206 for (int i = 0 ; i < Dimensions ; i++) {
2207 if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2208 veldim = i;
2209 break;
2210 }
2211 }
2212 if (veldim == -1) return;
2213
2214 int step = 1;
2215 for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2216 int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2217 int end = step * pDimensionDefinitions[veldim].zones;
2218
2219 // loop through all dimension regions for all dimensions except the velocity dimension
2220 int dim[8] = { 0 };
2221 for (int i = 0 ; i < DimensionRegions ; i++) {
2222
2223 if (pDimensionRegions[i]->VelocityUpperLimit) {
2224 // create the velocity table
2225 uint8_t* table = pDimensionRegions[i]->VelocityTable;
2226 if (!table) {
2227 table = new uint8_t[128];
2228 pDimensionRegions[i]->VelocityTable = table;
2229 }
2230 int tableidx = 0;
2231 int velocityZone = 0;
2232 for (int k = i ; k < end ; k += step) {
2233 DimensionRegion *d = pDimensionRegions[k];
2234 for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2235 velocityZone++;
2236 }
2237 } else {
2238 if (pDimensionRegions[i]->VelocityTable) {
2239 delete[] pDimensionRegions[i]->VelocityTable;
2240 pDimensionRegions[i]->VelocityTable = 0;
2241 }
2242 }
2243
2244 int j;
2245 int shift = 0;
2246 for (j = 0 ; j < Dimensions ; j++) {
2247 if (j == veldim) i += skipveldim; // skip velocity dimension
2248 else {
2249 dim[j]++;
2250 if (dim[j] < pDimensionDefinitions[j].zones) break;
2251 else {
2252 // skip unused dimension regions
2253 dim[j] = 0;
2254 i += ((1 << pDimensionDefinitions[j].bits) -
2255 pDimensionDefinitions[j].zones) << shift;
2256 }
2257 }
2258 shift += pDimensionDefinitions[j].bits;
2259 }
2260 if (j == Dimensions) break;
2261 }
2262 }
2263
2264 /** @brief Einstein would have dreamed of it - create a new dimension.
2265 *
2266 * Creates a new dimension with the dimension definition given by
2267 * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2268 * There is a hard limit of dimensions and total amount of "bits" all
2269 * dimensions can have. This limit is dependant to what gig file format
2270 * version this file refers to. The gig v2 (and lower) format has a
2271 * dimension limit and total amount of bits limit of 5, whereas the gig v3
2272 * format has a limit of 8.
2273 *
2274 * @param pDimDef - defintion of the new dimension
2275 * @throws gig::Exception if dimension of the same type exists already
2276 * @throws gig::Exception if amount of dimensions or total amount of
2277 * dimension bits limit is violated
2278 */
2279 void Region::AddDimension(dimension_def_t* pDimDef) {
2280 // check if max. amount of dimensions reached
2281 File* file = (File*) GetParent()->GetParent();
2282 const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2283 if (Dimensions >= iMaxDimensions)
2284 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2285 // check if max. amount of dimension bits reached
2286 int iCurrentBits = 0;
2287 for (int i = 0; i < Dimensions; i++)
2288 iCurrentBits += pDimensionDefinitions[i].bits;
2289 if (iCurrentBits >= iMaxDimensions)
2290 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2291 const int iNewBits = iCurrentBits + pDimDef->bits;
2292 if (iNewBits > iMaxDimensions)
2293 throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2294 // check if there's already a dimensions of the same type
2295 for (int i = 0; i < Dimensions; i++)
2296 if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2297 throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2298
2299 // assign definition of new dimension
2300 pDimensionDefinitions[Dimensions] = *pDimDef;
2301
2302 // create new dimension region(s) for this new dimension
2303 for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2304 //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2305 RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2306 pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2307 DimensionRegions++;
2308 }
2309
2310 Dimensions++;
2311
2312 // if this is a layer dimension, update 'Layers' attribute
2313 if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2314
2315 UpdateVelocityTable();
2316 }
2317
2318 /** @brief Delete an existing dimension.
2319 *
2320 * Deletes the dimension given by \a pDimDef and deletes all respective
2321 * dimension regions, that is all dimension regions where the dimension's
2322 * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2323 * for example this would delete all dimension regions for the case(s)
2324 * where the sustain pedal is pressed down.
2325 *
2326 * @param pDimDef - dimension to delete
2327 * @throws gig::Exception if given dimension cannot be found
2328 */
2329 void Region::DeleteDimension(dimension_def_t* pDimDef) {
2330 // get dimension's index
2331 int iDimensionNr = -1;
2332 for (int i = 0; i < Dimensions; i++) {
2333 if (&pDimensionDefinitions[i] == pDimDef) {
2334 iDimensionNr = i;
2335 break;
2336 }
2337 }
2338 if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2339
2340 // get amount of bits below the dimension to delete
2341 int iLowerBits = 0;
2342 for (int i = 0; i < iDimensionNr; i++)
2343 iLowerBits += pDimensionDefinitions[i].bits;
2344
2345 // get amount ot bits above the dimension to delete
2346 int iUpperBits = 0;
2347 for (int i = iDimensionNr + 1; i < Dimensions; i++)
2348 iUpperBits += pDimensionDefinitions[i].bits;
2349
2350 // delete dimension regions which belong to the given dimension
2351 // (that is where the dimension's bit > 0)
2352 for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2353 for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2354 for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2355 int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2356 iObsoleteBit << iLowerBits |
2357 iLowerBit;
2358 delete pDimensionRegions[iToDelete];
2359 pDimensionRegions[iToDelete] = NULL;
2360 DimensionRegions--;
2361 }
2362 }
2363 }
2364
2365 // defrag pDimensionRegions array
2366 // (that is remove the NULL spaces within the pDimensionRegions array)
2367 for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2368 if (!pDimensionRegions[iTo]) {
2369 if (iFrom <= iTo) iFrom = iTo + 1;
2370 while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2371 if (iFrom < 256 && pDimensionRegions[iFrom]) {
2372 pDimensionRegions[iTo] = pDimensionRegions[iFrom];
2373 pDimensionRegions[iFrom] = NULL;
2374 }
2375 }
2376 }
2377
2378 // 'remove' dimension definition
2379 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2380 pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2381 }
2382 pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2383 pDimensionDefinitions[Dimensions - 1].bits = 0;
2384 pDimensionDefinitions[Dimensions - 1].zones = 0;
2385
2386 Dimensions--;
2387
2388 // if this was a layer dimension, update 'Layers' attribute
2389 if (pDimDef->dimension == dimension_layer) Layers = 1;
2390 }
2391
2392 Region::~Region() {
2393 for (int i = 0; i < 256; i++) {
2394 if (pDimensionRegions[i]) delete pDimensionRegions[i];
2395 }
2396 }
2397
2398 /**
2399 * Use this method in your audio engine to get the appropriate dimension
2400 * region with it's articulation data for the current situation. Just
2401 * call the method with the current MIDI controller values and you'll get
2402 * the DimensionRegion with the appropriate articulation data for the
2403 * current situation (for this Region of course only). To do that you'll
2404 * first have to look which dimensions with which controllers and in
2405 * which order are defined for this Region when you load the .gig file.
2406 * Special cases are e.g. layer or channel dimensions where you just put
2407 * in the index numbers instead of a MIDI controller value (means 0 for
2408 * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
2409 * etc.).
2410 *
2411 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
2412 * @returns adress to the DimensionRegion for the given situation
2413 * @see pDimensionDefinitions
2414 * @see Dimensions
2415 */
2416 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2417 uint8_t bits;
2418 int veldim = -1;
2419 int velbitpos;
2420 int bitpos = 0;
2421 int dimregidx = 0;
2422 for (uint i = 0; i < Dimensions; i++) {
2423 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2424 // the velocity dimension must be handled after the other dimensions
2425 veldim = i;
2426 velbitpos = bitpos;
2427 } else {
2428 switch (pDimensionDefinitions[i].split_type) {
2429 case split_type_normal:
2430 bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2431 break;
2432 case split_type_bit: // the value is already the sought dimension bit number
2433 const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2434 bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2435 break;
2436 }
2437 dimregidx |= bits << bitpos;
2438 }
2439 bitpos += pDimensionDefinitions[i].bits;
2440 }
2441 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2442 if (veldim != -1) {
2443 // (dimreg is now the dimension region for the lowest velocity)
2444 if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2445 bits = dimreg->VelocityTable[DimValues[veldim]];
2446 else // normal split type
2447 bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2448
2449 dimregidx |= bits << velbitpos;
2450 dimreg = pDimensionRegions[dimregidx];
2451 }
2452 return dimreg;
2453 }
2454
2455 /**
2456 * Returns the appropriate DimensionRegion for the given dimension bit
2457 * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
2458 * instead of calling this method directly!
2459 *
2460 * @param DimBits Bit numbers for dimension 0 to 7
2461 * @returns adress to the DimensionRegion for the given dimension
2462 * bit numbers
2463 * @see GetDimensionRegionByValue()
2464 */
2465 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
2466 return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
2467 << pDimensionDefinitions[5].bits | DimBits[5])
2468 << pDimensionDefinitions[4].bits | DimBits[4])
2469 << pDimensionDefinitions[3].bits | DimBits[3])
2470 << pDimensionDefinitions[2].bits | DimBits[2])
2471 << pDimensionDefinitions[1].bits | DimBits[1])
2472 << pDimensionDefinitions[0].bits | DimBits[0]];
2473 }
2474
2475 /**
2476 * Returns pointer address to the Sample referenced with this region.
2477 * This is the global Sample for the entire Region (not sure if this is
2478 * actually used by the Gigasampler engine - I would only use the Sample
2479 * referenced by the appropriate DimensionRegion instead of this sample).
2480 *
2481 * @returns address to Sample or NULL if there is no reference to a
2482 * sample saved in the .gig file
2483 */
2484 Sample* Region::GetSample() {
2485 if (pSample) return static_cast<gig::Sample*>(pSample);
2486 else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2487 }
2488
2489 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2490 if ((int32_t)WavePoolTableIndex == -1) return NULL;
2491 File* file = (File*) GetParent()->GetParent();
2492 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2493 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2494 Sample* sample = file->GetFirstSample(pProgress);
2495 while (sample) {
2496 if (sample->ulWavePoolOffset == soughtoffset &&
2497 sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2498 sample = file->GetNextSample();
2499 }
2500 return NULL;
2501 }
2502
2503
2504
2505 // *************** Instrument ***************
2506 // *
2507
2508 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2509 // Initialization
2510 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2511
2512 // Loading
2513 RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
2514 if (lart) {
2515 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2516 if (_3ewg) {
2517 EffectSend = _3ewg->ReadUint16();
2518 Attenuation = _3ewg->ReadInt32();
2519 FineTune = _3ewg->ReadInt16();
2520 PitchbendRange = _3ewg->ReadInt16();
2521 uint8_t dimkeystart = _3ewg->ReadUint8();
2522 PianoReleaseMode = dimkeystart & 0x01;
2523 DimensionKeyRange.low = dimkeystart >> 1;
2524 DimensionKeyRange.high = _3ewg->ReadUint8();
2525 }
2526 }
2527
2528 if (!pRegions) pRegions = new RegionList;
2529 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2530 if (lrgn) {
2531 RIFF::List* rgn = lrgn->GetFirstSubList();
2532 while (rgn) {
2533 if (rgn->GetListType() == LIST_TYPE_RGN) {
2534 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2535 pRegions->push_back(new Region(this, rgn));
2536 }
2537 rgn = lrgn->GetNextSubList();
2538 }
2539 // Creating Region Key Table for fast lookup
2540 UpdateRegionKeyTable();
2541 }
2542
2543 __notify_progress(pProgress, 1.0f); // notify done
2544 }
2545
2546 void Instrument::UpdateRegionKeyTable() {
2547 RegionList::iterator iter = pRegions->begin();
2548 RegionList::iterator end = pRegions->end();
2549 for (; iter != end; ++iter) {
2550 gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2551 for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2552 RegionKeyTable[iKey] = pRegion;
2553 }
2554 }
2555 }
2556
2557 Instrument::~Instrument() {
2558 }
2559
2560 /**
2561 * Apply Instrument with all its Regions to the respective RIFF chunks.
2562 * You have to call File::Save() to make changes persistent.
2563 *
2564 * Usually there is absolutely no need to call this method explicitly.
2565 * It will be called automatically when File::Save() was called.
2566 *
2567 * @throws gig::Exception if samples cannot be dereferenced
2568 */
2569 void Instrument::UpdateChunks() {
2570 // first update base classes' chunks
2571 DLS::Instrument::UpdateChunks();
2572
2573 // update Regions' chunks
2574 {
2575 RegionList::iterator iter = pRegions->begin();
2576 RegionList::iterator end = pRegions->end();
2577 for (; iter != end; ++iter)
2578 (*iter)->UpdateChunks();
2579 }
2580
2581 // make sure 'lart' RIFF list chunk exists
2582 RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2583 if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2584 // make sure '3ewg' RIFF chunk exists
2585 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2586 if (!_3ewg) _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2587 // update '3ewg' RIFF chunk
2588 uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2589 memcpy(&pData[0], &EffectSend, 2);
2590 memcpy(&pData[2], &Attenuation, 4);
2591 memcpy(&pData[6], &FineTune, 2);
2592 memcpy(&pData[8], &PitchbendRange, 2);
2593 const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2594 DimensionKeyRange.low << 1;
2595 memcpy(&pData[10], &dimkeystart, 1);
2596 memcpy(&pData[11], &DimensionKeyRange.high, 1);
2597 }
2598
2599 /**
2600 * Returns the appropriate Region for a triggered note.
2601 *
2602 * @param Key MIDI Key number of triggered note / key (0 - 127)
2603 * @returns pointer adress to the appropriate Region or NULL if there
2604 * there is no Region defined for the given \a Key
2605 */
2606 Region* Instrument::GetRegion(unsigned int Key) {
2607 if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2608 return RegionKeyTable[Key];
2609
2610 /*for (int i = 0; i < Regions; i++) {
2611 if (Key <= pRegions[i]->KeyRange.high &&
2612 Key >= pRegions[i]->KeyRange.low) return pRegions[i];
2613 }
2614 return NULL;*/
2615 }
2616
2617 /**
2618 * Returns the first Region of the instrument. You have to call this
2619 * method once before you use GetNextRegion().
2620 *
2621 * @returns pointer address to first region or NULL if there is none
2622 * @see GetNextRegion()
2623 */
2624 Region* Instrument::GetFirstRegion() {
2625 if (!pRegions) return NULL;
2626 RegionsIterator = pRegions->begin();
2627 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2628 }
2629
2630 /**
2631 * Returns the next Region of the instrument. You have to call
2632 * GetFirstRegion() once before you can use this method. By calling this
2633 * method multiple times it iterates through the available Regions.
2634 *
2635 * @returns pointer address to the next region or NULL if end reached
2636 * @see GetFirstRegion()
2637 */
2638 Region* Instrument::GetNextRegion() {
2639 if (!pRegions) return NULL;
2640 RegionsIterator++;
2641 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2642 }
2643
2644 Region* Instrument::AddRegion() {
2645 // create new Region object (and its RIFF chunks)
2646 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2647 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2648 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2649 Region* pNewRegion = new Region(this, rgn);
2650 pRegions->push_back(pNewRegion);
2651 Regions = pRegions->size();
2652 // update Region key table for fast lookup
2653 UpdateRegionKeyTable();
2654 // done
2655 return pNewRegion;
2656 }
2657
2658 void Instrument::DeleteRegion(Region* pRegion) {
2659 if (!pRegions) return;
2660 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2661 // update Region key table for fast lookup
2662 UpdateRegionKeyTable();
2663 }
2664
2665
2666
2667 // *************** File ***************
2668 // *
2669
2670 File::File() : DLS::File() {
2671 }
2672
2673 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2674 }
2675
2676 Sample* File::GetFirstSample(progress_t* pProgress) {
2677 if (!pSamples) LoadSamples(pProgress);
2678 if (!pSamples) return NULL;
2679 SamplesIterator = pSamples->begin();
2680 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2681 }
2682
2683 Sample* File::GetNextSample() {
2684 if (!pSamples) return NULL;
2685 SamplesIterator++;
2686 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2687 }
2688
2689 /** @brief Add a new sample.
2690 *
2691 * This will create a new Sample object for the gig file. You have to
2692 * call Save() to make this persistent to the file.
2693 *
2694 * @returns pointer to new Sample object
2695 */
2696 Sample* File::AddSample() {
2697 if (!pSamples) LoadSamples();
2698 __ensureMandatoryChunksExist();
2699 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2700 // create new Sample object and its respective 'wave' list chunk
2701 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2702 Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2703 pSamples->push_back(pSample);
2704 return pSample;
2705 }
2706
2707 /** @brief Delete a sample.
2708 *
2709 * This will delete the given Sample object from the gig file. You have
2710 * to call Save() to make this persistent to the file.
2711 *
2712 * @param pSample - sample to delete
2713 * @throws gig::Exception if given sample could not be found
2714 */
2715 void File::DeleteSample(Sample* pSample) {
2716 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2717 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2718 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2719 pSamples->erase(iter);
2720 delete pSample;
2721 }
2722
2723 void File::LoadSamples() {
2724 LoadSamples(NULL);
2725 }
2726
2727 void File::LoadSamples(progress_t* pProgress) {
2728 if (!pSamples) pSamples = new SampleList;
2729
2730 RIFF::File* file = pRIFF;
2731
2732 // just for progress calculation
2733 int iSampleIndex = 0;
2734 int iTotalSamples = WavePoolCount;
2735
2736 // check if samples should be loaded from extension files
2737 int lastFileNo = 0;
2738 for (int i = 0 ; i < WavePoolCount ; i++) {
2739 if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2740 }
2741 String name(pRIFF->GetFileName());
2742 int nameLen = name.length();
2743 char suffix[6];
2744 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2745
2746 for (int fileNo = 0 ; ; ) {
2747 RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2748 if (wvpl) {
2749 unsigned long wvplFileOffset = wvpl->GetFilePos();
2750 RIFF::List* wave = wvpl->GetFirstSubList();
2751 while (wave) {
2752 if (wave->GetListType() == LIST_TYPE_WAVE) {
2753 // notify current progress
2754 const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2755 __notify_progress(pProgress, subprogress);
2756
2757 unsigned long waveFileOffset = wave->GetFilePos();
2758 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2759
2760 iSampleIndex++;
2761 }
2762 wave = wvpl->GetNextSubList();
2763 }
2764
2765 if (fileNo == lastFileNo) break;
2766
2767 // open extension file (*.gx01, *.gx02, ...)
2768 fileNo++;
2769 sprintf(suffix, ".gx%02d", fileNo);
2770 name.replace(nameLen, 5, suffix);
2771 file = new RIFF::File(name);
2772 ExtensionFiles.push_back(file);
2773 } else break;
2774 }
2775
2776 __notify_progress(pProgress, 1.0); // notify done
2777 }
2778
2779 Instrument* File::GetFirstInstrument() {
2780 if (!pInstruments) LoadInstruments();
2781 if (!pInstruments) return NULL;
2782 InstrumentsIterator = pInstruments->begin();
2783 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2784 }
2785
2786 Instrument* File::GetNextInstrument() {
2787 if (!pInstruments) return NULL;
2788 InstrumentsIterator++;
2789 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2790 }
2791
2792 /**
2793 * Returns the instrument with the given index.
2794 *
2795 * @param index - number of the sought instrument (0..n)
2796 * @param pProgress - optional: callback function for progress notification
2797 * @returns sought instrument or NULL if there's no such instrument
2798 */
2799 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2800 if (!pInstruments) {
2801 // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2802
2803 // sample loading subtask
2804 progress_t subprogress;
2805 __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2806 __notify_progress(&subprogress, 0.0f);
2807 GetFirstSample(&subprogress); // now force all samples to be loaded
2808 __notify_progress(&subprogress, 1.0f);
2809
2810 // instrument loading subtask
2811 if (pProgress && pProgress->callback) {
2812 subprogress.__range_min = subprogress.__range_max;
2813 subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2814 }
2815 __notify_progress(&subprogress, 0.0f);
2816 LoadInstruments(&subprogress);
2817 __notify_progress(&subprogress, 1.0f);
2818 }
2819 if (!pInstruments) return NULL;
2820 InstrumentsIterator = pInstruments->begin();
2821 for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2822 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2823 InstrumentsIterator++;
2824 }
2825 return NULL;
2826 }
2827
2828 /** @brief Add a new instrument definition.
2829 *
2830 * This will create a new Instrument object for the gig file. You have
2831 * to call Save() to make this persistent to the file.
2832 *
2833 * @returns pointer to new Instrument object
2834 */
2835 Instrument* File::AddInstrument() {
2836 if (!pInstruments) LoadInstruments();
2837 __ensureMandatoryChunksExist();
2838 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2839 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2840 Instrument* pInstrument = new Instrument(this, lstInstr);
2841 pInstruments->push_back(pInstrument);
2842 return pInstrument;
2843 }
2844
2845 /** @brief Delete an instrument.
2846 *
2847 * This will delete the given Instrument object from the gig file. You
2848 * have to call Save() to make this persistent to the file.
2849 *
2850 * @param pInstrument - instrument to delete
2851 * @throws gig::Excption if given instrument could not be found
2852 */
2853 void File::DeleteInstrument(Instrument* pInstrument) {
2854 if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2855 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2856 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2857 pInstruments->erase(iter);
2858 delete pInstrument;
2859 }
2860
2861 void File::LoadInstruments() {
2862 LoadInstruments(NULL);
2863 }
2864
2865 void File::LoadInstruments(progress_t* pProgress) {
2866 if (!pInstruments) pInstruments = new InstrumentList;
2867 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2868 if (lstInstruments) {
2869 int iInstrumentIndex = 0;
2870 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2871 while (lstInstr) {
2872 if (lstInstr->GetListType() == LIST_TYPE_INS) {
2873 // notify current progress
2874 const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2875 __notify_progress(pProgress, localProgress);
2876
2877 // divide local progress into subprogress for loading current Instrument
2878 progress_t subprogress;
2879 __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2880
2881 pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2882
2883 iInstrumentIndex++;
2884 }
2885 lstInstr = lstInstruments->GetNextSubList();
2886 }
2887 __notify_progress(pProgress, 1.0); // notify done
2888 }
2889 }
2890
2891
2892
2893 // *************** Exception ***************
2894 // *
2895
2896 Exception::Exception(String Message) : DLS::Exception(Message) {
2897 }
2898
2899 void Exception::PrintMessage() {
2900 std::cout << "gig::Exception: " << Message << std::endl;
2901 }
2902
2903
2904 // *************** functions ***************
2905 // *
2906
2907 /**
2908 * Returns the name of this C++ library. This is usually "libgig" of
2909 * course. This call is equivalent to RIFF::libraryName() and
2910 * DLS::libraryName().
2911 */
2912 String libraryName() {
2913 return PACKAGE;
2914 }
2915
2916 /**
2917 * Returns version of this C++ library. This call is equivalent to
2918 * RIFF::libraryVersion() and DLS::libraryVersion().
2919 */
2920 String libraryVersion() {
2921 return VERSION;
2922 }
2923
2924 } // namespace gig

  ViewVC Help
Powered by ViewVC