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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2593 - (hide annotations) (download)
Wed Jun 4 01:59:56 2014 UTC (8 years, 8 months ago) by schoenebeck
File size: 255864 byte(s)
* gig.cpp: Missed implementation of Instrument::GetScriptOfSlot().

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