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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 902 - (hide annotations) (download)
Sat Jul 22 14:22:01 2006 UTC (17 years, 8 months ago) by persson
File size: 133408 byte(s)
* real support for 24 bit samples
* support for reading of .art files

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

  ViewVC Help
Powered by ViewVC