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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3323 - (show annotations) (download)
Thu Jul 20 22:09:54 2017 UTC (11 months ago) by schoenebeck
File size: 284084 byte(s)
* gig.h/.cpp: Added new struct "eg_opt_t" and new class member variable
  "DimensionRegion::EGOptions" as an extension to the gig file format,
  which allows to override the default behavior of EGs' state machines.
* DLS.h: Got rid of C-style typedefs.
* src/tools/gigdump.cpp: Print the new EG behavior options.
* Bumped version (4.0.0.svn27).

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