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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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

  ViewVC Help
Powered by ViewVC