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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1195 - (hide annotations) (download)
Thu May 17 17:24:26 2007 UTC (16 years, 10 months ago) by persson
File size: 149253 byte(s)
* write support fix: dimension region chunks were added in wrong list

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

  ViewVC Help
Powered by ViewVC