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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 933 - (hide annotations) (download)
Fri Nov 24 12:50:05 2006 UTC (12 years, 6 months ago) by schoenebeck
File size: 141748 byte(s)
* preparations for release 3.1.0

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