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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 929 - (hide annotations) (download)
Tue Oct 24 22:24:45 2006 UTC (17 years, 5 months ago) by schoenebeck
File size: 138372 byte(s)
* support for Gigasampler's sample groups added

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

  ViewVC Help
Powered by ViewVC