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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3112 - (show annotations) (download)
Wed Feb 15 13:21:31 2017 UTC (3 years, 9 months ago) by schoenebeck
File size: 277238 byte(s)
* gig.cpp: Instruments' default pitch bend range is now +-2 semi tones.
* Bumped version (4.0.0.svn12).

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