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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2547 - (show annotations) (download)
Tue May 13 11:17:24 2014 UTC (6 years, 5 months ago) by schoenebeck
File size: 218005 byte(s)
* Fix: don't alter region pointer in gig::DimensionRegion::CopyAssign()
  (caused crash with the new "combine instruments" feature in gigedit).
* Added new method gig::Region::GetDimensionDefinition(dimension_t type).
* Added some more sanity checks in gig::Region::AddDimension().
* Added inline helper methods overlaps() for struct DLS::range_t.
* Added more API doc comments.
* Bumped version (3.3.0.svn10).


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