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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2912 * Copyright (C) 2003-2016 by Christian Schoenebeck *
6 schoenebeck 384 * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
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 schoenebeck 809 #include "helper.h"
27    
28 persson 1713 #include <algorithm>
29 schoenebeck 809 #include <math.h>
30 schoenebeck 384 #include <iostream>
31 schoenebeck 2555 #include <assert.h>
32 schoenebeck 384
33 schoenebeck 2912 /// 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 schoenebeck 809 /// 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 schoenebeck 515 namespace gig {
59 schoenebeck 2
60 schoenebeck 809 // *************** Internal functions for sample decompression ***************
61 persson 365 // *
62    
63 schoenebeck 515 namespace {
64    
65 persson 365 inline int get12lo(const unsigned char* pSrc)
66     {
67     const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
68     return x & 0x800 ? x - 0x1000 : x;
69     }
70    
71     inline int get12hi(const unsigned char* pSrc)
72     {
73     const int x = pSrc[1] >> 4 | pSrc[2] << 4;
74     return x & 0x800 ? x - 0x1000 : x;
75     }
76    
77     inline int16_t get16(const unsigned char* pSrc)
78     {
79     return int16_t(pSrc[0] | pSrc[1] << 8);
80     }
81    
82     inline int get24(const unsigned char* pSrc)
83     {
84     const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
85     return x & 0x800000 ? x - 0x1000000 : x;
86     }
87    
88 persson 902 inline void store24(unsigned char* pDst, int x)
89     {
90     pDst[0] = x;
91     pDst[1] = x >> 8;
92     pDst[2] = x >> 16;
93     }
94    
95 persson 365 void Decompress16(int compressionmode, const unsigned char* params,
96 persson 372 int srcStep, int dstStep,
97     const unsigned char* pSrc, int16_t* pDst,
98 schoenebeck 2912 file_offset_t currentframeoffset,
99     file_offset_t copysamples)
100 persson 365 {
101     switch (compressionmode) {
102     case 0: // 16 bit uncompressed
103     pSrc += currentframeoffset * srcStep;
104     while (copysamples) {
105     *pDst = get16(pSrc);
106 persson 372 pDst += dstStep;
107 persson 365 pSrc += srcStep;
108     copysamples--;
109     }
110     break;
111    
112     case 1: // 16 bit compressed to 8 bit
113     int y = get16(params);
114     int dy = get16(params + 2);
115     while (currentframeoffset) {
116     dy -= int8_t(*pSrc);
117     y -= dy;
118     pSrc += srcStep;
119     currentframeoffset--;
120     }
121     while (copysamples) {
122     dy -= int8_t(*pSrc);
123     y -= dy;
124     *pDst = y;
125 persson 372 pDst += dstStep;
126 persson 365 pSrc += srcStep;
127     copysamples--;
128     }
129     break;
130     }
131     }
132    
133     void Decompress24(int compressionmode, const unsigned char* params,
134 persson 902 int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135 schoenebeck 2912 file_offset_t currentframeoffset,
136     file_offset_t copysamples, int truncatedBits)
137 persson 365 {
138 persson 695 int y, dy, ddy, dddy;
139 persson 437
140 persson 695 #define GET_PARAMS(params) \
141     y = get24(params); \
142     dy = y - get24((params) + 3); \
143     ddy = get24((params) + 6); \
144     dddy = get24((params) + 9)
145 persson 365
146     #define SKIP_ONE(x) \
147 persson 695 dddy -= (x); \
148     ddy -= dddy; \
149     dy = -dy - ddy; \
150     y += dy
151 persson 365
152     #define COPY_ONE(x) \
153     SKIP_ONE(x); \
154 persson 902 store24(pDst, y << truncatedBits); \
155 persson 372 pDst += dstStep
156 persson 365
157     switch (compressionmode) {
158     case 2: // 24 bit uncompressed
159     pSrc += currentframeoffset * 3;
160     while (copysamples) {
161 persson 902 store24(pDst, get24(pSrc) << truncatedBits);
162 persson 372 pDst += dstStep;
163 persson 365 pSrc += 3;
164     copysamples--;
165     }
166     break;
167    
168     case 3: // 24 bit compressed to 16 bit
169     GET_PARAMS(params);
170     while (currentframeoffset) {
171     SKIP_ONE(get16(pSrc));
172     pSrc += 2;
173     currentframeoffset--;
174     }
175     while (copysamples) {
176     COPY_ONE(get16(pSrc));
177     pSrc += 2;
178     copysamples--;
179     }
180     break;
181    
182     case 4: // 24 bit compressed to 12 bit
183     GET_PARAMS(params);
184     while (currentframeoffset > 1) {
185     SKIP_ONE(get12lo(pSrc));
186     SKIP_ONE(get12hi(pSrc));
187     pSrc += 3;
188     currentframeoffset -= 2;
189     }
190     if (currentframeoffset) {
191     SKIP_ONE(get12lo(pSrc));
192     currentframeoffset--;
193     if (copysamples) {
194     COPY_ONE(get12hi(pSrc));
195     pSrc += 3;
196     copysamples--;
197     }
198     }
199     while (copysamples > 1) {
200     COPY_ONE(get12lo(pSrc));
201     COPY_ONE(get12hi(pSrc));
202     pSrc += 3;
203     copysamples -= 2;
204     }
205     if (copysamples) {
206     COPY_ONE(get12lo(pSrc));
207     }
208     break;
209    
210     case 5: // 24 bit compressed to 8 bit
211     GET_PARAMS(params);
212     while (currentframeoffset) {
213     SKIP_ONE(int8_t(*pSrc++));
214     currentframeoffset--;
215     }
216     while (copysamples) {
217     COPY_ONE(int8_t(*pSrc++));
218     copysamples--;
219     }
220     break;
221     }
222     }
223    
224     const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
225     const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
226     const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
227     const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
228     }
229    
230    
231 schoenebeck 1113
232 schoenebeck 1381 // *************** Internal CRC-32 (Cyclic Redundancy Check) functions ***************
233     // *
234    
235     static uint32_t* __initCRCTable() {
236     static uint32_t res[256];
237    
238     for (int i = 0 ; i < 256 ; i++) {
239     uint32_t c = i;
240     for (int j = 0 ; j < 8 ; j++) {
241     c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
242     }
243     res[i] = c;
244     }
245     return res;
246     }
247    
248     static const uint32_t* __CRCTable = __initCRCTable();
249    
250     /**
251     * Initialize a CRC variable.
252     *
253     * @param crc - variable to be initialized
254     */
255     inline static void __resetCRC(uint32_t& crc) {
256     crc = 0xffffffff;
257     }
258    
259     /**
260     * Used to calculate checksums of the sample data in a gig file. The
261     * checksums are stored in the 3crc chunk of the gig file and
262     * automatically updated when a sample is written with Sample::Write().
263     *
264     * One should call __resetCRC() to initialize the CRC variable to be
265     * used before calling this function the first time.
266     *
267     * After initializing the CRC variable one can call this function
268     * arbitrary times, i.e. to split the overall CRC calculation into
269     * steps.
270     *
271     * Once the whole data was processed by __calculateCRC(), one should
272     * call __encodeCRC() to get the final CRC result.
273     *
274     * @param buf - pointer to data the CRC shall be calculated of
275     * @param bufSize - size of the data to be processed
276     * @param crc - variable the CRC sum shall be stored to
277     */
278 schoenebeck 3053 static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
279     for (size_t i = 0 ; i < bufSize ; i++) {
280 schoenebeck 1381 crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281     }
282     }
283    
284     /**
285     * Returns the final CRC result.
286     *
287     * @param crc - variable previously passed to __calculateCRC()
288     */
289     inline static uint32_t __encodeCRC(const uint32_t& crc) {
290     return crc ^ 0xffffffff;
291     }
292    
293    
294    
295 schoenebeck 1113 // *************** Other Internal functions ***************
296     // *
297    
298     static split_type_t __resolveSplitType(dimension_t dimension) {
299     return (
300     dimension == dimension_layer ||
301     dimension == dimension_samplechannel ||
302     dimension == dimension_releasetrigger ||
303     dimension == dimension_keyboard ||
304     dimension == dimension_roundrobin ||
305     dimension == dimension_random ||
306     dimension == dimension_smartmidi ||
307     dimension == dimension_roundrobinkeyboard
308     ) ? split_type_bit : split_type_normal;
309     }
310    
311     static int __resolveZoneSize(dimension_def_t& dimension_definition) {
312     return (dimension_definition.split_type == split_type_normal)
313     ? int(128.0 / dimension_definition.zones) : 0;
314     }
315    
316    
317    
318 schoenebeck 2 // *************** Sample ***************
319     // *
320    
321 schoenebeck 2922 size_t Sample::Instances = 0;
322 schoenebeck 384 buffer_t Sample::InternalDecompressionBuffer;
323 schoenebeck 2
324 schoenebeck 809 /** @brief Constructor.
325     *
326     * Load an existing sample or create a new one. A 'wave' list chunk must
327     * be given to this constructor. In case the given 'wave' list chunk
328     * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
329     * format and sample data will be loaded from there, otherwise default
330     * values will be used and those chunks will be created when
331     * File::Save() will be called later on.
332     *
333     * @param pFile - pointer to gig::File where this sample is
334     * located (or will be located)
335     * @param waveList - pointer to 'wave' list chunk which is (or
336     * will be) associated with this sample
337     * @param WavePoolOffset - offset of this sample data from wave pool
338     * ('wvpl') list chunk
339     * @param fileNo - number of an extension file where this sample
340     * is located, 0 otherwise
341 schoenebeck 2989 * @param index - wave pool index of sample (may be -1 on new sample)
342 schoenebeck 809 */
343 schoenebeck 2989 Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
344     : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345     {
346 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
347 persson 1180 { CHUNK_ID_INAM, 64 },
348     { 0, 0 }
349     };
350 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
351 schoenebeck 2 Instances++;
352 persson 666 FileNo = fileNo;
353 schoenebeck 2
354 schoenebeck 1381 __resetCRC(crc);
355 schoenebeck 2989 // if this is not a new sample, try to get the sample's already existing
356     // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357     // checksum of the time when the sample was consciously modified by the
358     // user for the last time (by calling Sample::Write() that is).
359     if (index >= 0) { // not a new file ...
360     try {
361     uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362     this->crc = crc;
363     } catch (...) {}
364     }
365 schoenebeck 1381
366 schoenebeck 809 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367     if (pCk3gix) {
368 schoenebeck 929 uint16_t iSampleGroup = pCk3gix->ReadInt16();
369 schoenebeck 930 pGroup = pFile->GetGroup(iSampleGroup);
370 schoenebeck 809 } else { // '3gix' chunk missing
371 schoenebeck 930 // by default assigned to that mandatory "Default Group"
372     pGroup = pFile->GetGroup(0);
373 schoenebeck 809 }
374 schoenebeck 2
375 schoenebeck 809 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
376     if (pCkSmpl) {
377     Manufacturer = pCkSmpl->ReadInt32();
378     Product = pCkSmpl->ReadInt32();
379     SamplePeriod = pCkSmpl->ReadInt32();
380     MIDIUnityNote = pCkSmpl->ReadInt32();
381     FineTune = pCkSmpl->ReadInt32();
382     pCkSmpl->Read(&SMPTEFormat, 1, 4);
383     SMPTEOffset = pCkSmpl->ReadInt32();
384     Loops = pCkSmpl->ReadInt32();
385     pCkSmpl->ReadInt32(); // manufByt
386     LoopID = pCkSmpl->ReadInt32();
387     pCkSmpl->Read(&LoopType, 1, 4);
388     LoopStart = pCkSmpl->ReadInt32();
389     LoopEnd = pCkSmpl->ReadInt32();
390     LoopFraction = pCkSmpl->ReadInt32();
391     LoopPlayCount = pCkSmpl->ReadInt32();
392     } else { // 'smpl' chunk missing
393     // use default values
394     Manufacturer = 0;
395     Product = 0;
396 persson 928 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
397 persson 1218 MIDIUnityNote = 60;
398 schoenebeck 809 FineTune = 0;
399 persson 1182 SMPTEFormat = smpte_format_no_offset;
400 schoenebeck 809 SMPTEOffset = 0;
401     Loops = 0;
402     LoopID = 0;
403 persson 1182 LoopType = loop_type_normal;
404 schoenebeck 809 LoopStart = 0;
405     LoopEnd = 0;
406     LoopFraction = 0;
407     LoopPlayCount = 0;
408     }
409 schoenebeck 2
410     FrameTable = NULL;
411     SamplePos = 0;
412     RAMCache.Size = 0;
413     RAMCache.pStart = NULL;
414     RAMCache.NullExtensionSize = 0;
415    
416 persson 365 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
417    
418 persson 437 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
419     Compressed = ewav;
420     Dithered = false;
421     TruncatedBits = 0;
422 schoenebeck 2 if (Compressed) {
423 persson 437 uint32_t version = ewav->ReadInt32();
424     if (version == 3 && BitDepth == 24) {
425     Dithered = ewav->ReadInt32();
426     ewav->SetPos(Channels == 2 ? 84 : 64);
427     TruncatedBits = ewav->ReadInt32();
428     }
429 schoenebeck 2 ScanCompressedSample();
430     }
431 schoenebeck 317
432     // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
433 schoenebeck 384 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
434     InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
435     InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
436 schoenebeck 317 }
437 persson 437 FrameOffset = 0; // just for streaming compressed samples
438 schoenebeck 21
439 persson 864 LoopSize = LoopEnd - LoopStart + 1;
440 schoenebeck 2 }
441    
442 schoenebeck 809 /**
443 schoenebeck 2482 * Make a (semi) deep copy of the Sample object given by @a orig (without
444     * the actual waveform data) and assign it to this object.
445     *
446     * Discussion: copying .gig samples is a bit tricky. It requires three
447     * steps:
448     * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
449     * its new sample waveform data size.
450     * 2. Saving the file (done by File::Save()) so that it gains correct size
451     * and layout for writing the actual wave form data directly to disc
452     * in next step.
453     * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
454     *
455     * @param orig - original Sample object to be copied from
456     */
457     void Sample::CopyAssignMeta(const Sample* orig) {
458     // handle base classes
459     DLS::Sample::CopyAssignCore(orig);
460    
461     // handle actual own attributes of this class
462     Manufacturer = orig->Manufacturer;
463     Product = orig->Product;
464     SamplePeriod = orig->SamplePeriod;
465     MIDIUnityNote = orig->MIDIUnityNote;
466     FineTune = orig->FineTune;
467     SMPTEFormat = orig->SMPTEFormat;
468     SMPTEOffset = orig->SMPTEOffset;
469     Loops = orig->Loops;
470     LoopID = orig->LoopID;
471     LoopType = orig->LoopType;
472     LoopStart = orig->LoopStart;
473     LoopEnd = orig->LoopEnd;
474     LoopSize = orig->LoopSize;
475     LoopFraction = orig->LoopFraction;
476     LoopPlayCount = orig->LoopPlayCount;
477    
478     // schedule resizing this sample to the given sample's size
479     Resize(orig->GetSize());
480     }
481    
482     /**
483     * Should be called after CopyAssignMeta() and File::Save() sequence.
484     * Read more about it in the discussion of CopyAssignMeta(). This method
485     * copies the actual waveform data by disk streaming.
486     *
487     * @e CAUTION: this method is currently not thread safe! During this
488     * operation the sample must not be used for other purposes by other
489     * threads!
490     *
491     * @param orig - original Sample object to be copied from
492     */
493     void Sample::CopyAssignWave(const Sample* orig) {
494     const int iReadAtOnce = 32*1024;
495     char* buf = new char[iReadAtOnce * orig->FrameSize];
496     Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497 schoenebeck 2912 file_offset_t restorePos = pOrig->GetPos();
498 schoenebeck 2482 pOrig->SetPos(0);
499     SetPos(0);
500 schoenebeck 2912 for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501 schoenebeck 2482 n = pOrig->Read(buf, iReadAtOnce))
502     {
503     Write(buf, n);
504     }
505     pOrig->SetPos(restorePos);
506     delete [] buf;
507     }
508    
509     /**
510 schoenebeck 809 * Apply sample and its settings to the respective RIFF chunks. You have
511     * to call File::Save() to make changes persistent.
512     *
513     * Usually there is absolutely no need to call this method explicitly.
514     * It will be called automatically when File::Save() was called.
515     *
516 schoenebeck 2682 * @param pProgress - callback function for progress notification
517 schoenebeck 1050 * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
518 schoenebeck 809 * was provided yet
519     * @throws gig::Exception if there is any invalid sample setting
520     */
521 schoenebeck 2682 void Sample::UpdateChunks(progress_t* pProgress) {
522 schoenebeck 809 // first update base class's chunks
523 schoenebeck 2682 DLS::Sample::UpdateChunks(pProgress);
524 schoenebeck 809
525     // make sure 'smpl' chunk exists
526     pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
527 persson 1182 if (!pCkSmpl) {
528     pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
529     memset(pCkSmpl->LoadChunkData(), 0, 60);
530     }
531 schoenebeck 809 // update 'smpl' chunk
532     uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
533 persson 918 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
534 persson 1179 store32(&pData[0], Manufacturer);
535     store32(&pData[4], Product);
536     store32(&pData[8], SamplePeriod);
537     store32(&pData[12], MIDIUnityNote);
538     store32(&pData[16], FineTune);
539     store32(&pData[20], SMPTEFormat);
540     store32(&pData[24], SMPTEOffset);
541     store32(&pData[28], Loops);
542 schoenebeck 809
543     // we skip 'manufByt' for now (4 bytes)
544    
545 persson 1179 store32(&pData[36], LoopID);
546     store32(&pData[40], LoopType);
547     store32(&pData[44], LoopStart);
548     store32(&pData[48], LoopEnd);
549     store32(&pData[52], LoopFraction);
550     store32(&pData[56], LoopPlayCount);
551 schoenebeck 809
552     // make sure '3gix' chunk exists
553     pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
554     if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
555 schoenebeck 929 // determine appropriate sample group index (to be stored in chunk)
556 schoenebeck 930 uint16_t iSampleGroup = 0; // 0 refers to default sample group
557 schoenebeck 929 File* pFile = static_cast<File*>(pParent);
558     if (pFile->pGroups) {
559     std::list<Group*>::iterator iter = pFile->pGroups->begin();
560     std::list<Group*>::iterator end = pFile->pGroups->end();
561 schoenebeck 930 for (int i = 0; iter != end; i++, iter++) {
562 schoenebeck 929 if (*iter == pGroup) {
563     iSampleGroup = i;
564     break; // found
565     }
566     }
567     }
568 schoenebeck 809 // update '3gix' chunk
569     pData = (uint8_t*) pCk3gix->LoadChunkData();
570 persson 1179 store16(&pData[0], iSampleGroup);
571 schoenebeck 2484
572     // if the library user toggled the "Compressed" attribute from true to
573     // false, then the EWAV chunk associated with compressed samples needs
574     // to be deleted
575     RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
576     if (ewav && !Compressed) {
577     pWaveList->DeleteSubChunk(ewav);
578     }
579 schoenebeck 809 }
580    
581 schoenebeck 2 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
582     void Sample::ScanCompressedSample() {
583     //TODO: we have to add some more scans here (e.g. determine compression rate)
584     this->SamplesTotal = 0;
585 schoenebeck 2912 std::list<file_offset_t> frameOffsets;
586 schoenebeck 2
587 persson 365 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
588 schoenebeck 384 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
589 persson 365
590 schoenebeck 2 // Scanning
591     pCkData->SetPos(0);
592 persson 365 if (Channels == 2) { // Stereo
593     for (int i = 0 ; ; i++) {
594     // for 24 bit samples every 8:th frame offset is
595     // stored, to save some memory
596     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
597    
598     const int mode_l = pCkData->ReadUint8();
599     const int mode_r = pCkData->ReadUint8();
600     if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
601 schoenebeck 2912 const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
602 persson 365
603     if (pCkData->RemainingBytes() <= frameSize) {
604     SamplesInLastFrame =
605     ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
606     (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
607     SamplesTotal += SamplesInLastFrame;
608 schoenebeck 2 break;
609 persson 365 }
610     SamplesTotal += SamplesPerFrame;
611     pCkData->SetPos(frameSize, RIFF::stream_curpos);
612     }
613     }
614     else { // Mono
615     for (int i = 0 ; ; i++) {
616     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
617    
618     const int mode = pCkData->ReadUint8();
619     if (mode > 5) throw gig::Exception("Unknown compression mode");
620 schoenebeck 2912 const file_offset_t frameSize = bytesPerFrame[mode];
621 persson 365
622     if (pCkData->RemainingBytes() <= frameSize) {
623     SamplesInLastFrame =
624     ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
625     SamplesTotal += SamplesInLastFrame;
626 schoenebeck 2 break;
627 persson 365 }
628     SamplesTotal += SamplesPerFrame;
629     pCkData->SetPos(frameSize, RIFF::stream_curpos);
630 schoenebeck 2 }
631     }
632     pCkData->SetPos(0);
633    
634     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
635     if (FrameTable) delete[] FrameTable;
636 schoenebeck 2912 FrameTable = new file_offset_t[frameOffsets.size()];
637     std::list<file_offset_t>::iterator end = frameOffsets.end();
638     std::list<file_offset_t>::iterator iter = frameOffsets.begin();
639 schoenebeck 2 for (int i = 0; iter != end; i++, iter++) {
640     FrameTable[i] = *iter;
641     }
642     }
643    
644     /**
645     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
646     * ReleaseSampleData() to free the memory if you don't need the cached
647     * sample data anymore.
648     *
649     * @returns buffer_t structure with start address and size of the buffer
650     * in bytes
651     * @see ReleaseSampleData(), Read(), SetPos()
652     */
653     buffer_t Sample::LoadSampleData() {
654     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
655     }
656    
657     /**
658     * Reads (uncompresses if needed) and caches the first \a SampleCount
659     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
660     * memory space if you don't need the cached samples anymore. There is no
661     * guarantee that exactly \a SampleCount samples will be cached; this is
662     * not an error. The size will be eventually truncated e.g. to the
663     * beginning of a frame of a compressed sample. This is done for
664     * efficiency reasons while streaming the wave by your sampler engine
665     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
666     * that will be returned to determine the actual cached samples, but note
667     * that the size is given in bytes! You get the number of actually cached
668     * samples by dividing it by the frame size of the sample:
669 schoenebeck 384 * @code
670 schoenebeck 2 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
671     * long cachedsamples = buf.Size / pSample->FrameSize;
672 schoenebeck 384 * @endcode
673 schoenebeck 2 *
674     * @param SampleCount - number of sample points to load into RAM
675     * @returns buffer_t structure with start address and size of
676     * the cached sample data in bytes
677     * @see ReleaseSampleData(), Read(), SetPos()
678     */
679 schoenebeck 2912 buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
680 schoenebeck 2 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
681     }
682    
683     /**
684     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
685     * ReleaseSampleData() to free the memory if you don't need the cached
686     * sample data anymore.
687     * The method will add \a NullSamplesCount silence samples past the
688     * official buffer end (this won't affect the 'Size' member of the
689     * buffer_t structure, that means 'Size' always reflects the size of the
690     * actual sample data, the buffer might be bigger though). Silence
691     * samples past the official buffer are needed for differential
692     * algorithms that always have to take subsequent samples into account
693     * (resampling/interpolation would be an important example) and avoids
694     * memory access faults in such cases.
695     *
696     * @param NullSamplesCount - number of silence samples the buffer should
697     * be extended past it's data end
698     * @returns buffer_t structure with start address and
699     * size of the buffer in bytes
700     * @see ReleaseSampleData(), Read(), SetPos()
701     */
702     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
703     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
704     }
705    
706     /**
707     * Reads (uncompresses if needed) and caches the first \a SampleCount
708     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
709     * memory space if you don't need the cached samples anymore. There is no
710     * guarantee that exactly \a SampleCount samples will be cached; this is
711     * not an error. The size will be eventually truncated e.g. to the
712     * beginning of a frame of a compressed sample. This is done for
713     * efficiency reasons while streaming the wave by your sampler engine
714     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
715     * that will be returned to determine the actual cached samples, but note
716     * that the size is given in bytes! You get the number of actually cached
717     * samples by dividing it by the frame size of the sample:
718 schoenebeck 384 * @code
719 schoenebeck 2 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
720     * long cachedsamples = buf.Size / pSample->FrameSize;
721 schoenebeck 384 * @endcode
722 schoenebeck 2 * The method will add \a NullSamplesCount silence samples past the
723     * official buffer end (this won't affect the 'Size' member of the
724     * buffer_t structure, that means 'Size' always reflects the size of the
725     * actual sample data, the buffer might be bigger though). Silence
726     * samples past the official buffer are needed for differential
727     * algorithms that always have to take subsequent samples into account
728     * (resampling/interpolation would be an important example) and avoids
729     * memory access faults in such cases.
730     *
731     * @param SampleCount - number of sample points to load into RAM
732     * @param NullSamplesCount - number of silence samples the buffer should
733     * be extended past it's data end
734     * @returns buffer_t structure with start address and
735     * size of the cached sample data in bytes
736     * @see ReleaseSampleData(), Read(), SetPos()
737     */
738 schoenebeck 2912 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
739 schoenebeck 2 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
740     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
741 schoenebeck 2912 file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
742 schoenebeck 1851 SetPos(0); // reset read position to begin of sample
743 schoenebeck 2 RAMCache.pStart = new int8_t[allocationsize];
744     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
745     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
746     // fill the remaining buffer space with silence samples
747     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
748     return GetCache();
749     }
750    
751     /**
752     * Returns current cached sample points. A buffer_t structure will be
753     * returned which contains address pointer to the begin of the cache and
754     * the size of the cached sample data in bytes. Use
755     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
756     * RAM.
757     *
758     * @returns buffer_t structure with current cached sample points
759     * @see LoadSampleData();
760     */
761     buffer_t Sample::GetCache() {
762     // return a copy of the buffer_t structure
763     buffer_t result;
764     result.Size = this->RAMCache.Size;
765     result.pStart = this->RAMCache.pStart;
766     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
767     return result;
768     }
769    
770     /**
771     * Frees the cached sample from RAM if loaded with
772     * <i>LoadSampleData()</i> previously.
773     *
774     * @see LoadSampleData();
775     */
776     void Sample::ReleaseSampleData() {
777     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
778     RAMCache.pStart = NULL;
779     RAMCache.Size = 0;
780 schoenebeck 1851 RAMCache.NullExtensionSize = 0;
781 schoenebeck 2 }
782    
783 schoenebeck 809 /** @brief Resize sample.
784     *
785     * Resizes the sample's wave form data, that is the actual size of
786     * sample wave data possible to be written for this sample. This call
787     * will return immediately and just schedule the resize operation. You
788     * should call File::Save() to actually perform the resize operation(s)
789     * "physically" to the file. As this can take a while on large files, it
790     * is recommended to call Resize() first on all samples which have to be
791     * resized and finally to call File::Save() to perform all those resize
792     * operations in one rush.
793     *
794     * The actual size (in bytes) is dependant to the current FrameSize
795     * value. You may want to set FrameSize before calling Resize().
796     *
797     * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
798     * enlarged samples before calling File::Save() as this might exceed the
799     * current sample's boundary!
800     *
801 schoenebeck 1050 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
802     * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
803 schoenebeck 809 * other formats will fail!
804     *
805 schoenebeck 2922 * @param NewSize - new sample wave data size in sample points (must be
806     * greater than zero)
807 schoenebeck 1050 * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
808 schoenebeck 2922 * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
809 schoenebeck 809 * @throws gig::Exception if existing sample is compressed
810     * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
811     * DLS::Sample::FormatTag, File::Save()
812     */
813 schoenebeck 2922 void Sample::Resize(file_offset_t NewSize) {
814 schoenebeck 809 if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
815 schoenebeck 2922 DLS::Sample::Resize(NewSize);
816 schoenebeck 809 }
817    
818 schoenebeck 2 /**
819     * Sets the position within the sample (in sample points, not in
820     * bytes). Use this method and <i>Read()</i> if you don't want to load
821     * the sample into RAM, thus for disk streaming.
822     *
823     * Although the original Gigasampler engine doesn't allow positioning
824     * within compressed samples, I decided to implement it. Even though
825     * the Gigasampler format doesn't allow to define loops for compressed
826     * samples at the moment, positioning within compressed samples might be
827     * interesting for some sampler engines though. The only drawback about
828     * my decision is that it takes longer to load compressed gig Files on
829     * startup, because it's neccessary to scan the samples for some
830     * mandatory informations. But I think as it doesn't affect the runtime
831     * efficiency, nobody will have a problem with that.
832     *
833     * @param SampleCount number of sample points to jump
834     * @param Whence optional: to which relation \a SampleCount refers
835     * to, if omited <i>RIFF::stream_start</i> is assumed
836     * @returns the new sample position
837     * @see Read()
838     */
839 schoenebeck 2912 file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
840 schoenebeck 2 if (Compressed) {
841     switch (Whence) {
842     case RIFF::stream_curpos:
843     this->SamplePos += SampleCount;
844     break;
845     case RIFF::stream_end:
846     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
847     break;
848     case RIFF::stream_backward:
849     this->SamplePos -= SampleCount;
850     break;
851     case RIFF::stream_start: default:
852     this->SamplePos = SampleCount;
853     break;
854     }
855     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
856    
857 schoenebeck 2912 file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
858 schoenebeck 2 this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
859     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
860     return this->SamplePos;
861     }
862     else { // not compressed
863 schoenebeck 2912 file_offset_t orderedBytes = SampleCount * this->FrameSize;
864     file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
865 schoenebeck 2 return (result == orderedBytes) ? SampleCount
866     : result / this->FrameSize;
867     }
868     }
869    
870     /**
871     * Returns the current position in the sample (in sample points).
872     */
873 schoenebeck 2912 file_offset_t Sample::GetPos() const {
874 schoenebeck 2 if (Compressed) return SamplePos;
875     else return pCkData->GetPos() / FrameSize;
876     }
877    
878     /**
879 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
880     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
881     * the position within the sample respectively, this method honors the
882     * looping informations of the sample (if any). The sample wave stream
883     * will be decompressed on the fly if using a compressed sample. Use this
884     * method if you don't want to load the sample into RAM, thus for disk
885     * streaming. All this methods needs to know to proceed with streaming
886     * for the next time you call this method is stored in \a pPlaybackState.
887     * You have to allocate and initialize the playback_state_t structure by
888     * yourself before you use it to stream a sample:
889 schoenebeck 384 * @code
890     * gig::playback_state_t playbackstate;
891     * playbackstate.position = 0;
892     * playbackstate.reverse = false;
893     * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
894     * @endcode
895 schoenebeck 24 * You don't have to take care of things like if there is actually a loop
896     * defined or if the current read position is located within a loop area.
897     * The method already handles such cases by itself.
898     *
899 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
900     * have to use an external decompression buffer for <b>EACH</b>
901     * streaming thread to avoid race conditions and crashes!
902     *
903 schoenebeck 24 * @param pBuffer destination buffer
904     * @param SampleCount number of sample points to read
905     * @param pPlaybackState will be used to store and reload the playback
906     * state for the next ReadAndLoop() call
907 persson 864 * @param pDimRgn dimension region with looping information
908 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
909 schoenebeck 24 * @returns number of successfully read sample points
910 schoenebeck 384 * @see CreateDecompressionBuffer()
911 schoenebeck 24 */
912 schoenebeck 2912 file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
913 persson 864 DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
914 schoenebeck 2912 file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
915 schoenebeck 24 uint8_t* pDst = (uint8_t*) pBuffer;
916    
917     SetPos(pPlaybackState->position); // recover position from the last time
918    
919 persson 864 if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
920 schoenebeck 24
921 persson 864 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
922     const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
923 schoenebeck 24
924 persson 864 if (GetPos() <= loopEnd) {
925     switch (loop.LoopType) {
926 schoenebeck 24
927 persson 864 case loop_type_bidirectional: { //TODO: not tested yet!
928     do {
929     // if not endless loop check if max. number of loop cycles have been passed
930     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
931 schoenebeck 24
932 persson 864 if (!pPlaybackState->reverse) { // forward playback
933     do {
934     samplestoloopend = loopEnd - GetPos();
935     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
936     samplestoread -= readsamples;
937     totalreadsamples += readsamples;
938     if (readsamples == samplestoloopend) {
939     pPlaybackState->reverse = true;
940     break;
941     }
942     } while (samplestoread && readsamples);
943     }
944     else { // backward playback
945 schoenebeck 24
946 persson 864 // as we can only read forward from disk, we have to
947     // determine the end position within the loop first,
948     // read forward from that 'end' and finally after
949     // reading, swap all sample frames so it reflects
950     // backward playback
951 schoenebeck 24
952 schoenebeck 2912 file_offset_t swapareastart = totalreadsamples;
953     file_offset_t loopoffset = GetPos() - loop.LoopStart;
954     file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
955     file_offset_t reverseplaybackend = GetPos() - samplestoreadinloop;
956 schoenebeck 24
957 persson 864 SetPos(reverseplaybackend);
958 schoenebeck 24
959 persson 864 // read samples for backward playback
960     do {
961     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
962     samplestoreadinloop -= readsamples;
963     samplestoread -= readsamples;
964     totalreadsamples += readsamples;
965     } while (samplestoreadinloop && readsamples);
966 schoenebeck 24
967 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
968    
969     if (reverseplaybackend == loop.LoopStart) {
970     pPlaybackState->loop_cycles_left--;
971     pPlaybackState->reverse = false;
972     }
973    
974     // reverse the sample frames for backward playback
975 schoenebeck 1875 if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
976     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
977 schoenebeck 24 }
978 persson 864 } while (samplestoread && readsamples);
979     break;
980     }
981 schoenebeck 24
982 persson 864 case loop_type_backward: { // TODO: not tested yet!
983     // forward playback (not entered the loop yet)
984     if (!pPlaybackState->reverse) do {
985     samplestoloopend = loopEnd - GetPos();
986     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
987     samplestoread -= readsamples;
988     totalreadsamples += readsamples;
989     if (readsamples == samplestoloopend) {
990     pPlaybackState->reverse = true;
991     break;
992     }
993     } while (samplestoread && readsamples);
994 schoenebeck 24
995 persson 864 if (!samplestoread) break;
996 schoenebeck 24
997 persson 864 // as we can only read forward from disk, we have to
998     // determine the end position within the loop first,
999     // read forward from that 'end' and finally after
1000     // reading, swap all sample frames so it reflects
1001     // backward playback
1002 schoenebeck 24
1003 schoenebeck 2912 file_offset_t swapareastart = totalreadsamples;
1004     file_offset_t loopoffset = GetPos() - loop.LoopStart;
1005     file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1006 persson 864 : samplestoread;
1007 schoenebeck 2912 file_offset_t reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1008 schoenebeck 24
1009 persson 864 SetPos(reverseplaybackend);
1010 schoenebeck 24
1011 persson 864 // read samples for backward playback
1012     do {
1013     // if not endless loop check if max. number of loop cycles have been passed
1014     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1015     samplestoloopend = loopEnd - GetPos();
1016     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1017     samplestoreadinloop -= readsamples;
1018     samplestoread -= readsamples;
1019     totalreadsamples += readsamples;
1020     if (readsamples == samplestoloopend) {
1021     pPlaybackState->loop_cycles_left--;
1022     SetPos(loop.LoopStart);
1023     }
1024     } while (samplestoreadinloop && readsamples);
1025 schoenebeck 24
1026 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
1027 schoenebeck 24
1028 persson 864 // reverse the sample frames for backward playback
1029     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1030     break;
1031     }
1032 schoenebeck 24
1033 persson 864 default: case loop_type_normal: {
1034     do {
1035     // if not endless loop check if max. number of loop cycles have been passed
1036     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1037     samplestoloopend = loopEnd - GetPos();
1038     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1039     samplestoread -= readsamples;
1040     totalreadsamples += readsamples;
1041     if (readsamples == samplestoloopend) {
1042     pPlaybackState->loop_cycles_left--;
1043     SetPos(loop.LoopStart);
1044     }
1045     } while (samplestoread && readsamples);
1046     break;
1047     }
1048 schoenebeck 24 }
1049     }
1050     }
1051    
1052     // read on without looping
1053     if (samplestoread) do {
1054 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1055 schoenebeck 24 samplestoread -= readsamples;
1056     totalreadsamples += readsamples;
1057     } while (readsamples && samplestoread);
1058    
1059     // store current position
1060     pPlaybackState->position = GetPos();
1061    
1062     return totalreadsamples;
1063     }
1064    
1065     /**
1066 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
1067     * position into the buffer pointed by \a pBuffer and increments the
1068     * position within the sample. The sample wave stream will be
1069     * decompressed on the fly if using a compressed sample. Use this method
1070     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
1071     * thus for disk streaming.
1072     *
1073 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
1074     * have to use an external decompression buffer for <b>EACH</b>
1075     * streaming thread to avoid race conditions and crashes!
1076     *
1077 persson 902 * For 16 bit samples, the data in the buffer will be int16_t
1078     * (using native endianness). For 24 bit, the buffer will
1079     * contain three bytes per sample, little-endian.
1080     *
1081 schoenebeck 2 * @param pBuffer destination buffer
1082     * @param SampleCount number of sample points to read
1083 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
1084 schoenebeck 2 * @returns number of successfully read sample points
1085 schoenebeck 384 * @see SetPos(), CreateDecompressionBuffer()
1086 schoenebeck 2 */
1087 schoenebeck 2912 file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1088 schoenebeck 21 if (SampleCount == 0) return 0;
1089 schoenebeck 317 if (!Compressed) {
1090     if (BitDepth == 24) {
1091 persson 902 return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1092 schoenebeck 317 }
1093 persson 365 else { // 16 bit
1094     // (pCkData->Read does endian correction)
1095     return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1096     : pCkData->Read(pBuffer, SampleCount, 2);
1097     }
1098 schoenebeck 317 }
1099 persson 365 else {
1100 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
1101 persson 365 //TODO: efficiency: maybe we should test for an average compression rate
1102 schoenebeck 2912 file_offset_t assumedsize = GuessSize(SampleCount),
1103 schoenebeck 2 remainingbytes = 0, // remaining bytes in the local buffer
1104     remainingsamples = SampleCount,
1105 persson 365 copysamples, skipsamples,
1106     currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1107 schoenebeck 2 this->FrameOffset = 0;
1108    
1109 schoenebeck 384 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1110    
1111     // if decompression buffer too small, then reduce amount of samples to read
1112     if (pDecompressionBuffer->Size < assumedsize) {
1113     std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1114     SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1115     remainingsamples = SampleCount;
1116     assumedsize = GuessSize(SampleCount);
1117 schoenebeck 2 }
1118    
1119 schoenebeck 384 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1120 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
1121 persson 902 uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1122 schoenebeck 2 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1123    
1124 persson 365 while (remainingsamples && remainingbytes) {
1125 schoenebeck 2912 file_offset_t framesamples = SamplesPerFrame;
1126     file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1127 schoenebeck 2
1128 persson 365 int mode_l = *pSrc++, mode_r = 0;
1129    
1130     if (Channels == 2) {
1131     mode_r = *pSrc++;
1132     framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1133     rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1134     nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1135     if (remainingbytes < framebytes) { // last frame in sample
1136     framesamples = SamplesInLastFrame;
1137     if (mode_l == 4 && (framesamples & 1)) {
1138     rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1139     }
1140     else {
1141     rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1142     }
1143 schoenebeck 2 }
1144     }
1145 persson 365 else {
1146     framebytes = bytesPerFrame[mode_l] + 1;
1147     nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1148     if (remainingbytes < framebytes) {
1149     framesamples = SamplesInLastFrame;
1150     }
1151     }
1152 schoenebeck 2
1153     // determine how many samples in this frame to skip and read
1154 persson 365 if (currentframeoffset + remainingsamples >= framesamples) {
1155     if (currentframeoffset <= framesamples) {
1156     copysamples = framesamples - currentframeoffset;
1157     skipsamples = currentframeoffset;
1158     }
1159     else {
1160     copysamples = 0;
1161     skipsamples = framesamples;
1162     }
1163 schoenebeck 2 }
1164     else {
1165 persson 365 // This frame has enough data for pBuffer, but not
1166     // all of the frame is needed. Set file position
1167     // to start of this frame for next call to Read.
1168 schoenebeck 2 copysamples = remainingsamples;
1169 persson 365 skipsamples = currentframeoffset;
1170     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1171     this->FrameOffset = currentframeoffset + copysamples;
1172     }
1173     remainingsamples -= copysamples;
1174    
1175     if (remainingbytes > framebytes) {
1176     remainingbytes -= framebytes;
1177     if (remainingsamples == 0 &&
1178     currentframeoffset + copysamples == framesamples) {
1179     // This frame has enough data for pBuffer, and
1180     // all of the frame is needed. Set file
1181     // position to start of next frame for next
1182     // call to Read. FrameOffset is 0.
1183 schoenebeck 2 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1184     }
1185     }
1186 persson 365 else remainingbytes = 0;
1187 schoenebeck 2
1188 persson 365 currentframeoffset -= skipsamples;
1189 schoenebeck 2
1190 persson 365 if (copysamples == 0) {
1191     // skip this frame
1192     pSrc += framebytes - Channels;
1193     }
1194     else {
1195     const unsigned char* const param_l = pSrc;
1196     if (BitDepth == 24) {
1197     if (mode_l != 2) pSrc += 12;
1198 schoenebeck 2
1199 persson 365 if (Channels == 2) { // Stereo
1200     const unsigned char* const param_r = pSrc;
1201     if (mode_r != 2) pSrc += 12;
1202    
1203 persson 902 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1204 persson 437 skipsamples, copysamples, TruncatedBits);
1205 persson 902 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1206 persson 437 skipsamples, copysamples, TruncatedBits);
1207 persson 902 pDst24 += copysamples * 6;
1208 schoenebeck 2 }
1209 persson 365 else { // Mono
1210 persson 902 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1211 persson 437 skipsamples, copysamples, TruncatedBits);
1212 persson 902 pDst24 += copysamples * 3;
1213 schoenebeck 2 }
1214 persson 365 }
1215     else { // 16 bit
1216     if (mode_l) pSrc += 4;
1217 schoenebeck 2
1218 persson 365 int step;
1219     if (Channels == 2) { // Stereo
1220     const unsigned char* const param_r = pSrc;
1221     if (mode_r) pSrc += 4;
1222    
1223     step = (2 - mode_l) + (2 - mode_r);
1224 persson 372 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1225     Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1226 persson 365 skipsamples, copysamples);
1227     pDst += copysamples << 1;
1228 schoenebeck 2 }
1229 persson 365 else { // Mono
1230     step = 2 - mode_l;
1231 persson 372 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1232 persson 365 pDst += copysamples;
1233 schoenebeck 2 }
1234 persson 365 }
1235     pSrc += nextFrameOffset;
1236     }
1237 schoenebeck 2
1238 persson 365 // reload from disk to local buffer if needed
1239     if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1240     assumedsize = GuessSize(remainingsamples);
1241     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1242     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1243 schoenebeck 384 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1244     pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1245 schoenebeck 2 }
1246 persson 365 } // while
1247    
1248 schoenebeck 2 this->SamplePos += (SampleCount - remainingsamples);
1249 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1250 schoenebeck 2 return (SampleCount - remainingsamples);
1251     }
1252     }
1253    
1254 schoenebeck 809 /** @brief Write sample wave data.
1255     *
1256     * Writes \a SampleCount number of sample points from the buffer pointed
1257     * by \a pBuffer and increments the position within the sample. Use this
1258     * method to directly write the sample data to disk, i.e. if you don't
1259     * want or cannot load the whole sample data into RAM.
1260     *
1261     * You have to Resize() the sample to the desired size and call
1262     * File::Save() <b>before</b> using Write().
1263     *
1264     * Note: there is currently no support for writing compressed samples.
1265     *
1266 persson 1264 * For 16 bit samples, the data in the source buffer should be
1267     * int16_t (using native endianness). For 24 bit, the buffer
1268     * should contain three bytes per sample, little-endian.
1269     *
1270 schoenebeck 809 * @param pBuffer - source buffer
1271     * @param SampleCount - number of sample points to write
1272     * @throws DLS::Exception if current sample size is too small
1273     * @throws gig::Exception if sample is compressed
1274     * @see DLS::LoadSampleData()
1275     */
1276 schoenebeck 2912 file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1277 schoenebeck 809 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1278 persson 1207
1279     // if this is the first write in this sample, reset the
1280     // checksum calculator
1281 persson 1199 if (pCkData->GetPos() == 0) {
1282 schoenebeck 1381 __resetCRC(crc);
1283 persson 1199 }
1284 persson 1264 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1285 schoenebeck 2912 file_offset_t res;
1286 persson 1264 if (BitDepth == 24) {
1287     res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1288     } else { // 16 bit
1289     res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1290     : pCkData->Write(pBuffer, SampleCount, 2);
1291     }
1292 schoenebeck 1381 __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1293 persson 1199
1294 persson 1207 // if this is the last write, update the checksum chunk in the
1295     // file
1296 persson 1199 if (pCkData->GetPos() == pCkData->GetSize()) {
1297     File* pFile = static_cast<File*>(GetParent());
1298 schoenebeck 1381 pFile->SetSampleChecksum(this, __encodeCRC(crc));
1299 persson 1199 }
1300     return res;
1301 schoenebeck 809 }
1302    
1303 schoenebeck 384 /**
1304     * Allocates a decompression buffer for streaming (compressed) samples
1305     * with Sample::Read(). If you are using more than one streaming thread
1306     * in your application you <b>HAVE</b> to create a decompression buffer
1307     * for <b>EACH</b> of your streaming threads and provide it with the
1308     * Sample::Read() call in order to avoid race conditions and crashes.
1309     *
1310     * You should free the memory occupied by the allocated buffer(s) once
1311     * you don't need one of your streaming threads anymore by calling
1312     * DestroyDecompressionBuffer().
1313     *
1314     * @param MaxReadSize - the maximum size (in sample points) you ever
1315     * expect to read with one Read() call
1316     * @returns allocated decompression buffer
1317     * @see DestroyDecompressionBuffer()
1318     */
1319 schoenebeck 2912 buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1320 schoenebeck 384 buffer_t result;
1321     const double worstCaseHeaderOverhead =
1322     (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1323 schoenebeck 2912 result.Size = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1324 schoenebeck 384 result.pStart = new int8_t[result.Size];
1325     result.NullExtensionSize = 0;
1326     return result;
1327     }
1328    
1329     /**
1330     * Free decompression buffer, previously created with
1331     * CreateDecompressionBuffer().
1332     *
1333     * @param DecompressionBuffer - previously allocated decompression
1334     * buffer to free
1335     */
1336     void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1337     if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1338     delete[] (int8_t*) DecompressionBuffer.pStart;
1339     DecompressionBuffer.pStart = NULL;
1340     DecompressionBuffer.Size = 0;
1341     DecompressionBuffer.NullExtensionSize = 0;
1342     }
1343     }
1344    
1345 schoenebeck 930 /**
1346     * Returns pointer to the Group this Sample belongs to. In the .gig
1347     * format a sample always belongs to one group. If it wasn't explicitly
1348     * assigned to a certain group, it will be automatically assigned to a
1349     * default group.
1350     *
1351     * @returns Sample's Group (never NULL)
1352     */
1353     Group* Sample::GetGroup() const {
1354     return pGroup;
1355     }
1356    
1357 schoenebeck 2985 /**
1358 schoenebeck 2989 * Returns the CRC-32 checksum of the sample's raw wave form data at the
1359     * time when this sample's wave form data was modified for the last time
1360     * by calling Write(). This checksum only covers the raw wave form data,
1361     * not any meta informations like i.e. bit depth or loop points. Since
1362     * this method just returns the checksum stored for this sample i.e. when
1363     * the gig file was loaded, this method returns immediately. So it does no
1364     * recalcuation of the checksum with the currently available sample wave
1365     * form data.
1366     *
1367     * @see VerifyWaveData()
1368     */
1369     uint32_t Sample::GetWaveDataCRC32Checksum() {
1370     return crc;
1371     }
1372    
1373     /**
1374 schoenebeck 2985 * Checks the integrity of this sample's raw audio wave data. Whenever a
1375     * Sample's raw wave data is intentionally modified (i.e. by calling
1376     * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1377     * is calculated and stored/updated for this sample, along to the sample's
1378     * meta informations.
1379     *
1380     * Now by calling this method the current raw audio wave data is checked
1381     * against the already stored CRC32 check sum in order to check whether the
1382     * sample data had been damaged unintentionally for some reason. Since by
1383     * calling this method always the entire raw audio wave data has to be
1384     * read, verifying all samples this way may take a long time accordingly.
1385     * And that's also the reason why the sample integrity is not checked by
1386     * default whenever a gig file is loaded. So this method must be called
1387     * explicitly to fulfill this task.
1388     *
1389 schoenebeck 2989 * @param pActually - (optional) if provided, will be set to the actually
1390     * calculated checksum of the current raw wave form data,
1391     * you can get the expected checksum instead by calling
1392     * GetWaveDataCRC32Checksum()
1393 schoenebeck 2985 * @returns true if sample is OK or false if the sample is damaged
1394     * @throws Exception if no checksum had been stored to disk for this
1395     * sample yet, or on I/O issues
1396 schoenebeck 2989 * @see GetWaveDataCRC32Checksum()
1397 schoenebeck 2985 */
1398 schoenebeck 2989 bool Sample::VerifyWaveData(uint32_t* pActually) {
1399 schoenebeck 3053 //File* pFile = static_cast<File*>(GetParent());
1400 schoenebeck 2985 uint32_t crc = CalculateWaveDataChecksum();
1401 schoenebeck 2989 if (pActually) *pActually = crc;
1402     return crc == this->crc;
1403 schoenebeck 2985 }
1404    
1405     uint32_t Sample::CalculateWaveDataChecksum() {
1406     const size_t sz = 20*1024; // 20kB buffer size
1407     std::vector<uint8_t> buffer(sz);
1408     buffer.resize(sz);
1409    
1410     const size_t n = sz / FrameSize;
1411     SetPos(0);
1412     uint32_t crc = 0;
1413     __resetCRC(crc);
1414     while (true) {
1415     file_offset_t nRead = Read(&buffer[0], n);
1416     if (nRead <= 0) break;
1417     __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1418     }
1419     __encodeCRC(crc);
1420     return crc;
1421     }
1422    
1423 schoenebeck 2 Sample::~Sample() {
1424     Instances--;
1425 schoenebeck 384 if (!Instances && InternalDecompressionBuffer.Size) {
1426     delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1427     InternalDecompressionBuffer.pStart = NULL;
1428     InternalDecompressionBuffer.Size = 0;
1429 schoenebeck 355 }
1430 schoenebeck 2 if (FrameTable) delete[] FrameTable;
1431     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1432     }
1433    
1434    
1435    
1436     // *************** DimensionRegion ***************
1437     // *
1438    
1439 schoenebeck 2922 size_t DimensionRegion::Instances = 0;
1440 schoenebeck 16 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1441    
1442 schoenebeck 1316 DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1443 schoenebeck 16 Instances++;
1444    
1445 schoenebeck 823 pSample = NULL;
1446 schoenebeck 1316 pRegion = pParent;
1447 schoenebeck 823
1448 persson 1247 if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1449     else memset(&Crossfade, 0, 4);
1450    
1451 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1452 schoenebeck 2
1453     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1454 schoenebeck 809 if (_3ewa) { // if '3ewa' chunk exists
1455 persson 918 _3ewa->ReadInt32(); // unknown, always == chunk size ?
1456 schoenebeck 809 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1457     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1458     _3ewa->ReadInt16(); // unknown
1459     LFO1InternalDepth = _3ewa->ReadUint16();
1460     _3ewa->ReadInt16(); // unknown
1461     LFO3InternalDepth = _3ewa->ReadInt16();
1462     _3ewa->ReadInt16(); // unknown
1463     LFO1ControlDepth = _3ewa->ReadUint16();
1464     _3ewa->ReadInt16(); // unknown
1465     LFO3ControlDepth = _3ewa->ReadInt16();
1466     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1467     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1468     _3ewa->ReadInt16(); // unknown
1469     EG1Sustain = _3ewa->ReadUint16();
1470     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1471     EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1472     uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1473     EG1ControllerInvert = eg1ctrloptions & 0x01;
1474     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1475     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1476     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1477     EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1478     uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1479     EG2ControllerInvert = eg2ctrloptions & 0x01;
1480     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1481     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1482     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1483     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1484     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1485     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1486     _3ewa->ReadInt16(); // unknown
1487     EG2Sustain = _3ewa->ReadUint16();
1488     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1489     _3ewa->ReadInt16(); // unknown
1490     LFO2ControlDepth = _3ewa->ReadUint16();
1491     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1492     _3ewa->ReadInt16(); // unknown
1493     LFO2InternalDepth = _3ewa->ReadUint16();
1494     int32_t eg1decay2 = _3ewa->ReadInt32();
1495     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1496     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1497     _3ewa->ReadInt16(); // unknown
1498     EG1PreAttack = _3ewa->ReadUint16();
1499     int32_t eg2decay2 = _3ewa->ReadInt32();
1500     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1501     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1502     _3ewa->ReadInt16(); // unknown
1503     EG2PreAttack = _3ewa->ReadUint16();
1504     uint8_t velocityresponse = _3ewa->ReadUint8();
1505     if (velocityresponse < 5) {
1506     VelocityResponseCurve = curve_type_nonlinear;
1507     VelocityResponseDepth = velocityresponse;
1508     } else if (velocityresponse < 10) {
1509     VelocityResponseCurve = curve_type_linear;
1510     VelocityResponseDepth = velocityresponse - 5;
1511     } else if (velocityresponse < 15) {
1512     VelocityResponseCurve = curve_type_special;
1513     VelocityResponseDepth = velocityresponse - 10;
1514     } else {
1515     VelocityResponseCurve = curve_type_unknown;
1516     VelocityResponseDepth = 0;
1517     }
1518     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1519     if (releasevelocityresponse < 5) {
1520     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1521     ReleaseVelocityResponseDepth = releasevelocityresponse;
1522     } else if (releasevelocityresponse < 10) {
1523     ReleaseVelocityResponseCurve = curve_type_linear;
1524     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1525     } else if (releasevelocityresponse < 15) {
1526     ReleaseVelocityResponseCurve = curve_type_special;
1527     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1528     } else {
1529     ReleaseVelocityResponseCurve = curve_type_unknown;
1530     ReleaseVelocityResponseDepth = 0;
1531     }
1532     VelocityResponseCurveScaling = _3ewa->ReadUint8();
1533     AttenuationControllerThreshold = _3ewa->ReadInt8();
1534     _3ewa->ReadInt32(); // unknown
1535     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1536     _3ewa->ReadInt16(); // unknown
1537     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1538     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1539     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1540     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1541     else DimensionBypass = dim_bypass_ctrl_none;
1542     uint8_t pan = _3ewa->ReadUint8();
1543     Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1544     SelfMask = _3ewa->ReadInt8() & 0x01;
1545     _3ewa->ReadInt8(); // unknown
1546     uint8_t lfo3ctrl = _3ewa->ReadUint8();
1547     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1548     LFO3Sync = lfo3ctrl & 0x20; // bit 5
1549     InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1550     AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1551     uint8_t lfo2ctrl = _3ewa->ReadUint8();
1552     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1553     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1554     LFO2Sync = lfo2ctrl & 0x20; // bit 5
1555     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1556     uint8_t lfo1ctrl = _3ewa->ReadUint8();
1557     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1558     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1559     LFO1Sync = lfo1ctrl & 0x40; // bit 6
1560     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1561     : vcf_res_ctrl_none;
1562     uint16_t eg3depth = _3ewa->ReadUint16();
1563     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1564 persson 2402 : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1565 schoenebeck 809 _3ewa->ReadInt16(); // unknown
1566     ChannelOffset = _3ewa->ReadUint8() / 4;
1567     uint8_t regoptions = _3ewa->ReadUint8();
1568     MSDecode = regoptions & 0x01; // bit 0
1569     SustainDefeat = regoptions & 0x02; // bit 1
1570     _3ewa->ReadInt16(); // unknown
1571     VelocityUpperLimit = _3ewa->ReadInt8();
1572     _3ewa->ReadInt8(); // unknown
1573     _3ewa->ReadInt16(); // unknown
1574     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1575     _3ewa->ReadInt8(); // unknown
1576     _3ewa->ReadInt8(); // unknown
1577     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1578     uint8_t vcfcutoff = _3ewa->ReadUint8();
1579     VCFEnabled = vcfcutoff & 0x80; // bit 7
1580     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1581     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1582     uint8_t vcfvelscale = _3ewa->ReadUint8();
1583     VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1584     VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1585     _3ewa->ReadInt8(); // unknown
1586     uint8_t vcfresonance = _3ewa->ReadUint8();
1587     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1588     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1589     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1590     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1591     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1592     uint8_t vcfvelocity = _3ewa->ReadUint8();
1593     VCFVelocityDynamicRange = vcfvelocity % 5;
1594     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1595     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1596     if (VCFType == vcf_type_lowpass) {
1597     if (lfo3ctrl & 0x40) // bit 6
1598     VCFType = vcf_type_lowpassturbo;
1599     }
1600 persson 1070 if (_3ewa->RemainingBytes() >= 8) {
1601     _3ewa->Read(DimensionUpperLimits, 1, 8);
1602     } else {
1603     memset(DimensionUpperLimits, 0, 8);
1604     }
1605 schoenebeck 809 } else { // '3ewa' chunk does not exist yet
1606     // use default values
1607     LFO3Frequency = 1.0;
1608     EG3Attack = 0.0;
1609     LFO1InternalDepth = 0;
1610     LFO3InternalDepth = 0;
1611     LFO1ControlDepth = 0;
1612     LFO3ControlDepth = 0;
1613     EG1Attack = 0.0;
1614 persson 1218 EG1Decay1 = 0.005;
1615     EG1Sustain = 1000;
1616     EG1Release = 0.3;
1617 schoenebeck 809 EG1Controller.type = eg1_ctrl_t::type_none;
1618     EG1Controller.controller_number = 0;
1619     EG1ControllerInvert = false;
1620     EG1ControllerAttackInfluence = 0;
1621     EG1ControllerDecayInfluence = 0;
1622     EG1ControllerReleaseInfluence = 0;
1623     EG2Controller.type = eg2_ctrl_t::type_none;
1624     EG2Controller.controller_number = 0;
1625     EG2ControllerInvert = false;
1626     EG2ControllerAttackInfluence = 0;
1627     EG2ControllerDecayInfluence = 0;
1628     EG2ControllerReleaseInfluence = 0;
1629     LFO1Frequency = 1.0;
1630     EG2Attack = 0.0;
1631 persson 1218 EG2Decay1 = 0.005;
1632     EG2Sustain = 1000;
1633 schoenebeck 2990 EG2Release = 60;
1634 schoenebeck 809 LFO2ControlDepth = 0;
1635     LFO2Frequency = 1.0;
1636     LFO2InternalDepth = 0;
1637     EG1Decay2 = 0.0;
1638 persson 1218 EG1InfiniteSustain = true;
1639     EG1PreAttack = 0;
1640 schoenebeck 809 EG2Decay2 = 0.0;
1641 persson 1218 EG2InfiniteSustain = true;
1642     EG2PreAttack = 0;
1643 schoenebeck 809 VelocityResponseCurve = curve_type_nonlinear;
1644     VelocityResponseDepth = 3;
1645     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1646     ReleaseVelocityResponseDepth = 3;
1647     VelocityResponseCurveScaling = 32;
1648     AttenuationControllerThreshold = 0;
1649     SampleStartOffset = 0;
1650     PitchTrack = true;
1651     DimensionBypass = dim_bypass_ctrl_none;
1652     Pan = 0;
1653     SelfMask = true;
1654     LFO3Controller = lfo3_ctrl_modwheel;
1655     LFO3Sync = false;
1656     InvertAttenuationController = false;
1657     AttenuationController.type = attenuation_ctrl_t::type_none;
1658     AttenuationController.controller_number = 0;
1659     LFO2Controller = lfo2_ctrl_internal;
1660     LFO2FlipPhase = false;
1661     LFO2Sync = false;
1662     LFO1Controller = lfo1_ctrl_internal;
1663     LFO1FlipPhase = false;
1664     LFO1Sync = false;
1665     VCFResonanceController = vcf_res_ctrl_none;
1666     EG3Depth = 0;
1667     ChannelOffset = 0;
1668     MSDecode = false;
1669     SustainDefeat = false;
1670     VelocityUpperLimit = 0;
1671     ReleaseTriggerDecay = 0;
1672     EG1Hold = false;
1673     VCFEnabled = false;
1674     VCFCutoff = 0;
1675     VCFCutoffController = vcf_cutoff_ctrl_none;
1676     VCFCutoffControllerInvert = false;
1677     VCFVelocityScale = 0;
1678     VCFResonance = 0;
1679     VCFResonanceDynamic = false;
1680     VCFKeyboardTracking = false;
1681     VCFKeyboardTrackingBreakpoint = 0;
1682     VCFVelocityDynamicRange = 0x04;
1683     VCFVelocityCurve = curve_type_linear;
1684     VCFType = vcf_type_lowpass;
1685 persson 1247 memset(DimensionUpperLimits, 127, 8);
1686 schoenebeck 2 }
1687 schoenebeck 16
1688 persson 613 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1689     VelocityResponseDepth,
1690     VelocityResponseCurveScaling);
1691    
1692 schoenebeck 1358 pVelocityReleaseTable = GetReleaseVelocityTable(
1693     ReleaseVelocityResponseCurve,
1694     ReleaseVelocityResponseDepth
1695     );
1696 persson 613
1697 schoenebeck 1358 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1698     VCFVelocityDynamicRange,
1699     VCFVelocityScale,
1700     VCFCutoffController);
1701 persson 613
1702     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1703 persson 858 VelocityTable = 0;
1704 persson 613 }
1705    
1706 persson 1301 /*
1707     * Constructs a DimensionRegion by copying all parameters from
1708     * another DimensionRegion
1709     */
1710     DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1711     Instances++;
1712 schoenebeck 2394 //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1713 persson 1301 *this = src; // default memberwise shallow copy of all parameters
1714     pParentList = _3ewl; // restore the chunk pointer
1715    
1716     // deep copy of owned structures
1717     if (src.VelocityTable) {
1718     VelocityTable = new uint8_t[128];
1719     for (int k = 0 ; k < 128 ; k++)
1720     VelocityTable[k] = src.VelocityTable[k];
1721     }
1722     if (src.pSampleLoops) {
1723     pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1724     for (int k = 0 ; k < src.SampleLoops ; k++)
1725     pSampleLoops[k] = src.pSampleLoops[k];
1726     }
1727     }
1728 schoenebeck 2394
1729     /**
1730     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1731     * and assign it to this object.
1732     *
1733     * Note that all sample pointers referenced by @a orig are simply copied as
1734     * memory address. Thus the respective samples are shared, not duplicated!
1735     *
1736     * @param orig - original DimensionRegion object to be copied from
1737     */
1738     void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1739 schoenebeck 2482 CopyAssign(orig, NULL);
1740     }
1741    
1742     /**
1743     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1744     * and assign it to this object.
1745     *
1746     * @param orig - original DimensionRegion object to be copied from
1747     * @param mSamples - crosslink map between the foreign file's samples and
1748     * this file's samples
1749     */
1750     void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1751 schoenebeck 2394 // delete all allocated data first
1752     if (VelocityTable) delete [] VelocityTable;
1753     if (pSampleLoops) delete [] pSampleLoops;
1754    
1755     // backup parent list pointer
1756     RIFF::List* p = pParentList;
1757    
1758 schoenebeck 2482 gig::Sample* pOriginalSample = pSample;
1759     gig::Region* pOriginalRegion = pRegion;
1760    
1761 schoenebeck 2394 //NOTE: copy code copied from assignment constructor above, see comment there as well
1762    
1763     *this = *orig; // default memberwise shallow copy of all parameters
1764 schoenebeck 2547
1765     // restore members that shall not be altered
1766 schoenebeck 2394 pParentList = p; // restore the chunk pointer
1767 schoenebeck 2547 pRegion = pOriginalRegion;
1768 schoenebeck 2482
1769 schoenebeck 2547 // only take the raw sample reference reference if the
1770 schoenebeck 2482 // two DimensionRegion objects are part of the same file
1771     if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1772     pSample = pOriginalSample;
1773     }
1774    
1775     if (mSamples && mSamples->count(orig->pSample)) {
1776     pSample = mSamples->find(orig->pSample)->second;
1777     }
1778 persson 1301
1779 schoenebeck 2394 // deep copy of owned structures
1780     if (orig->VelocityTable) {
1781     VelocityTable = new uint8_t[128];
1782     for (int k = 0 ; k < 128 ; k++)
1783     VelocityTable[k] = orig->VelocityTable[k];
1784     }
1785     if (orig->pSampleLoops) {
1786     pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1787     for (int k = 0 ; k < orig->SampleLoops ; k++)
1788     pSampleLoops[k] = orig->pSampleLoops[k];
1789     }
1790     }
1791    
1792 schoenebeck 809 /**
1793 schoenebeck 1358 * Updates the respective member variable and updates @c SampleAttenuation
1794     * which depends on this value.
1795     */
1796     void DimensionRegion::SetGain(int32_t gain) {
1797     DLS::Sampler::SetGain(gain);
1798     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1799     }
1800    
1801     /**
1802 schoenebeck 809 * Apply dimension region settings to the respective RIFF chunks. You
1803     * have to call File::Save() to make changes persistent.
1804     *
1805     * Usually there is absolutely no need to call this method explicitly.
1806     * It will be called automatically when File::Save() was called.
1807 schoenebeck 2682 *
1808     * @param pProgress - callback function for progress notification
1809 schoenebeck 809 */
1810 schoenebeck 2682 void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1811 schoenebeck 809 // first update base class's chunk
1812 schoenebeck 2682 DLS::Sampler::UpdateChunks(pProgress);
1813 schoenebeck 809
1814 persson 1247 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1815     uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1816     pData[12] = Crossfade.in_start;
1817     pData[13] = Crossfade.in_end;
1818     pData[14] = Crossfade.out_start;
1819     pData[15] = Crossfade.out_end;
1820    
1821 schoenebeck 809 // make sure '3ewa' chunk exists
1822     RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1823 persson 1317 if (!_3ewa) {
1824     File* pFile = (File*) GetParent()->GetParent()->GetParent();
1825     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1826     _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1827 persson 1264 }
1828 persson 1247 pData = (uint8_t*) _3ewa->LoadChunkData();
1829 schoenebeck 809
1830     // update '3ewa' chunk with DimensionRegion's current settings
1831    
1832 schoenebeck 3053 const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1833 persson 1179 store32(&pData[0], chunksize); // unknown, always chunk size?
1834 schoenebeck 809
1835     const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1836 persson 1179 store32(&pData[4], lfo3freq);
1837 schoenebeck 809
1838     const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1839 persson 1179 store32(&pData[8], eg3attack);
1840 schoenebeck 809
1841     // next 2 bytes unknown
1842    
1843 persson 1179 store16(&pData[14], LFO1InternalDepth);
1844 schoenebeck 809
1845     // next 2 bytes unknown
1846    
1847 persson 1179 store16(&pData[18], LFO3InternalDepth);
1848 schoenebeck 809
1849     // next 2 bytes unknown
1850    
1851 persson 1179 store16(&pData[22], LFO1ControlDepth);
1852 schoenebeck 809
1853     // next 2 bytes unknown
1854    
1855 persson 1179 store16(&pData[26], LFO3ControlDepth);
1856 schoenebeck 809
1857     const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1858 persson 1179 store32(&pData[28], eg1attack);
1859 schoenebeck 809
1860     const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1861 persson 1179 store32(&pData[32], eg1decay1);
1862 schoenebeck 809
1863     // next 2 bytes unknown
1864    
1865 persson 1179 store16(&pData[38], EG1Sustain);
1866 schoenebeck 809
1867     const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1868 persson 1179 store32(&pData[40], eg1release);
1869 schoenebeck 809
1870     const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1871 persson 1179 pData[44] = eg1ctl;
1872 schoenebeck 809
1873     const uint8_t eg1ctrloptions =
1874 persson 1266 (EG1ControllerInvert ? 0x01 : 0x00) |
1875 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1876     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1877     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1878 persson 1179 pData[45] = eg1ctrloptions;
1879 schoenebeck 809
1880     const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1881 persson 1179 pData[46] = eg2ctl;
1882 schoenebeck 809
1883     const uint8_t eg2ctrloptions =
1884 persson 1266 (EG2ControllerInvert ? 0x01 : 0x00) |
1885 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1886     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1887     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1888 persson 1179 pData[47] = eg2ctrloptions;
1889 schoenebeck 809
1890     const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1891 persson 1179 store32(&pData[48], lfo1freq);
1892 schoenebeck 809
1893     const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1894 persson 1179 store32(&pData[52], eg2attack);
1895 schoenebeck 809
1896     const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1897 persson 1179 store32(&pData[56], eg2decay1);
1898 schoenebeck 809
1899     // next 2 bytes unknown
1900    
1901 persson 1179 store16(&pData[62], EG2Sustain);
1902 schoenebeck 809
1903     const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1904 persson 1179 store32(&pData[64], eg2release);
1905 schoenebeck 809
1906     // next 2 bytes unknown
1907    
1908 persson 1179 store16(&pData[70], LFO2ControlDepth);
1909 schoenebeck 809
1910     const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1911 persson 1179 store32(&pData[72], lfo2freq);
1912 schoenebeck 809
1913     // next 2 bytes unknown
1914    
1915 persson 1179 store16(&pData[78], LFO2InternalDepth);
1916 schoenebeck 809
1917     const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1918 persson 1179 store32(&pData[80], eg1decay2);
1919 schoenebeck 809
1920     // next 2 bytes unknown
1921    
1922 persson 1179 store16(&pData[86], EG1PreAttack);
1923 schoenebeck 809
1924     const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1925 persson 1179 store32(&pData[88], eg2decay2);
1926 schoenebeck 809
1927     // next 2 bytes unknown
1928    
1929 persson 1179 store16(&pData[94], EG2PreAttack);
1930 schoenebeck 809
1931     {
1932     if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1933     uint8_t velocityresponse = VelocityResponseDepth;
1934     switch (VelocityResponseCurve) {
1935     case curve_type_nonlinear:
1936     break;
1937     case curve_type_linear:
1938     velocityresponse += 5;
1939     break;
1940     case curve_type_special:
1941     velocityresponse += 10;
1942     break;
1943     case curve_type_unknown:
1944     default:
1945     throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1946     }
1947 persson 1179 pData[96] = velocityresponse;
1948 schoenebeck 809 }
1949    
1950     {
1951     if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1952     uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1953     switch (ReleaseVelocityResponseCurve) {
1954     case curve_type_nonlinear:
1955     break;
1956     case curve_type_linear:
1957     releasevelocityresponse += 5;
1958     break;
1959     case curve_type_special:
1960     releasevelocityresponse += 10;
1961     break;
1962     case curve_type_unknown:
1963     default:
1964     throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1965     }
1966 persson 1179 pData[97] = releasevelocityresponse;
1967 schoenebeck 809 }
1968    
1969 persson 1179 pData[98] = VelocityResponseCurveScaling;
1970 schoenebeck 809
1971 persson 1179 pData[99] = AttenuationControllerThreshold;
1972 schoenebeck 809
1973     // next 4 bytes unknown
1974    
1975 persson 1179 store16(&pData[104], SampleStartOffset);
1976 schoenebeck 809
1977     // next 2 bytes unknown
1978    
1979     {
1980     uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1981     switch (DimensionBypass) {
1982     case dim_bypass_ctrl_94:
1983     pitchTrackDimensionBypass |= 0x10;
1984     break;
1985     case dim_bypass_ctrl_95:
1986     pitchTrackDimensionBypass |= 0x20;
1987     break;
1988     case dim_bypass_ctrl_none:
1989     //FIXME: should we set anything here?
1990     break;
1991     default:
1992     throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1993     }
1994 persson 1179 pData[108] = pitchTrackDimensionBypass;
1995 schoenebeck 809 }
1996    
1997     const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1998 persson 1179 pData[109] = pan;
1999 schoenebeck 809
2000     const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
2001 persson 1179 pData[110] = selfmask;
2002 schoenebeck 809
2003     // next byte unknown
2004    
2005     {
2006     uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
2007     if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
2008     if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
2009     if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
2010 persson 1179 pData[112] = lfo3ctrl;
2011 schoenebeck 809 }
2012    
2013     const uint8_t attenctl = EncodeLeverageController(AttenuationController);
2014 persson 1179 pData[113] = attenctl;
2015 schoenebeck 809
2016     {
2017     uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
2018     if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
2019     if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
2020     if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
2021 persson 1179 pData[114] = lfo2ctrl;
2022 schoenebeck 809 }
2023    
2024     {
2025     uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
2026     if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
2027     if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
2028     if (VCFResonanceController != vcf_res_ctrl_none)
2029     lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
2030 persson 1179 pData[115] = lfo1ctrl;
2031 schoenebeck 809 }
2032    
2033     const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2034 persson 2402 : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2035 persson 1869 store16(&pData[116], eg3depth);
2036 schoenebeck 809
2037     // next 2 bytes unknown
2038    
2039     const uint8_t channeloffset = ChannelOffset * 4;
2040 persson 1179 pData[120] = channeloffset;
2041 schoenebeck 809
2042     {
2043     uint8_t regoptions = 0;
2044     if (MSDecode) regoptions |= 0x01; // bit 0
2045     if (SustainDefeat) regoptions |= 0x02; // bit 1
2046 persson 1179 pData[121] = regoptions;
2047 schoenebeck 809 }
2048    
2049     // next 2 bytes unknown
2050    
2051 persson 1179 pData[124] = VelocityUpperLimit;
2052 schoenebeck 809
2053     // next 3 bytes unknown
2054    
2055 persson 1179 pData[128] = ReleaseTriggerDecay;
2056 schoenebeck 809
2057     // next 2 bytes unknown
2058    
2059     const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2060 persson 1179 pData[131] = eg1hold;
2061 schoenebeck 809
2062 persson 1266 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2063 persson 918 (VCFCutoff & 0x7f); /* lower 7 bits */
2064 persson 1179 pData[132] = vcfcutoff;
2065 schoenebeck 809
2066 persson 1179 pData[133] = VCFCutoffController;
2067 schoenebeck 809
2068 persson 1266 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2069 persson 918 (VCFVelocityScale & 0x7f); /* lower 7 bits */
2070 persson 1179 pData[134] = vcfvelscale;
2071 schoenebeck 809
2072     // next byte unknown
2073    
2074 persson 1266 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2075 persson 918 (VCFResonance & 0x7f); /* lower 7 bits */
2076 persson 1179 pData[136] = vcfresonance;
2077 schoenebeck 809
2078 persson 1266 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2079 persson 918 (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2080 persson 1179 pData[137] = vcfbreakpoint;
2081 schoenebeck 809
2082 persson 2152 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2083 schoenebeck 809 VCFVelocityCurve * 5;
2084 persson 1179 pData[138] = vcfvelocity;
2085 schoenebeck 809
2086     const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2087 persson 1179 pData[139] = vcftype;
2088 persson 1070
2089     if (chunksize >= 148) {
2090     memcpy(&pData[140], DimensionUpperLimits, 8);
2091     }
2092 schoenebeck 809 }
2093    
2094 schoenebeck 1358 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2095     curve_type_t curveType = releaseVelocityResponseCurve;
2096     uint8_t depth = releaseVelocityResponseDepth;
2097     // this models a strange behaviour or bug in GSt: two of the
2098     // velocity response curves for release time are not used even
2099     // if specified, instead another curve is chosen.
2100     if ((curveType == curve_type_nonlinear && depth == 0) ||
2101     (curveType == curve_type_special && depth == 4)) {
2102     curveType = curve_type_nonlinear;
2103     depth = 3;
2104     }
2105     return GetVelocityTable(curveType, depth, 0);
2106     }
2107    
2108     double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2109     uint8_t vcfVelocityDynamicRange,
2110     uint8_t vcfVelocityScale,
2111     vcf_cutoff_ctrl_t vcfCutoffController)
2112     {
2113     curve_type_t curveType = vcfVelocityCurve;
2114     uint8_t depth = vcfVelocityDynamicRange;
2115     // even stranger GSt: two of the velocity response curves for
2116     // filter cutoff are not used, instead another special curve
2117     // is chosen. This curve is not used anywhere else.
2118     if ((curveType == curve_type_nonlinear && depth == 0) ||
2119     (curveType == curve_type_special && depth == 4)) {
2120     curveType = curve_type_special;
2121     depth = 5;
2122     }
2123     return GetVelocityTable(curveType, depth,
2124     (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2125     ? vcfVelocityScale : 0);
2126     }
2127    
2128 persson 613 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2129     double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2130     {
2131     double* table;
2132     uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2133 schoenebeck 16 if (pVelocityTables->count(tableKey)) { // if key exists
2134 persson 613 table = (*pVelocityTables)[tableKey];
2135 schoenebeck 16 }
2136     else {
2137 persson 613 table = CreateVelocityTable(curveType, depth, scaling);
2138     (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2139 schoenebeck 16 }
2140 persson 613 return table;
2141 schoenebeck 2 }
2142 schoenebeck 55
2143 schoenebeck 1316 Region* DimensionRegion::GetParent() const {
2144     return pRegion;
2145     }
2146    
2147 schoenebeck 2540 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2148     // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2149     // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2150     //#pragma GCC diagnostic push
2151     //#pragma GCC diagnostic error "-Wswitch"
2152    
2153 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2154     leverage_ctrl_t decodedcontroller;
2155     switch (EncodedController) {
2156     // special controller
2157     case _lev_ctrl_none:
2158     decodedcontroller.type = leverage_ctrl_t::type_none;
2159     decodedcontroller.controller_number = 0;
2160     break;
2161     case _lev_ctrl_velocity:
2162     decodedcontroller.type = leverage_ctrl_t::type_velocity;
2163     decodedcontroller.controller_number = 0;
2164     break;
2165     case _lev_ctrl_channelaftertouch:
2166     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2167     decodedcontroller.controller_number = 0;
2168     break;
2169 schoenebeck 55
2170 schoenebeck 36 // ordinary MIDI control change controller
2171     case _lev_ctrl_modwheel:
2172     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2173     decodedcontroller.controller_number = 1;
2174     break;
2175     case _lev_ctrl_breath:
2176     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2177     decodedcontroller.controller_number = 2;
2178     break;
2179     case _lev_ctrl_foot:
2180     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2181     decodedcontroller.controller_number = 4;
2182     break;
2183     case _lev_ctrl_effect1:
2184     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2185     decodedcontroller.controller_number = 12;
2186     break;
2187     case _lev_ctrl_effect2:
2188     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2189     decodedcontroller.controller_number = 13;
2190     break;
2191     case _lev_ctrl_genpurpose1:
2192     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2193     decodedcontroller.controller_number = 16;
2194     break;
2195     case _lev_ctrl_genpurpose2:
2196     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2197     decodedcontroller.controller_number = 17;
2198     break;
2199     case _lev_ctrl_genpurpose3:
2200     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2201     decodedcontroller.controller_number = 18;
2202     break;
2203     case _lev_ctrl_genpurpose4:
2204     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2205     decodedcontroller.controller_number = 19;
2206     break;
2207     case _lev_ctrl_portamentotime:
2208     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2209     decodedcontroller.controller_number = 5;
2210     break;
2211     case _lev_ctrl_sustainpedal:
2212     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2213     decodedcontroller.controller_number = 64;
2214     break;
2215     case _lev_ctrl_portamento:
2216     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2217     decodedcontroller.controller_number = 65;
2218     break;
2219     case _lev_ctrl_sostenutopedal:
2220     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2221     decodedcontroller.controller_number = 66;
2222     break;
2223     case _lev_ctrl_softpedal:
2224     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2225     decodedcontroller.controller_number = 67;
2226     break;
2227     case _lev_ctrl_genpurpose5:
2228     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2229     decodedcontroller.controller_number = 80;
2230     break;
2231     case _lev_ctrl_genpurpose6:
2232     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2233     decodedcontroller.controller_number = 81;
2234     break;
2235     case _lev_ctrl_genpurpose7:
2236     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2237     decodedcontroller.controller_number = 82;
2238     break;
2239     case _lev_ctrl_genpurpose8:
2240     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2241     decodedcontroller.controller_number = 83;
2242     break;
2243     case _lev_ctrl_effect1depth:
2244     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2245     decodedcontroller.controller_number = 91;
2246     break;
2247     case _lev_ctrl_effect2depth:
2248     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2249     decodedcontroller.controller_number = 92;
2250     break;
2251     case _lev_ctrl_effect3depth:
2252     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2253     decodedcontroller.controller_number = 93;
2254     break;
2255     case _lev_ctrl_effect4depth:
2256     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2257     decodedcontroller.controller_number = 94;
2258     break;
2259     case _lev_ctrl_effect5depth:
2260     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2261     decodedcontroller.controller_number = 95;
2262     break;
2263 schoenebeck 55
2264 schoenebeck 2540 // format extension (these controllers are so far only supported by
2265     // LinuxSampler & gigedit) they will *NOT* work with
2266     // Gigasampler/GigaStudio !
2267     case _lev_ctrl_CC3_EXT:
2268     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2269     decodedcontroller.controller_number = 3;
2270     break;
2271     case _lev_ctrl_CC6_EXT:
2272     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2273     decodedcontroller.controller_number = 6;
2274     break;
2275     case _lev_ctrl_CC7_EXT:
2276     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2277     decodedcontroller.controller_number = 7;
2278     break;
2279     case _lev_ctrl_CC8_EXT:
2280     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2281     decodedcontroller.controller_number = 8;
2282     break;
2283     case _lev_ctrl_CC9_EXT:
2284     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2285     decodedcontroller.controller_number = 9;
2286     break;
2287     case _lev_ctrl_CC10_EXT:
2288     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2289     decodedcontroller.controller_number = 10;
2290     break;
2291     case _lev_ctrl_CC11_EXT:
2292     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2293     decodedcontroller.controller_number = 11;
2294     break;
2295     case _lev_ctrl_CC14_EXT:
2296     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2297     decodedcontroller.controller_number = 14;
2298     break;
2299     case _lev_ctrl_CC15_EXT:
2300     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2301     decodedcontroller.controller_number = 15;
2302     break;
2303     case _lev_ctrl_CC20_EXT:
2304     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2305     decodedcontroller.controller_number = 20;
2306     break;
2307     case _lev_ctrl_CC21_EXT:
2308     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2309     decodedcontroller.controller_number = 21;
2310     break;
2311     case _lev_ctrl_CC22_EXT:
2312     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2313     decodedcontroller.controller_number = 22;
2314     break;
2315     case _lev_ctrl_CC23_EXT:
2316     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2317     decodedcontroller.controller_number = 23;
2318     break;
2319     case _lev_ctrl_CC24_EXT:
2320     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2321     decodedcontroller.controller_number = 24;
2322     break;
2323     case _lev_ctrl_CC25_EXT:
2324     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2325     decodedcontroller.controller_number = 25;
2326     break;
2327     case _lev_ctrl_CC26_EXT:
2328     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2329     decodedcontroller.controller_number = 26;
2330     break;
2331     case _lev_ctrl_CC27_EXT:
2332     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2333     decodedcontroller.controller_number = 27;
2334     break;
2335     case _lev_ctrl_CC28_EXT:
2336     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2337     decodedcontroller.controller_number = 28;
2338     break;
2339     case _lev_ctrl_CC29_EXT:
2340     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2341     decodedcontroller.controller_number = 29;
2342     break;
2343     case _lev_ctrl_CC30_EXT:
2344     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2345     decodedcontroller.controller_number = 30;
2346     break;
2347     case _lev_ctrl_CC31_EXT:
2348     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2349     decodedcontroller.controller_number = 31;
2350     break;
2351     case _lev_ctrl_CC68_EXT:
2352     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2353     decodedcontroller.controller_number = 68;
2354     break;
2355     case _lev_ctrl_CC69_EXT:
2356     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2357     decodedcontroller.controller_number = 69;
2358     break;
2359     case _lev_ctrl_CC70_EXT:
2360     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2361     decodedcontroller.controller_number = 70;
2362     break;
2363     case _lev_ctrl_CC71_EXT:
2364     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2365     decodedcontroller.controller_number = 71;
2366     break;
2367     case _lev_ctrl_CC72_EXT:
2368     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2369     decodedcontroller.controller_number = 72;
2370     break;
2371     case _lev_ctrl_CC73_EXT:
2372     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2373     decodedcontroller.controller_number = 73;
2374     break;
2375     case _lev_ctrl_CC74_EXT:
2376     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2377     decodedcontroller.controller_number = 74;
2378     break;
2379     case _lev_ctrl_CC75_EXT:
2380     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2381     decodedcontroller.controller_number = 75;
2382     break;
2383     case _lev_ctrl_CC76_EXT:
2384     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2385     decodedcontroller.controller_number = 76;
2386     break;
2387     case _lev_ctrl_CC77_EXT:
2388     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2389     decodedcontroller.controller_number = 77;
2390     break;
2391     case _lev_ctrl_CC78_EXT:
2392     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2393     decodedcontroller.controller_number = 78;
23