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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3138 - (show annotations) (download)
Wed May 3 14:41:58 2017 UTC (2 years, 9 months ago) by schoenebeck
File size: 281449 byte(s)
* Added new "Serialization" framework (and equally named namespace)
  which allows to serialize and deserialize native C++ objects
  in a portable, easy and flexible way.
* gig.cpp/gig.h: Added support for serializing & deserializing
  DimensionRegion objects (and crossfade_t and leverage_ctrl_t
  objects).
* Bumped version (4.0.0.svn15).

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