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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2702 - (show annotations) (download)
Tue Jan 13 00:32:30 2015 UTC (9 years, 1 month ago) by schoenebeck
File size: 264840 byte(s)
* Bugfix of previous commit.
* Bumped version (3.3.0.svn27).

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