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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3182 - (show annotations) (download)
Sun May 14 20:40:02 2017 UTC (3 years, 5 months ago) by schoenebeck
File size: 281706 byte(s)
* Serialization framework: moved methods setVersion() and
  setMinVersion() from class Object to class Archive, and
  hide enum type operation_t from the public API.
* Bumped version (4.0.0.svn23).

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