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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1180 - (hide annotations) (download)
Sat May 12 12:39:25 2007 UTC (12 years, 6 months ago) by persson
File size: 147114 byte(s)
* improved handling of fixed length info strings

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