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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3115 - (hide annotations) (download)
Sat Apr 15 20:17:05 2017 UTC (6 years, 11 months ago) by schoenebeck
File size: 277249 byte(s)
* src/gig.cpp: Fixed CRC checksums being wrong sometimes.
* src/tools/gig2stereo.cpp: Also merge mono sample pairs
  with non matching loop information if argument
  "--incompatible" was given.
* Bumped version (4.0.0.svn13).

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2912 * Copyright (C) 2003-2016 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 persson 1713 #include <algorithm>
29 schoenebeck 809 #include <math.h>
30 schoenebeck 384 #include <iostream>
31 schoenebeck 2555 #include <assert.h>
32 schoenebeck 384
33 schoenebeck 2912 /// libgig's current file format version (for extending the original Giga file
34     /// format with libgig's own custom data / custom features).
35     #define GIG_FILE_EXT_VERSION 2
36    
37 schoenebeck 809 /// Initial size of the sample buffer which is used for decompression of
38     /// compressed sample wave streams - this value should always be bigger than
39     /// the biggest sample piece expected to be read by the sampler engine,
40     /// otherwise the buffer size will be raised at runtime and thus the buffer
41     /// reallocated which is time consuming and unefficient.
42     #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
43    
44     /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
45     #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
46     #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
47     #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
48     #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
49     #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
50     #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
51     #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
52     #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
53     #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
54     #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
55     #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
56     #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
57    
58 schoenebeck 515 namespace gig {
59 schoenebeck 2
60 schoenebeck 809 // *************** Internal functions for sample decompression ***************
61 persson 365 // *
62    
63 schoenebeck 515 namespace {
64    
65 persson 365 inline int get12lo(const unsigned char* pSrc)
66     {
67     const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
68     return x & 0x800 ? x - 0x1000 : x;
69     }
70    
71     inline int get12hi(const unsigned char* pSrc)
72     {
73     const int x = pSrc[1] >> 4 | pSrc[2] << 4;
74     return x & 0x800 ? x - 0x1000 : x;
75     }
76    
77     inline int16_t get16(const unsigned char* pSrc)
78     {
79     return int16_t(pSrc[0] | pSrc[1] << 8);
80     }
81    
82     inline int get24(const unsigned char* pSrc)
83     {
84     const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
85     return x & 0x800000 ? x - 0x1000000 : x;
86     }
87    
88 persson 902 inline void store24(unsigned char* pDst, int x)
89     {
90     pDst[0] = x;
91     pDst[1] = x >> 8;
92     pDst[2] = x >> 16;
93     }
94    
95 persson 365 void Decompress16(int compressionmode, const unsigned char* params,
96 persson 372 int srcStep, int dstStep,
97     const unsigned char* pSrc, int16_t* pDst,
98 schoenebeck 2912 file_offset_t currentframeoffset,
99     file_offset_t copysamples)
100 persson 365 {
101     switch (compressionmode) {
102     case 0: // 16 bit uncompressed
103     pSrc += currentframeoffset * srcStep;
104     while (copysamples) {
105     *pDst = get16(pSrc);
106 persson 372 pDst += dstStep;
107 persson 365 pSrc += srcStep;
108     copysamples--;
109     }
110     break;
111    
112     case 1: // 16 bit compressed to 8 bit
113     int y = get16(params);
114     int dy = get16(params + 2);
115     while (currentframeoffset) {
116     dy -= int8_t(*pSrc);
117     y -= dy;
118     pSrc += srcStep;
119     currentframeoffset--;
120     }
121     while (copysamples) {
122     dy -= int8_t(*pSrc);
123     y -= dy;
124     *pDst = y;
125 persson 372 pDst += dstStep;
126 persson 365 pSrc += srcStep;
127     copysamples--;
128     }
129     break;
130     }
131     }
132    
133     void Decompress24(int compressionmode, const unsigned char* params,
134 persson 902 int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135 schoenebeck 2912 file_offset_t currentframeoffset,
136     file_offset_t copysamples, int truncatedBits)
137 persson 365 {
138 persson 695 int y, dy, ddy, dddy;
139 persson 437
140 persson 695 #define GET_PARAMS(params) \
141     y = get24(params); \
142     dy = y - get24((params) + 3); \
143     ddy = get24((params) + 6); \
144     dddy = get24((params) + 9)
145 persson 365
146     #define SKIP_ONE(x) \
147 persson 695 dddy -= (x); \
148     ddy -= dddy; \
149     dy = -dy - ddy; \
150     y += dy
151 persson 365
152     #define COPY_ONE(x) \
153     SKIP_ONE(x); \
154 persson 902 store24(pDst, y << truncatedBits); \
155 persson 372 pDst += dstStep
156 persson 365
157     switch (compressionmode) {
158     case 2: // 24 bit uncompressed
159     pSrc += currentframeoffset * 3;
160     while (copysamples) {
161 persson 902 store24(pDst, get24(pSrc) << truncatedBits);
162 persson 372 pDst += dstStep;
163 persson 365 pSrc += 3;
164     copysamples--;
165     }
166     break;
167    
168     case 3: // 24 bit compressed to 16 bit
169     GET_PARAMS(params);
170     while (currentframeoffset) {
171     SKIP_ONE(get16(pSrc));
172     pSrc += 2;
173     currentframeoffset--;
174     }
175     while (copysamples) {
176     COPY_ONE(get16(pSrc));
177     pSrc += 2;
178     copysamples--;
179     }
180     break;
181    
182     case 4: // 24 bit compressed to 12 bit
183     GET_PARAMS(params);
184     while (currentframeoffset > 1) {
185     SKIP_ONE(get12lo(pSrc));
186     SKIP_ONE(get12hi(pSrc));
187     pSrc += 3;
188     currentframeoffset -= 2;
189     }
190     if (currentframeoffset) {
191     SKIP_ONE(get12lo(pSrc));
192     currentframeoffset--;
193     if (copysamples) {
194     COPY_ONE(get12hi(pSrc));
195     pSrc += 3;
196     copysamples--;
197     }
198     }
199     while (copysamples > 1) {
200     COPY_ONE(get12lo(pSrc));
201     COPY_ONE(get12hi(pSrc));
202     pSrc += 3;
203     copysamples -= 2;
204     }
205     if (copysamples) {
206     COPY_ONE(get12lo(pSrc));
207     }
208     break;
209    
210     case 5: // 24 bit compressed to 8 bit
211     GET_PARAMS(params);
212     while (currentframeoffset) {
213     SKIP_ONE(int8_t(*pSrc++));
214     currentframeoffset--;
215     }
216     while (copysamples) {
217     COPY_ONE(int8_t(*pSrc++));
218     copysamples--;
219     }
220     break;
221     }
222     }
223    
224     const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
225     const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
226     const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
227     const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
228     }
229    
230    
231 schoenebeck 1113
232 schoenebeck 1381 // *************** Internal CRC-32 (Cyclic Redundancy Check) functions ***************
233     // *
234    
235     static uint32_t* __initCRCTable() {
236     static uint32_t res[256];
237    
238     for (int i = 0 ; i < 256 ; i++) {
239     uint32_t c = i;
240     for (int j = 0 ; j < 8 ; j++) {
241     c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
242     }
243     res[i] = c;
244     }
245     return res;
246     }
247    
248     static const uint32_t* __CRCTable = __initCRCTable();
249    
250     /**
251     * Initialize a CRC variable.
252     *
253     * @param crc - variable to be initialized
254     */
255     inline static void __resetCRC(uint32_t& crc) {
256     crc = 0xffffffff;
257     }
258    
259     /**
260     * Used to calculate checksums of the sample data in a gig file. The
261     * checksums are stored in the 3crc chunk of the gig file and
262     * automatically updated when a sample is written with Sample::Write().
263     *
264     * One should call __resetCRC() to initialize the CRC variable to be
265     * used before calling this function the first time.
266     *
267     * After initializing the CRC variable one can call this function
268     * arbitrary times, i.e. to split the overall CRC calculation into
269     * steps.
270     *
271     * Once the whole data was processed by __calculateCRC(), one should
272 schoenebeck 3115 * call __finalizeCRC() to get the final CRC result.
273 schoenebeck 1381 *
274     * @param buf - pointer to data the CRC shall be calculated of
275     * @param bufSize - size of the data to be processed
276     * @param crc - variable the CRC sum shall be stored to
277     */
278 schoenebeck 3053 static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
279     for (size_t i = 0 ; i < bufSize ; i++) {
280 schoenebeck 1381 crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281     }
282     }
283    
284     /**
285     * Returns the final CRC result.
286     *
287     * @param crc - variable previously passed to __calculateCRC()
288     */
289 schoenebeck 3115 inline static void __finalizeCRC(uint32_t& crc) {
290     crc ^= 0xffffffff;
291 schoenebeck 1381 }
292    
293    
294    
295 schoenebeck 1113 // *************** Other Internal functions ***************
296     // *
297    
298     static split_type_t __resolveSplitType(dimension_t dimension) {
299     return (
300     dimension == dimension_layer ||
301     dimension == dimension_samplechannel ||
302     dimension == dimension_releasetrigger ||
303     dimension == dimension_keyboard ||
304     dimension == dimension_roundrobin ||
305     dimension == dimension_random ||
306     dimension == dimension_smartmidi ||
307     dimension == dimension_roundrobinkeyboard
308     ) ? split_type_bit : split_type_normal;
309     }
310    
311     static int __resolveZoneSize(dimension_def_t& dimension_definition) {
312     return (dimension_definition.split_type == split_type_normal)
313     ? int(128.0 / dimension_definition.zones) : 0;
314     }
315    
316    
317    
318 schoenebeck 2 // *************** Sample ***************
319     // *
320    
321 schoenebeck 2922 size_t Sample::Instances = 0;
322 schoenebeck 384 buffer_t Sample::InternalDecompressionBuffer;
323 schoenebeck 2
324 schoenebeck 809 /** @brief Constructor.
325     *
326     * Load an existing sample or create a new one. A 'wave' list chunk must
327     * be given to this constructor. In case the given 'wave' list chunk
328     * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
329     * format and sample data will be loaded from there, otherwise default
330     * values will be used and those chunks will be created when
331     * File::Save() will be called later on.
332     *
333     * @param pFile - pointer to gig::File where this sample is
334     * located (or will be located)
335     * @param waveList - pointer to 'wave' list chunk which is (or
336     * will be) associated with this sample
337     * @param WavePoolOffset - offset of this sample data from wave pool
338     * ('wvpl') list chunk
339     * @param fileNo - number of an extension file where this sample
340     * is located, 0 otherwise
341 schoenebeck 2989 * @param index - wave pool index of sample (may be -1 on new sample)
342 schoenebeck 809 */
343 schoenebeck 2989 Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
344     : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345     {
346 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
347 persson 1180 { CHUNK_ID_INAM, 64 },
348     { 0, 0 }
349     };
350 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
351 schoenebeck 2 Instances++;
352 persson 666 FileNo = fileNo;
353 schoenebeck 2
354 schoenebeck 1381 __resetCRC(crc);
355 schoenebeck 2989 // if this is not a new sample, try to get the sample's already existing
356     // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357     // checksum of the time when the sample was consciously modified by the
358     // user for the last time (by calling Sample::Write() that is).
359     if (index >= 0) { // not a new file ...
360     try {
361     uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362     this->crc = crc;
363     } catch (...) {}
364     }
365 schoenebeck 1381
366 schoenebeck 809 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367     if (pCk3gix) {
368 schoenebeck 929 uint16_t iSampleGroup = pCk3gix->ReadInt16();
369 schoenebeck 930 pGroup = pFile->GetGroup(iSampleGroup);
370 schoenebeck 809 } else { // '3gix' chunk missing
371 schoenebeck 930 // by default assigned to that mandatory "Default Group"
372     pGroup = pFile->GetGroup(0);
373 schoenebeck 809 }
374 schoenebeck 2
375 schoenebeck 809 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
376     if (pCkSmpl) {
377     Manufacturer = pCkSmpl->ReadInt32();
378     Product = pCkSmpl->ReadInt32();
379     SamplePeriod = pCkSmpl->ReadInt32();
380     MIDIUnityNote = pCkSmpl->ReadInt32();
381     FineTune = pCkSmpl->ReadInt32();
382     pCkSmpl->Read(&SMPTEFormat, 1, 4);
383     SMPTEOffset = pCkSmpl->ReadInt32();
384     Loops = pCkSmpl->ReadInt32();
385     pCkSmpl->ReadInt32(); // manufByt
386     LoopID = pCkSmpl->ReadInt32();
387     pCkSmpl->Read(&LoopType, 1, 4);
388     LoopStart = pCkSmpl->ReadInt32();
389     LoopEnd = pCkSmpl->ReadInt32();
390     LoopFraction = pCkSmpl->ReadInt32();
391     LoopPlayCount = pCkSmpl->ReadInt32();
392     } else { // 'smpl' chunk missing
393     // use default values
394     Manufacturer = 0;
395     Product = 0;
396 persson 928 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
397 persson 1218 MIDIUnityNote = 60;
398 schoenebeck 809 FineTune = 0;
399 persson 1182 SMPTEFormat = smpte_format_no_offset;
400 schoenebeck 809 SMPTEOffset = 0;
401     Loops = 0;
402     LoopID = 0;
403 persson 1182 LoopType = loop_type_normal;
404 schoenebeck 809 LoopStart = 0;
405     LoopEnd = 0;
406     LoopFraction = 0;
407     LoopPlayCount = 0;
408     }
409 schoenebeck 2
410     FrameTable = NULL;
411     SamplePos = 0;
412     RAMCache.Size = 0;
413     RAMCache.pStart = NULL;
414     RAMCache.NullExtensionSize = 0;
415    
416 persson 365 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
417    
418 persson 437 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
419     Compressed = ewav;
420     Dithered = false;
421     TruncatedBits = 0;
422 schoenebeck 2 if (Compressed) {
423 persson 437 uint32_t version = ewav->ReadInt32();
424     if (version == 3 && BitDepth == 24) {
425     Dithered = ewav->ReadInt32();
426     ewav->SetPos(Channels == 2 ? 84 : 64);
427     TruncatedBits = ewav->ReadInt32();
428     }
429 schoenebeck 2 ScanCompressedSample();
430     }
431 schoenebeck 317
432     // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
433 schoenebeck 384 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
434     InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
435     InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
436 schoenebeck 317 }
437 persson 437 FrameOffset = 0; // just for streaming compressed samples
438 schoenebeck 21
439 persson 864 LoopSize = LoopEnd - LoopStart + 1;
440 schoenebeck 2 }
441    
442 schoenebeck 809 /**
443 schoenebeck 2482 * Make a (semi) deep copy of the Sample object given by @a orig (without
444     * the actual waveform data) and assign it to this object.
445     *
446     * Discussion: copying .gig samples is a bit tricky. It requires three
447     * steps:
448     * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
449     * its new sample waveform data size.
450     * 2. Saving the file (done by File::Save()) so that it gains correct size
451     * and layout for writing the actual wave form data directly to disc
452     * in next step.
453     * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
454     *
455     * @param orig - original Sample object to be copied from
456     */
457     void Sample::CopyAssignMeta(const Sample* orig) {
458     // handle base classes
459     DLS::Sample::CopyAssignCore(orig);
460    
461     // handle actual own attributes of this class
462     Manufacturer = orig->Manufacturer;
463     Product = orig->Product;
464     SamplePeriod = orig->SamplePeriod;
465     MIDIUnityNote = orig->MIDIUnityNote;
466     FineTune = orig->FineTune;
467     SMPTEFormat = orig->SMPTEFormat;
468     SMPTEOffset = orig->SMPTEOffset;
469     Loops = orig->Loops;
470     LoopID = orig->LoopID;
471     LoopType = orig->LoopType;
472     LoopStart = orig->LoopStart;
473     LoopEnd = orig->LoopEnd;
474     LoopSize = orig->LoopSize;
475     LoopFraction = orig->LoopFraction;
476     LoopPlayCount = orig->LoopPlayCount;
477    
478     // schedule resizing this sample to the given sample's size
479     Resize(orig->GetSize());
480     }
481    
482     /**
483     * Should be called after CopyAssignMeta() and File::Save() sequence.
484     * Read more about it in the discussion of CopyAssignMeta(). This method
485     * copies the actual waveform data by disk streaming.
486     *
487     * @e CAUTION: this method is currently not thread safe! During this
488     * operation the sample must not be used for other purposes by other
489     * threads!
490     *
491     * @param orig - original Sample object to be copied from
492     */
493     void Sample::CopyAssignWave(const Sample* orig) {
494     const int iReadAtOnce = 32*1024;
495     char* buf = new char[iReadAtOnce * orig->FrameSize];
496     Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497 schoenebeck 2912 file_offset_t restorePos = pOrig->GetPos();
498 schoenebeck 2482 pOrig->SetPos(0);
499     SetPos(0);
500 schoenebeck 2912 for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501 schoenebeck 2482 n = pOrig->Read(buf, iReadAtOnce))
502     {
503     Write(buf, n);
504     }
505     pOrig->SetPos(restorePos);
506     delete [] buf;
507     }
508    
509     /**
510 schoenebeck 809 * Apply sample and its settings to the respective RIFF chunks. You have
511     * to call File::Save() to make changes persistent.
512     *
513     * Usually there is absolutely no need to call this method explicitly.
514     * It will be called automatically when File::Save() was called.
515     *
516 schoenebeck 2682 * @param pProgress - callback function for progress notification
517 schoenebeck 1050 * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
518 schoenebeck 809 * was provided yet
519     * @throws gig::Exception if there is any invalid sample setting
520     */
521 schoenebeck 2682 void Sample::UpdateChunks(progress_t* pProgress) {
522 schoenebeck 809 // first update base class's chunks
523 schoenebeck 2682 DLS::Sample::UpdateChunks(pProgress);
524 schoenebeck 809
525     // make sure 'smpl' chunk exists
526     pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
527 persson 1182 if (!pCkSmpl) {
528     pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
529     memset(pCkSmpl->LoadChunkData(), 0, 60);
530     }
531 schoenebeck 809 // update 'smpl' chunk
532     uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
533 persson 918 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
534 persson 1179 store32(&pData[0], Manufacturer);
535     store32(&pData[4], Product);
536     store32(&pData[8], SamplePeriod);
537     store32(&pData[12], MIDIUnityNote);
538     store32(&pData[16], FineTune);
539     store32(&pData[20], SMPTEFormat);
540     store32(&pData[24], SMPTEOffset);
541     store32(&pData[28], Loops);
542 schoenebeck 809
543     // we skip 'manufByt' for now (4 bytes)
544    
545 persson 1179 store32(&pData[36], LoopID);
546     store32(&pData[40], LoopType);
547     store32(&pData[44], LoopStart);
548     store32(&pData[48], LoopEnd);
549     store32(&pData[52], LoopFraction);
550     store32(&pData[56], LoopPlayCount);
551 schoenebeck 809
552     // make sure '3gix' chunk exists
553     pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
554     if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
555 schoenebeck 929 // determine appropriate sample group index (to be stored in chunk)
556 schoenebeck 930 uint16_t iSampleGroup = 0; // 0 refers to default sample group
557 schoenebeck 929 File* pFile = static_cast<File*>(pParent);
558     if (pFile->pGroups) {
559     std::list<Group*>::iterator iter = pFile->pGroups->begin();
560     std::list<Group*>::iterator end = pFile->pGroups->end();
561 schoenebeck 930 for (int i = 0; iter != end; i++, iter++) {
562 schoenebeck 929 if (*iter == pGroup) {
563     iSampleGroup = i;
564     break; // found
565     }
566     }
567     }
568 schoenebeck 809 // update '3gix' chunk
569     pData = (uint8_t*) pCk3gix->LoadChunkData();
570 persson 1179 store16(&pData[0], iSampleGroup);
571 schoenebeck 2484
572     // if the library user toggled the "Compressed" attribute from true to
573     // false, then the EWAV chunk associated with compressed samples needs
574     // to be deleted
575     RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
576     if (ewav && !Compressed) {
577     pWaveList->DeleteSubChunk(ewav);
578     }
579 schoenebeck 809 }
580    
581 schoenebeck 2 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
582     void Sample::ScanCompressedSample() {
583     //TODO: we have to add some more scans here (e.g. determine compression rate)
584     this->SamplesTotal = 0;
585 schoenebeck 2912 std::list<file_offset_t> frameOffsets;
586 schoenebeck 2
587 persson 365 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
588 schoenebeck 384 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
589 persson 365
590 schoenebeck 2 // Scanning
591     pCkData->SetPos(0);
592 persson 365 if (Channels == 2) { // Stereo
593     for (int i = 0 ; ; i++) {
594     // for 24 bit samples every 8:th frame offset is
595     // stored, to save some memory
596     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
597    
598     const int mode_l = pCkData->ReadUint8();
599     const int mode_r = pCkData->ReadUint8();
600     if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
601 schoenebeck 2912 const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
602 persson 365
603     if (pCkData->RemainingBytes() <= frameSize) {
604     SamplesInLastFrame =
605     ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
606     (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
607     SamplesTotal += SamplesInLastFrame;
608 schoenebeck 2 break;
609 persson 365 }
610     SamplesTotal += SamplesPerFrame;
611     pCkData->SetPos(frameSize, RIFF::stream_curpos);
612     }
613     }
614     else { // Mono
615     for (int i = 0 ; ; i++) {
616     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
617    
618     const int mode = pCkData->ReadUint8();
619     if (mode > 5) throw gig::Exception("Unknown compression mode");
620 schoenebeck 2912 const file_offset_t frameSize = bytesPerFrame[mode];
621 persson 365
622     if (pCkData->RemainingBytes() <= frameSize) {
623     SamplesInLastFrame =
624     ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
625     SamplesTotal += SamplesInLastFrame;
626 schoenebeck 2 break;
627 persson 365 }
628     SamplesTotal += SamplesPerFrame;
629     pCkData->SetPos(frameSize, RIFF::stream_curpos);
630 schoenebeck 2 }
631     }
632     pCkData->SetPos(0);
633    
634     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
635     if (FrameTable) delete[] FrameTable;
636 schoenebeck 2912 FrameTable = new file_offset_t[frameOffsets.size()];
637     std::list<file_offset_t>::iterator end = frameOffsets.end();
638     std::list<file_offset_t>::iterator iter = frameOffsets.begin();
639 schoenebeck 2 for (int i = 0; iter != end; i++, iter++) {
640     FrameTable[i] = *iter;
641     }
642     }
643    
644     /**
645     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
646     * ReleaseSampleData() to free the memory if you don't need the cached
647     * sample data anymore.
648     *
649     * @returns buffer_t structure with start address and size of the buffer
650     * in bytes
651     * @see ReleaseSampleData(), Read(), SetPos()
652     */
653     buffer_t Sample::LoadSampleData() {
654     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
655     }
656    
657     /**
658     * Reads (uncompresses if needed) and caches the first \a SampleCount
659     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
660     * memory space if you don't need the cached samples anymore. There is no
661     * guarantee that exactly \a SampleCount samples will be cached; this is
662     * not an error. The size will be eventually truncated e.g. to the
663     * beginning of a frame of a compressed sample. This is done for
664     * efficiency reasons while streaming the wave by your sampler engine
665     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
666     * that will be returned to determine the actual cached samples, but note
667     * that the size is given in bytes! You get the number of actually cached
668     * samples by dividing it by the frame size of the sample:
669 schoenebeck 384 * @code
670 schoenebeck 2 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
671     * long cachedsamples = buf.Size / pSample->FrameSize;
672 schoenebeck 384 * @endcode
673 schoenebeck 2 *
674     * @param SampleCount - number of sample points to load into RAM
675     * @returns buffer_t structure with start address and size of
676     * the cached sample data in bytes
677     * @see ReleaseSampleData(), Read(), SetPos()
678     */
679 schoenebeck 2912 buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
680 schoenebeck 2 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
681     }
682    
683     /**
684     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
685     * ReleaseSampleData() to free the memory if you don't need the cached
686     * sample data anymore.
687     * The method will add \a NullSamplesCount silence samples past the
688     * official buffer end (this won't affect the 'Size' member of the
689     * buffer_t structure, that means 'Size' always reflects the size of the
690     * actual sample data, the buffer might be bigger though). Silence
691     * samples past the official buffer are needed for differential
692     * algorithms that always have to take subsequent samples into account
693     * (resampling/interpolation would be an important example) and avoids
694     * memory access faults in such cases.
695     *
696     * @param NullSamplesCount - number of silence samples the buffer should
697     * be extended past it's data end
698     * @returns buffer_t structure with start address and
699     * size of the buffer in bytes
700     * @see ReleaseSampleData(), Read(), SetPos()
701     */
702     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
703     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
704     }
705    
706     /**
707     * Reads (uncompresses if needed) and caches the first \a SampleCount
708     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
709     * memory space if you don't need the cached samples anymore. There is no
710     * guarantee that exactly \a SampleCount samples will be cached; this is
711     * not an error. The size will be eventually truncated e.g. to the
712     * beginning of a frame of a compressed sample. This is done for
713     * efficiency reasons while streaming the wave by your sampler engine
714     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
715     * that will be returned to determine the actual cached samples, but note
716     * that the size is given in bytes! You get the number of actually cached
717     * samples by dividing it by the frame size of the sample:
718 schoenebeck 384 * @code
719 schoenebeck 2 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
720     * long cachedsamples = buf.Size / pSample->FrameSize;
721 schoenebeck 384 * @endcode
722 schoenebeck 2 * The method will add \a NullSamplesCount silence samples past the
723     * official buffer end (this won't affect the 'Size' member of the
724     * buffer_t structure, that means 'Size' always reflects the size of the
725     * actual sample data, the buffer might be bigger though). Silence
726     * samples past the official buffer are needed for differential
727     * algorithms that always have to take subsequent samples into account
728     * (resampling/interpolation would be an important example) and avoids
729     * memory access faults in such cases.
730     *
731     * @param SampleCount - number of sample points to load into RAM
732     * @param NullSamplesCount - number of silence samples the buffer should
733     * be extended past it's data end
734     * @returns buffer_t structure with start address and
735     * size of the cached sample data in bytes
736     * @see ReleaseSampleData(), Read(), SetPos()
737     */
738 schoenebeck 2912 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
739 schoenebeck 2 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
740     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
741 schoenebeck 2912 file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
742 schoenebeck 1851 SetPos(0); // reset read position to begin of sample
743 schoenebeck 2 RAMCache.pStart = new int8_t[allocationsize];
744     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
745     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
746     // fill the remaining buffer space with silence samples
747     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
748     return GetCache();
749     }
750    
751     /**
752     * Returns current cached sample points. A buffer_t structure will be
753     * returned which contains address pointer to the begin of the cache and
754     * the size of the cached sample data in bytes. Use
755     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
756     * RAM.
757     *
758     * @returns buffer_t structure with current cached sample points
759     * @see LoadSampleData();
760     */
761     buffer_t Sample::GetCache() {
762     // return a copy of the buffer_t structure
763     buffer_t result;
764     result.Size = this->RAMCache.Size;
765     result.pStart = this->RAMCache.pStart;
766     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
767     return result;
768     }
769    
770     /**
771     * Frees the cached sample from RAM if loaded with
772     * <i>LoadSampleData()</i> previously.
773     *
774     * @see LoadSampleData();
775     */
776     void Sample::ReleaseSampleData() {
777     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
778     RAMCache.pStart = NULL;
779     RAMCache.Size = 0;
780 schoenebeck 1851 RAMCache.NullExtensionSize = 0;
781 schoenebeck 2 }
782    
783 schoenebeck 809 /** @brief Resize sample.
784     *
785     * Resizes the sample's wave form data, that is the actual size of
786     * sample wave data possible to be written for this sample. This call
787     * will return immediately and just schedule the resize operation. You
788     * should call File::Save() to actually perform the resize operation(s)
789     * "physically" to the file. As this can take a while on large files, it
790     * is recommended to call Resize() first on all samples which have to be
791     * resized and finally to call File::Save() to perform all those resize
792     * operations in one rush.
793     *
794     * The actual size (in bytes) is dependant to the current FrameSize
795     * value. You may want to set FrameSize before calling Resize().
796     *
797     * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
798     * enlarged samples before calling File::Save() as this might exceed the
799     * current sample's boundary!
800     *
801 schoenebeck 1050 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
802     * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
803 schoenebeck 809 * other formats will fail!
804     *
805 schoenebeck 2922 * @param NewSize - new sample wave data size in sample points (must be
806     * greater than zero)
807 schoenebeck 1050 * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
808 schoenebeck 2922 * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
809 schoenebeck 809 * @throws gig::Exception if existing sample is compressed
810     * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
811     * DLS::Sample::FormatTag, File::Save()
812     */
813 schoenebeck 2922 void Sample::Resize(file_offset_t NewSize) {
814 schoenebeck 809 if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
815 schoenebeck 2922 DLS::Sample::Resize(NewSize);
816 schoenebeck 809 }
817    
818 schoenebeck 2 /**
819     * Sets the position within the sample (in sample points, not in
820     * bytes). Use this method and <i>Read()</i> if you don't want to load
821     * the sample into RAM, thus for disk streaming.
822     *
823     * Although the original Gigasampler engine doesn't allow positioning
824     * within compressed samples, I decided to implement it. Even though
825     * the Gigasampler format doesn't allow to define loops for compressed
826     * samples at the moment, positioning within compressed samples might be
827     * interesting for some sampler engines though. The only drawback about
828     * my decision is that it takes longer to load compressed gig Files on
829     * startup, because it's neccessary to scan the samples for some
830     * mandatory informations. But I think as it doesn't affect the runtime
831     * efficiency, nobody will have a problem with that.
832     *
833     * @param SampleCount number of sample points to jump
834     * @param Whence optional: to which relation \a SampleCount refers
835     * to, if omited <i>RIFF::stream_start</i> is assumed
836     * @returns the new sample position
837     * @see Read()
838     */
839 schoenebeck 2912 file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
840 schoenebeck 2 if (Compressed) {
841     switch (Whence) {
842     case RIFF::stream_curpos:
843     this->SamplePos += SampleCount;
844     break;
845     case RIFF::stream_end:
846     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
847     break;
848     case RIFF::stream_backward:
849     this->SamplePos -= SampleCount;
850     break;
851     case RIFF::stream_start: default:
852     this->SamplePos = SampleCount;
853     break;
854     }
855     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
856    
857 schoenebeck 2912 file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
858 schoenebeck 2 this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
859     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
860     return this->SamplePos;
861     }
862     else { // not compressed
863 schoenebeck 2912 file_offset_t orderedBytes = SampleCount * this->FrameSize;
864     file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
865 schoenebeck 2 return (result == orderedBytes) ? SampleCount
866     : result / this->FrameSize;
867     }
868     }
869    
870     /**
871     * Returns the current position in the sample (in sample points).
872     */
873 schoenebeck 2912 file_offset_t Sample::GetPos() const {
874 schoenebeck 2 if (Compressed) return SamplePos;
875     else return pCkData->GetPos() / FrameSize;
876     }
877    
878     /**
879 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
880     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
881     * the position within the sample respectively, this method honors the
882     * looping informations of the sample (if any). The sample wave stream
883     * will be decompressed on the fly if using a compressed sample. Use this
884     * method if you don't want to load the sample into RAM, thus for disk
885     * streaming. All this methods needs to know to proceed with streaming
886     * for the next time you call this method is stored in \a pPlaybackState.
887     * You have to allocate and initialize the playback_state_t structure by
888     * yourself before you use it to stream a sample:
889 schoenebeck 384 * @code
890     * gig::playback_state_t playbackstate;
891     * playbackstate.position = 0;
892     * playbackstate.reverse = false;
893     * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
894     * @endcode
895 schoenebeck 24 * You don't have to take care of things like if there is actually a loop
896     * defined or if the current read position is located within a loop area.
897     * The method already handles such cases by itself.
898     *
899 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
900     * have to use an external decompression buffer for <b>EACH</b>
901     * streaming thread to avoid race conditions and crashes!
902     *
903 schoenebeck 24 * @param pBuffer destination buffer
904     * @param SampleCount number of sample points to read
905     * @param pPlaybackState will be used to store and reload the playback
906     * state for the next ReadAndLoop() call
907 persson 864 * @param pDimRgn dimension region with looping information
908 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
909 schoenebeck 24 * @returns number of successfully read sample points
910 schoenebeck 384 * @see CreateDecompressionBuffer()
911 schoenebeck 24 */
912 schoenebeck 2912 file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
913 persson 864 DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
914 schoenebeck 2912 file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
915 schoenebeck 24 uint8_t* pDst = (uint8_t*) pBuffer;
916    
917     SetPos(pPlaybackState->position); // recover position from the last time
918    
919 persson 864 if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
920 schoenebeck 24
921 persson 864 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
922     const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
923 schoenebeck 24
924 persson 864 if (GetPos() <= loopEnd) {
925     switch (loop.LoopType) {
926 schoenebeck 24
927 persson 864 case loop_type_bidirectional: { //TODO: not tested yet!
928     do {
929     // if not endless loop check if max. number of loop cycles have been passed
930     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
931 schoenebeck 24
932 persson 864 if (!pPlaybackState->reverse) { // forward playback
933     do {
934     samplestoloopend = loopEnd - GetPos();
935     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
936     samplestoread -= readsamples;
937     totalreadsamples += readsamples;
938     if (readsamples == samplestoloopend) {
939     pPlaybackState->reverse = true;
940     break;
941     }
942     } while (samplestoread && readsamples);
943     }
944     else { // backward playback
945 schoenebeck 24
946 persson 864 // as we can only read forward from disk, we have to
947     // determine the end position within the loop first,
948     // read forward from that 'end' and finally after
949     // reading, swap all sample frames so it reflects
950     // backward playback
951 schoenebeck 24
952 schoenebeck 2912 file_offset_t swapareastart = totalreadsamples;
953     file_offset_t loopoffset = GetPos() - loop.LoopStart;
954     file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
955     file_offset_t reverseplaybackend = GetPos() - samplestoreadinloop;
956 schoenebeck 24
957 persson 864 SetPos(reverseplaybackend);
958 schoenebeck 24
959 persson 864 // read samples for backward playback
960     do {
961     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
962     samplestoreadinloop -= readsamples;
963     samplestoread -= readsamples;
964     totalreadsamples += readsamples;
965     } while (samplestoreadinloop && readsamples);
966 schoenebeck 24
967 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
968    
969     if (reverseplaybackend == loop.LoopStart) {
970     pPlaybackState->loop_cycles_left--;
971     pPlaybackState->reverse = false;
972     }
973    
974     // reverse the sample frames for backward playback
975 schoenebeck 1875 if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
976     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
977 schoenebeck 24 }
978 persson 864 } while (samplestoread && readsamples);
979     break;
980     }
981 schoenebeck 24
982 persson 864 case loop_type_backward: { // TODO: not tested yet!
983     // forward playback (not entered the loop yet)
984     if (!pPlaybackState->reverse) do {
985     samplestoloopend = loopEnd - GetPos();
986     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
987     samplestoread -= readsamples;
988     totalreadsamples += readsamples;
989     if (readsamples == samplestoloopend) {
990     pPlaybackState->reverse = true;
991     break;
992     }
993     } while (samplestoread && readsamples);
994 schoenebeck 24
995 persson 864 if (!samplestoread) break;
996 schoenebeck 24
997 persson 864 // as we can only read forward from disk, we have to
998     // determine the end position within the loop first,
999     // read forward from that 'end' and finally after
1000     // reading, swap all sample frames so it reflects
1001     // backward playback
1002 schoenebeck 24
1003 schoenebeck 2912 file_offset_t swapareastart = totalreadsamples;
1004     file_offset_t loopoffset = GetPos() - loop.LoopStart;
1005     file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1006 persson 864 : samplestoread;
1007 schoenebeck 2912 file_offset_t reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1008 schoenebeck 24
1009 persson 864 SetPos(reverseplaybackend);
1010 schoenebeck 24
1011 persson 864 // read samples for backward playback
1012     do {
1013     // if not endless loop check if max. number of loop cycles have been passed
1014     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1015     samplestoloopend = loopEnd - GetPos();
1016     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1017     samplestoreadinloop -= readsamples;
1018     samplestoread -= readsamples;
1019     totalreadsamples += readsamples;
1020     if (readsamples == samplestoloopend) {
1021     pPlaybackState->loop_cycles_left--;
1022     SetPos(loop.LoopStart);
1023     }
1024     } while (samplestoreadinloop && readsamples);
1025 schoenebeck 24
1026 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
1027 schoenebeck 24
1028 persson 864 // reverse the sample frames for backward playback
1029     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1030     break;
1031     }
1032 schoenebeck 24
1033 persson 864 default: case loop_type_normal: {
1034     do {
1035     // if not endless loop check if max. number of loop cycles have been passed
1036     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1037     samplestoloopend = loopEnd - GetPos();
1038     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1039     samplestoread -= readsamples;
1040     totalreadsamples += readsamples;
1041     if (readsamples == samplestoloopend) {
1042     pPlaybackState->loop_cycles_left--;
1043     SetPos(loop.LoopStart);
1044     }
1045     } while (samplestoread && readsamples);
1046     break;
1047     }
1048 schoenebeck 24 }
1049     }
1050     }
1051    
1052     // read on without looping
1053     if (samplestoread) do {
1054 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1055 schoenebeck 24 samplestoread -= readsamples;
1056     totalreadsamples += readsamples;
1057     } while (readsamples && samplestoread);
1058    
1059     // store current position
1060     pPlaybackState->position = GetPos();
1061    
1062     return totalreadsamples;
1063     }
1064    
1065     /**
1066 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
1067     * position into the buffer pointed by \a pBuffer and increments the
1068     * position within the sample. The sample wave stream will be
1069     * decompressed on the fly if using a compressed sample. Use this method
1070     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
1071     * thus for disk streaming.
1072     *
1073 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
1074     * have to use an external decompression buffer for <b>EACH</b>
1075     * streaming thread to avoid race conditions and crashes!
1076     *
1077 persson 902 * For 16 bit samples, the data in the buffer will be int16_t
1078     * (using native endianness). For 24 bit, the buffer will
1079     * contain three bytes per sample, little-endian.
1080     *
1081 schoenebeck 2 * @param pBuffer destination buffer
1082     * @param SampleCount number of sample points to read
1083 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
1084 schoenebeck 2 * @returns number of successfully read sample points
1085 schoenebeck 384 * @see SetPos(), CreateDecompressionBuffer()
1086 schoenebeck 2 */
1087 schoenebeck 2912 file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1088 schoenebeck 21 if (SampleCount == 0) return 0;
1089 schoenebeck 317 if (!Compressed) {
1090     if (BitDepth == 24) {
1091 persson 902 return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1092 schoenebeck 317 }
1093 persson 365 else { // 16 bit
1094     // (pCkData->Read does endian correction)
1095     return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1096     : pCkData->Read(pBuffer, SampleCount, 2);
1097     }
1098 schoenebeck 317 }
1099 persson 365 else {
1100 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
1101 persson 365 //TODO: efficiency: maybe we should test for an average compression rate
1102 schoenebeck 2912 file_offset_t assumedsize = GuessSize(SampleCount),
1103 schoenebeck 2 remainingbytes = 0, // remaining bytes in the local buffer
1104     remainingsamples = SampleCount,
1105 persson 365 copysamples, skipsamples,
1106     currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1107 schoenebeck 2 this->FrameOffset = 0;
1108    
1109 schoenebeck 384 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1110    
1111     // if decompression buffer too small, then reduce amount of samples to read
1112     if (pDecompressionBuffer->Size < assumedsize) {
1113     std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1114     SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1115     remainingsamples = SampleCount;
1116     assumedsize = GuessSize(SampleCount);
1117 schoenebeck 2 }
1118    
1119 schoenebeck 384 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1120 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
1121 persson 902 uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1122 schoenebeck 2 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1123    
1124 persson 365 while (remainingsamples && remainingbytes) {
1125 schoenebeck 2912 file_offset_t framesamples = SamplesPerFrame;
1126     file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1127 schoenebeck 2
1128 persson 365 int mode_l = *pSrc++, mode_r = 0;
1129    
1130     if (Channels == 2) {
1131     mode_r = *pSrc++;
1132     framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1133     rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1134     nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1135     if (remainingbytes < framebytes) { // last frame in sample
1136     framesamples = SamplesInLastFrame;
1137     if (mode_l == 4 && (framesamples & 1)) {
1138     rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1139     }
1140     else {
1141     rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1142     }
1143 schoenebeck 2 }
1144     }
1145 persson 365 else {
1146     framebytes = bytesPerFrame[mode_l] + 1;
1147     nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1148     if (remainingbytes < framebytes) {
1149     framesamples = SamplesInLastFrame;
1150     }
1151     }
1152 schoenebeck 2
1153     // determine how many samples in this frame to skip and read
1154 persson 365 if (currentframeoffset + remainingsamples >= framesamples) {
1155     if (currentframeoffset <= framesamples) {
1156     copysamples = framesamples - currentframeoffset;
1157     skipsamples = currentframeoffset;
1158     }
1159     else {
1160     copysamples = 0;
1161     skipsamples = framesamples;
1162     }
1163 schoenebeck 2 }
1164     else {
1165 persson 365 // This frame has enough data for pBuffer, but not
1166     // all of the frame is needed. Set file position
1167     // to start of this frame for next call to Read.
1168 schoenebeck 2 copysamples = remainingsamples;
1169 persson 365 skipsamples = currentframeoffset;
1170     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1171     this->FrameOffset = currentframeoffset + copysamples;
1172     }
1173     remainingsamples -= copysamples;
1174    
1175     if (remainingbytes > framebytes) {
1176     remainingbytes -= framebytes;
1177     if (remainingsamples == 0 &&
1178     currentframeoffset + copysamples == framesamples) {
1179     // This frame has enough data for pBuffer, and
1180     // all of the frame is needed. Set file
1181     // position to start of next frame for next
1182     // call to Read. FrameOffset is 0.
1183 schoenebeck 2 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1184     }
1185     }
1186 persson 365 else remainingbytes = 0;
1187 schoenebeck 2
1188 persson 365 currentframeoffset -= skipsamples;
1189 schoenebeck 2
1190 persson 365 if (copysamples == 0) {
1191     // skip this frame
1192     pSrc += framebytes - Channels;
1193     }
1194     else {
1195     const unsigned char* const param_l = pSrc;
1196     if (BitDepth == 24) {
1197     if (mode_l != 2) pSrc += 12;
1198 schoenebeck 2
1199 persson 365 if (Channels == 2) { // Stereo
1200     const unsigned char* const param_r = pSrc;
1201     if (mode_r != 2) pSrc += 12;
1202    
1203 persson 902 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1204 persson 437 skipsamples, copysamples, TruncatedBits);
1205 persson 902 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1206 persson 437 skipsamples, copysamples, TruncatedBits);
1207 persson 902 pDst24 += copysamples * 6;
1208 schoenebeck 2 }
1209 persson 365 else { // Mono
1210 persson 902 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1211 persson 437 skipsamples, copysamples, TruncatedBits);
1212 persson 902 pDst24 += copysamples * 3;
1213 schoenebeck 2 }
1214 persson 365 }
1215     else { // 16 bit
1216     if (mode_l) pSrc += 4;
1217 schoenebeck 2
1218 persson 365 int step;
1219     if (Channels == 2) { // Stereo
1220     const unsigned char* const param_r = pSrc;
1221     if (mode_r) pSrc += 4;
1222    
1223     step = (2 - mode_l) + (2 - mode_r);
1224 persson 372 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1225     Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1226 persson 365 skipsamples, copysamples);
1227     pDst += copysamples << 1;
1228 schoenebeck 2 }
1229 persson 365 else { // Mono
1230     step = 2 - mode_l;
1231 persson 372 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1232 persson 365 pDst += copysamples;
1233 schoenebeck 2 }
1234 persson 365 }
1235     pSrc += nextFrameOffset;
1236     }
1237 schoenebeck 2
1238 persson 365 // reload from disk to local buffer if needed
1239     if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1240     assumedsize = GuessSize(remainingsamples);
1241     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1242     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1243 schoenebeck 384 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1244     pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1245 schoenebeck 2 }
1246 persson 365 } // while
1247    
1248 schoenebeck 2 this->SamplePos += (SampleCount - remainingsamples);
1249 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1250 schoenebeck 2 return (SampleCount - remainingsamples);
1251     }
1252     }
1253    
1254 schoenebeck 809 /** @brief Write sample wave data.
1255     *
1256     * Writes \a SampleCount number of sample points from the buffer pointed
1257     * by \a pBuffer and increments the position within the sample. Use this
1258     * method to directly write the sample data to disk, i.e. if you don't
1259     * want or cannot load the whole sample data into RAM.
1260     *
1261     * You have to Resize() the sample to the desired size and call
1262     * File::Save() <b>before</b> using Write().
1263     *
1264     * Note: there is currently no support for writing compressed samples.
1265     *
1266 persson 1264 * For 16 bit samples, the data in the source buffer should be
1267     * int16_t (using native endianness). For 24 bit, the buffer
1268     * should contain three bytes per sample, little-endian.
1269     *
1270 schoenebeck 809 * @param pBuffer - source buffer
1271     * @param SampleCount - number of sample points to write
1272     * @throws DLS::Exception if current sample size is too small
1273     * @throws gig::Exception if sample is compressed
1274     * @see DLS::LoadSampleData()
1275     */
1276 schoenebeck 2912 file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1277 schoenebeck 809 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1278 persson 1207
1279     // if this is the first write in this sample, reset the
1280     // checksum calculator
1281 persson 1199 if (pCkData->GetPos() == 0) {
1282 schoenebeck 1381 __resetCRC(crc);
1283 persson 1199 }
1284 persson 1264 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1285 schoenebeck 2912 file_offset_t res;
1286 persson 1264 if (BitDepth == 24) {
1287     res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1288     } else { // 16 bit
1289     res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1290     : pCkData->Write(pBuffer, SampleCount, 2);
1291     }
1292 schoenebeck 1381 __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1293 persson 1199
1294 persson 1207 // if this is the last write, update the checksum chunk in the
1295     // file
1296 persson 1199 if (pCkData->GetPos() == pCkData->GetSize()) {
1297 schoenebeck 3115 __finalizeCRC(crc);
1298 persson 1199 File* pFile = static_cast<File*>(GetParent());
1299 schoenebeck 3115 pFile->SetSampleChecksum(this, crc);
1300 persson 1199 }
1301     return res;
1302 schoenebeck 809 }
1303    
1304 schoenebeck 384 /**
1305     * Allocates a decompression buffer for streaming (compressed) samples
1306     * with Sample::Read(). If you are using more than one streaming thread
1307     * in your application you <b>HAVE</b> to create a decompression buffer
1308     * for <b>EACH</b> of your streaming threads and provide it with the
1309     * Sample::Read() call in order to avoid race conditions and crashes.
1310     *
1311     * You should free the memory occupied by the allocated buffer(s) once
1312     * you don't need one of your streaming threads anymore by calling
1313     * DestroyDecompressionBuffer().
1314     *
1315     * @param MaxReadSize - the maximum size (in sample points) you ever
1316     * expect to read with one Read() call
1317     * @returns allocated decompression buffer
1318     * @see DestroyDecompressionBuffer()
1319     */
1320 schoenebeck 2912 buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1321 schoenebeck 384 buffer_t result;
1322     const double worstCaseHeaderOverhead =
1323     (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1324 schoenebeck 2912 result.Size = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1325 schoenebeck 384 result.pStart = new int8_t[result.Size];
1326     result.NullExtensionSize = 0;
1327     return result;
1328     }
1329    
1330     /**
1331     * Free decompression buffer, previously created with
1332     * CreateDecompressionBuffer().
1333     *
1334     * @param DecompressionBuffer - previously allocated decompression
1335     * buffer to free
1336     */
1337     void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1338     if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1339     delete[] (int8_t*) DecompressionBuffer.pStart;
1340     DecompressionBuffer.pStart = NULL;
1341     DecompressionBuffer.Size = 0;
1342     DecompressionBuffer.NullExtensionSize = 0;
1343     }
1344     }
1345    
1346 schoenebeck 930 /**
1347     * Returns pointer to the Group this Sample belongs to. In the .gig
1348     * format a sample always belongs to one group. If it wasn't explicitly
1349     * assigned to a certain group, it will be automatically assigned to a
1350     * default group.
1351     *
1352     * @returns Sample's Group (never NULL)
1353     */
1354     Group* Sample::GetGroup() const {
1355     return pGroup;
1356     }
1357    
1358 schoenebeck 2985 /**
1359 schoenebeck 2989 * Returns the CRC-32 checksum of the sample's raw wave form data at the
1360     * time when this sample's wave form data was modified for the last time
1361     * by calling Write(). This checksum only covers the raw wave form data,
1362     * not any meta informations like i.e. bit depth or loop points. Since
1363     * this method just returns the checksum stored for this sample i.e. when
1364     * the gig file was loaded, this method returns immediately. So it does no
1365     * recalcuation of the checksum with the currently available sample wave
1366     * form data.
1367     *
1368     * @see VerifyWaveData()
1369     */
1370     uint32_t Sample::GetWaveDataCRC32Checksum() {
1371     return crc;
1372     }
1373    
1374     /**
1375 schoenebeck 2985 * Checks the integrity of this sample's raw audio wave data. Whenever a
1376     * Sample's raw wave data is intentionally modified (i.e. by calling
1377     * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1378     * is calculated and stored/updated for this sample, along to the sample's
1379     * meta informations.
1380     *
1381     * Now by calling this method the current raw audio wave data is checked
1382     * against the already stored CRC32 check sum in order to check whether the
1383     * sample data had been damaged unintentionally for some reason. Since by
1384     * calling this method always the entire raw audio wave data has to be
1385     * read, verifying all samples this way may take a long time accordingly.
1386     * And that's also the reason why the sample integrity is not checked by
1387     * default whenever a gig file is loaded. So this method must be called
1388     * explicitly to fulfill this task.
1389     *
1390 schoenebeck 2989 * @param pActually - (optional) if provided, will be set to the actually
1391     * calculated checksum of the current raw wave form data,
1392     * you can get the expected checksum instead by calling
1393     * GetWaveDataCRC32Checksum()
1394 schoenebeck 2985 * @returns true if sample is OK or false if the sample is damaged
1395     * @throws Exception if no checksum had been stored to disk for this
1396     * sample yet, or on I/O issues
1397 schoenebeck 2989 * @see GetWaveDataCRC32Checksum()
1398 schoenebeck 2985 */
1399 schoenebeck 2989 bool Sample::VerifyWaveData(uint32_t* pActually) {
1400 schoenebeck 3053 //File* pFile = static_cast<File*>(GetParent());
1401 schoenebeck 2985 uint32_t crc = CalculateWaveDataChecksum();
1402 schoenebeck 2989 if (pActually) *pActually = crc;
1403     return crc == this->crc;
1404 schoenebeck 2985 }
1405    
1406     uint32_t Sample::CalculateWaveDataChecksum() {
1407     const size_t sz = 20*1024; // 20kB buffer size
1408     std::vector<uint8_t> buffer(sz);
1409     buffer.resize(sz);
1410    
1411     const size_t n = sz / FrameSize;
1412     SetPos(0);
1413     uint32_t crc = 0;
1414     __resetCRC(crc);
1415     while (true) {
1416     file_offset_t nRead = Read(&buffer[0], n);
1417     if (nRead <= 0) break;
1418     __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1419     }
1420 schoenebeck 3115 __finalizeCRC(crc);
1421 schoenebeck 2985 return crc;
1422     }
1423    
1424 schoenebeck 2 Sample::~Sample() {
1425     Instances--;
1426 schoenebeck 384 if (!Instances && InternalDecompressionBuffer.Size) {
1427     delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1428     InternalDecompressionBuffer.pStart = NULL;
1429     InternalDecompressionBuffer.Size = 0;
1430 schoenebeck 355 }
1431 schoenebeck 2 if (FrameTable) delete[] FrameTable;
1432     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1433     }
1434    
1435    
1436    
1437     // *************** DimensionRegion ***************
1438     // *
1439    
1440 schoenebeck 2922 size_t DimensionRegion::Instances = 0;
1441 schoenebeck 16 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1442    
1443 schoenebeck 1316 DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1444 schoenebeck 16 Instances++;
1445    
1446 schoenebeck 823 pSample = NULL;
1447 schoenebeck 1316 pRegion = pParent;
1448 schoenebeck 823
1449 persson 1247 if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1450     else memset(&Crossfade, 0, 4);
1451    
1452 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1453 schoenebeck 2
1454     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1455 schoenebeck 809 if (_3ewa) { // if '3ewa' chunk exists
1456 persson 918 _3ewa->ReadInt32(); // unknown, always == chunk size ?
1457 schoenebeck 809 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1458     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1459     _3ewa->ReadInt16(); // unknown
1460     LFO1InternalDepth = _3ewa->ReadUint16();
1461     _3ewa->ReadInt16(); // unknown
1462     LFO3InternalDepth = _3ewa->ReadInt16();
1463     _3ewa->ReadInt16(); // unknown
1464     LFO1ControlDepth = _3ewa->ReadUint16();
1465     _3ewa->ReadInt16(); // unknown
1466     LFO3ControlDepth = _3ewa->ReadInt16();
1467     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1468     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1469     _3ewa->ReadInt16(); // unknown
1470     EG1Sustain = _3ewa->ReadUint16();
1471     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1472     EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1473     uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1474     EG1ControllerInvert = eg1ctrloptions & 0x01;
1475     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1476     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1477     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1478     EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1479     uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1480     EG2ControllerInvert = eg2ctrloptions & 0x01;
1481     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1482     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1483     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1484     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1485     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1486     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1487     _3ewa->ReadInt16(); // unknown
1488     EG2Sustain = _3ewa->ReadUint16();
1489     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1490     _3ewa->ReadInt16(); // unknown
1491     LFO2ControlDepth = _3ewa->ReadUint16();
1492     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1493     _3ewa->ReadInt16(); // unknown
1494     LFO2InternalDepth = _3ewa->ReadUint16();
1495     int32_t eg1decay2 = _3ewa->ReadInt32();
1496     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1497     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1498     _3ewa->ReadInt16(); // unknown
1499     EG1PreAttack = _3ewa->ReadUint16();
1500     int32_t eg2decay2 = _3ewa->ReadInt32();
1501     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1502     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1503     _3ewa->ReadInt16(); // unknown
1504     EG2PreAttack = _3ewa->ReadUint16();
1505     uint8_t velocityresponse = _3ewa->ReadUint8();
1506     if (velocityresponse < 5) {
1507     VelocityResponseCurve = curve_type_nonlinear;
1508     VelocityResponseDepth = velocityresponse;
1509     } else if (velocityresponse < 10) {
1510     VelocityResponseCurve = curve_type_linear;
1511     VelocityResponseDepth = velocityresponse - 5;
1512     } else if (velocityresponse < 15) {
1513     VelocityResponseCurve = curve_type_special;
1514     VelocityResponseDepth = velocityresponse - 10;
1515     } else {
1516     VelocityResponseCurve = curve_type_unknown;
1517     VelocityResponseDepth = 0;
1518     }
1519     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1520     if (releasevelocityresponse < 5) {
1521     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1522     ReleaseVelocityResponseDepth = releasevelocityresponse;
1523     } else if (releasevelocityresponse < 10) {
1524     ReleaseVelocityResponseCurve = curve_type_linear;
1525     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1526     } else if (releasevelocityresponse < 15) {
1527     ReleaseVelocityResponseCurve = curve_type_special;
1528     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1529     } else {
1530     ReleaseVelocityResponseCurve = curve_type_unknown;
1531     ReleaseVelocityResponseDepth = 0;
1532     }
1533     VelocityResponseCurveScaling = _3ewa->ReadUint8();
1534     AttenuationControllerThreshold = _3ewa->ReadInt8();
1535     _3ewa->ReadInt32(); // unknown
1536     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1537     _3ewa->ReadInt16(); // unknown
1538     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1539     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1540     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1541     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1542     else DimensionBypass = dim_bypass_ctrl_none;
1543     uint8_t pan = _3ewa->ReadUint8();
1544     Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1545     SelfMask = _3ewa->ReadInt8() & 0x01;
1546     _3ewa->ReadInt8(); // unknown
1547     uint8_t lfo3ctrl = _3ewa->ReadUint8();
1548     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1549     LFO3Sync = lfo3ctrl & 0x20; // bit 5
1550     InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1551     AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1552     uint8_t lfo2ctrl = _3ewa->ReadUint8();
1553     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1554     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1555     LFO2Sync = lfo2ctrl & 0x20; // bit 5
1556     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1557     uint8_t lfo1ctrl = _3ewa->ReadUint8();
1558     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1559     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1560     LFO1Sync = lfo1ctrl & 0x40; // bit 6
1561     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1562     : vcf_res_ctrl_none;
1563     uint16_t eg3depth = _3ewa->ReadUint16();
1564     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1565 persson 2402 : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1566 schoenebeck 809 _3ewa->ReadInt16(); // unknown
1567     ChannelOffset = _3ewa->ReadUint8() / 4;
1568     uint8_t regoptions = _3ewa->ReadUint8();
1569     MSDecode = regoptions & 0x01; // bit 0
1570     SustainDefeat = regoptions & 0x02; // bit 1
1571     _3ewa->ReadInt16(); // unknown
1572     VelocityUpperLimit = _3ewa->ReadInt8();
1573     _3ewa->ReadInt8(); // unknown
1574     _3ewa->ReadInt16(); // unknown
1575     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1576     _3ewa->ReadInt8(); // unknown
1577     _3ewa->ReadInt8(); // unknown
1578     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1579     uint8_t vcfcutoff = _3ewa->ReadUint8();
1580     VCFEnabled = vcfcutoff & 0x80; // bit 7
1581     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1582     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1583     uint8_t vcfvelscale = _3ewa->ReadUint8();
1584     VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1585     VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1586     _3ewa->ReadInt8(); // unknown
1587     uint8_t vcfresonance = _3ewa->ReadUint8();
1588     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1589     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1590     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1591     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1592     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1593     uint8_t vcfvelocity = _3ewa->ReadUint8();
1594     VCFVelocityDynamicRange = vcfvelocity % 5;
1595     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1596     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1597     if (VCFType == vcf_type_lowpass) {
1598     if (lfo3ctrl & 0x40) // bit 6
1599     VCFType = vcf_type_lowpassturbo;
1600     }
1601 persson 1070 if (_3ewa->RemainingBytes() >= 8) {
1602     _3ewa->Read(DimensionUpperLimits, 1, 8);
1603     } else {
1604     memset(DimensionUpperLimits, 0, 8);
1605     }
1606 schoenebeck 809 } else { // '3ewa' chunk does not exist yet
1607     // use default values
1608     LFO3Frequency = 1.0;
1609     EG3Attack = 0.0;
1610     LFO1InternalDepth = 0;
1611     LFO3InternalDepth = 0;
1612     LFO1ControlDepth = 0;
1613     LFO3ControlDepth = 0;
1614     EG1Attack = 0.0;
1615 persson 1218 EG1Decay1 = 0.005;
1616     EG1Sustain = 1000;
1617     EG1Release = 0.3;
1618 schoenebeck 809 EG1Controller.type = eg1_ctrl_t::type_none;
1619     EG1Controller.controller_number = 0;
1620     EG1ControllerInvert = false;
1621     EG1ControllerAttackInfluence = 0;
1622     EG1ControllerDecayInfluence = 0;
1623     EG1ControllerReleaseInfluence = 0;
1624     EG2Controller.type = eg2_ctrl_t::type_none;
1625     EG2Controller.controller_number = 0;
1626     EG2ControllerInvert = false;
1627     EG2ControllerAttackInfluence = 0;
1628     EG2ControllerDecayInfluence = 0;
1629     EG2ControllerReleaseInfluence = 0;
1630     LFO1Frequency = 1.0;
1631     EG2Attack = 0.0;
1632 persson 1218 EG2Decay1 = 0.005;
1633     EG2Sustain = 1000;
1634 schoenebeck 2990 EG2Release = 60;
1635 schoenebeck 809 LFO2ControlDepth = 0;
1636     LFO2Frequency = 1.0;
1637     LFO2InternalDepth = 0;
1638     EG1Decay2 = 0.0;
1639 persson 1218 EG1InfiniteSustain = true;
1640     EG1PreAttack = 0;
1641 schoenebeck 809 EG2Decay2 = 0.0;
1642 persson 1218 EG2InfiniteSustain = true;
1643     EG2PreAttack = 0;
1644 schoenebeck 809 VelocityResponseCurve = curve_type_nonlinear;
1645     VelocityResponseDepth = 3;
1646     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1647     ReleaseVelocityResponseDepth = 3;
1648     VelocityResponseCurveScaling = 32;
1649     AttenuationControllerThreshold = 0;
1650     SampleStartOffset = 0;
1651     PitchTrack = true;
1652     DimensionBypass = dim_bypass_ctrl_none;
1653     Pan = 0;
1654     SelfMask = true;
1655     LFO3Controller = lfo3_ctrl_modwheel;
1656     LFO3Sync = false;
1657     InvertAttenuationController = false;
1658     AttenuationController.type = attenuation_ctrl_t::type_none;
1659     AttenuationController.controller_number = 0;
1660     LFO2Controller = lfo2_ctrl_internal;
1661     LFO2FlipPhase = false;
1662     LFO2Sync = false;
1663     LFO1Controller = lfo1_ctrl_internal;
1664     LFO1FlipPhase = false;
1665     LFO1Sync = false;
1666     VCFResonanceController = vcf_res_ctrl_none;
1667     EG3Depth = 0;
1668     ChannelOffset = 0;
1669     MSDecode = false;
1670     SustainDefeat = false;
1671     VelocityUpperLimit = 0;
1672     ReleaseTriggerDecay = 0;
1673     EG1Hold = false;
1674     VCFEnabled = false;
1675     VCFCutoff = 0;
1676     VCFCutoffController = vcf_cutoff_ctrl_none;
1677     VCFCutoffControllerInvert = false;
1678     VCFVelocityScale = 0;
1679     VCFResonance = 0;
1680     VCFResonanceDynamic = false;
1681     VCFKeyboardTracking = false;
1682     VCFKeyboardTrackingBreakpoint = 0;
1683     VCFVelocityDynamicRange = 0x04;
1684     VCFVelocityCurve = curve_type_linear;
1685     VCFType = vcf_type_lowpass;
1686 persson 1247 memset(DimensionUpperLimits, 127, 8);
1687 schoenebeck 2 }
1688 schoenebeck 16
1689 persson 613 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1690     VelocityResponseDepth,
1691     VelocityResponseCurveScaling);
1692    
1693 schoenebeck 1358 pVelocityReleaseTable = GetReleaseVelocityTable(
1694     ReleaseVelocityResponseCurve,
1695     ReleaseVelocityResponseDepth
1696     );
1697 persson 613
1698 schoenebeck 1358 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1699     VCFVelocityDynamicRange,
1700     VCFVelocityScale,
1701     VCFCutoffController);
1702 persson 613
1703     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1704 persson 858 VelocityTable = 0;
1705 persson 613 }
1706    
1707 persson 1301 /*
1708     * Constructs a DimensionRegion by copying all parameters from
1709     * another DimensionRegion
1710     */
1711     DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1712     Instances++;
1713 schoenebeck 2394 //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1714 persson 1301 *this = src; // default memberwise shallow copy of all parameters
1715     pParentList = _3ewl; // restore the chunk pointer
1716    
1717     // deep copy of owned structures
1718     if (src.VelocityTable) {
1719     VelocityTable = new uint8_t[128];
1720     for (int k = 0 ; k < 128 ; k++)
1721     VelocityTable[k] = src.VelocityTable[k];
1722     }
1723     if (src.pSampleLoops) {
1724     pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1725     for (int k = 0 ; k < src.SampleLoops ; k++)
1726     pSampleLoops[k] = src.pSampleLoops[k];
1727     }
1728     }
1729 schoenebeck 2394
1730     /**
1731     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1732     * and assign it to this object.
1733     *
1734     * Note that all sample pointers referenced by @a orig are simply copied as
1735     * memory address. Thus the respective samples are shared, not duplicated!
1736     *
1737     * @param orig - original DimensionRegion object to be copied from
1738     */
1739     void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1740 schoenebeck 2482 CopyAssign(orig, NULL);
1741     }
1742    
1743     /**
1744     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1745     * and assign it to this object.
1746     *
1747     * @param orig - original DimensionRegion object to be copied from
1748     * @param mSamples - crosslink map between the foreign file's samples and
1749     * this file's samples
1750     */
1751     void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1752 schoenebeck 2394 // delete all allocated data first
1753     if (VelocityTable) delete [] VelocityTable;
1754     if (pSampleLoops) delete [] pSampleLoops;
1755    
1756     // backup parent list pointer
1757     RIFF::List* p = pParentList;
1758    
1759 schoenebeck 2482 gig::Sample* pOriginalSample = pSample;
1760     gig::Region* pOriginalRegion = pRegion;
1761    
1762 schoenebeck 2394 //NOTE: copy code copied from assignment constructor above, see comment there as well
1763    
1764     *this = *orig; // default memberwise shallow copy of all parameters
1765 schoenebeck 2547
1766     // restore members that shall not be altered
1767 schoenebeck 2394 pParentList = p; // restore the chunk pointer
1768 schoenebeck 2547 pRegion = pOriginalRegion;
1769 schoenebeck 2482
1770 schoenebeck 2547 // only take the raw sample reference reference if the
1771 schoenebeck 2482 // two DimensionRegion objects are part of the same file
1772     if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1773     pSample = pOriginalSample;
1774     }
1775    
1776     if (mSamples && mSamples->count(orig->pSample)) {
1777     pSample = mSamples->find(orig->pSample)->second;
1778     }
1779 persson 1301
1780 schoenebeck 2394 // deep copy of owned structures
1781     if (orig->VelocityTable) {
1782     VelocityTable = new uint8_t[128];
1783     for (int k = 0 ; k < 128 ; k++)
1784     VelocityTable[k] = orig->VelocityTable[k];
1785     }
1786     if (orig->pSampleLoops) {
1787     pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1788     for (int k = 0 ; k < orig->SampleLoops ; k++)
1789     pSampleLoops[k] = orig->pSampleLoops[k];
1790     }
1791     }
1792    
1793 schoenebeck 809 /**
1794 schoenebeck 1358 * Updates the respective member variable and updates @c SampleAttenuation
1795     * which depends on this value.
1796     */
1797     void DimensionRegion::SetGain(int32_t gain) {
1798     DLS::Sampler::SetGain(gain);
1799     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1800     }
1801    
1802     /**
1803 schoenebeck 809 * Apply dimension region settings to the respective RIFF chunks. You
1804     * have to call File::Save() to make changes persistent.
1805     *
1806     * Usually there is absolutely no need to call this method explicitly.
1807     * It will be called automatically when File::Save() was called.
1808 schoenebeck 2682 *
1809     * @param pProgress - callback function for progress notification
1810 schoenebeck 809 */
1811 schoenebeck 2682 void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1812 schoenebeck 809 // first update base class's chunk
1813 schoenebeck 2682 DLS::Sampler::UpdateChunks(pProgress);
1814 schoenebeck 809
1815 persson 1247 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1816     uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1817     pData[12] = Crossfade.in_start;
1818     pData[13] = Crossfade.in_end;
1819     pData[14] = Crossfade.out_start;
1820     pData[15] = Crossfade.out_end;
1821    
1822 schoenebeck 809 // make sure '3ewa' chunk exists
1823     RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1824 persson 1317 if (!_3ewa) {
1825     File* pFile = (File*) GetParent()->GetParent()->GetParent();
1826     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1827     _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1828 persson 1264 }
1829 persson 1247 pData = (uint8_t*) _3ewa->LoadChunkData();
1830 schoenebeck 809
1831     // update '3ewa' chunk with DimensionRegion's current settings
1832    
1833 schoenebeck 3053 const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1834 persson 1179 store32(&pData[0], chunksize); // unknown, always chunk size?
1835 schoenebeck 809
1836     const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1837 persson 1179 store32(&pData[4], lfo3freq);
1838 schoenebeck 809
1839     const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1840 persson 1179 store32(&pData[8], eg3attack);
1841 schoenebeck 809
1842     // next 2 bytes unknown
1843    
1844 persson 1179 store16(&pData[14], LFO1InternalDepth);
1845 schoenebeck 809
1846     // next 2 bytes unknown
1847    
1848 persson 1179 store16(&pData[18], LFO3InternalDepth);
1849 schoenebeck 809
1850     // next 2 bytes unknown
1851    
1852 persson 1179 store16(&pData[22], LFO1ControlDepth);
1853 schoenebeck 809
1854     // next 2 bytes unknown
1855    
1856 persson 1179 store16(&pData[26], LFO3ControlDepth);
1857 schoenebeck 809
1858     const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1859 persson 1179 store32(&pData[28], eg1attack);
1860 schoenebeck 809
1861     const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1862 persson 1179 store32(&pData[32], eg1decay1);
1863 schoenebeck 809
1864     // next 2 bytes unknown
1865    
1866 persson 1179 store16(&pData[38], EG1Sustain);
1867 schoenebeck 809
1868     const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1869 persson 1179 store32(&pData[40], eg1release);
1870 schoenebeck 809
1871     const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1872 persson 1179 pData[44] = eg1ctl;
1873 schoenebeck 809
1874     const uint8_t eg1ctrloptions =
1875 persson 1266 (EG1ControllerInvert ? 0x01 : 0x00) |
1876 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1877     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1878     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1879 persson 1179 pData[45] = eg1ctrloptions;
1880 schoenebeck 809
1881     const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1882 persson 1179 pData[46] = eg2ctl;
1883 schoenebeck 809
1884     const uint8_t eg2ctrloptions =
1885 persson 1266 (EG2ControllerInvert ? 0x01 : 0x00) |
1886 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1887     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1888     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1889 persson 1179 pData[47] = eg2ctrloptions;
1890 schoenebeck 809
1891     const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1892 persson 1179 store32(&pData[48], lfo1freq);
1893 schoenebeck 809
1894     const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1895 persson 1179 store32(&pData[52], eg2attack);
1896 schoenebeck 809
1897     const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1898 persson 1179 store32(&pData[56], eg2decay1);
1899 schoenebeck 809
1900     // next 2 bytes unknown
1901    
1902 persson 1179 store16(&pData[62], EG2Sustain);
1903 schoenebeck 809
1904     const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1905 persson 1179 store32(&pData[64], eg2release);
1906 schoenebeck 809
1907     // next 2 bytes unknown
1908    
1909 persson 1179 store16(&pData[70], LFO2ControlDepth);
1910 schoenebeck 809
1911     const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1912 persson 1179 store32(&pData[72], lfo2freq);
1913 schoenebeck 809
1914     // next 2 bytes unknown
1915    
1916 persson 1179 store16(&pData[78], LFO2InternalDepth);
1917 schoenebeck 809
1918     const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1919 persson 1179 store32(&pData[80], eg1decay2);
1920 schoenebeck 809
1921     // next 2 bytes unknown
1922    
1923 persson 1179 store16(&pData[86], EG1PreAttack);
1924 schoenebeck 809
1925     const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1926 persson 1179 store32(&pData[88], eg2decay2);
1927 schoenebeck 809
1928     // next 2 bytes unknown
1929    
1930 persson 1179 store16(&pData[94], EG2PreAttack);
1931 schoenebeck 809
1932     {
1933     if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1934     uint8_t velocityresponse = VelocityResponseDepth;
1935     switch (VelocityResponseCurve) {
1936     case curve_type_nonlinear:
1937     break;
1938     case curve_type_linear:
1939     velocityresponse += 5;
1940     break;
1941     case curve_type_special:
1942     velocityresponse += 10;
1943     break;
1944     case curve_type_unknown:
1945     default:
1946     throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1947     }
1948 persson 1179 pData[96] = velocityresponse;
1949 schoenebeck 809 }
1950    
1951     {
1952     if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1953     uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1954     switch (ReleaseVelocityResponseCurve) {
1955     case curve_type_nonlinear:
1956     break;
1957     case curve_type_linear:
1958     releasevelocityresponse += 5;
1959     break;
1960     case curve_type_special:
1961     releasevelocityresponse += 10;
1962     break;
1963     case curve_type_unknown:
1964     default:
1965     throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1966     }
1967 persson 1179 pData[97] = releasevelocityresponse;
1968 schoenebeck 809 }
1969    
1970 persson 1179 pData[98] = VelocityResponseCurveScaling;
1971 schoenebeck 809
1972 persson 1179 pData[99] = AttenuationControllerThreshold;
1973 schoenebeck 809
1974     // next 4 bytes unknown
1975    
1976 persson 1179 store16(&pData[104], SampleStartOffset);
1977 schoenebeck 809
1978     // next 2 bytes unknown
1979    
1980     {
1981     uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1982     switch (DimensionBypass) {
1983     case dim_bypass_ctrl_94:
1984     pitchTrackDimensionBypass |= 0x10;
1985     break;
1986     case dim_bypass_ctrl_95:
1987     pitchTrackDimensionBypass |= 0x20;
1988     break;
1989     case dim_bypass_ctrl_none:
1990     //FIXME: should we set anything here?
1991     break;
1992     default:
1993     throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1994     }
1995 persson 1179 pData[108] = pitchTrackDimensionBypass;
1996 schoenebeck 809 }
1997    
1998     const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1999 persson 1179 pData[109] = pan;
2000 schoenebeck 809
2001     const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
2002 persson 1179 pData[110] = selfmask;
2003 schoenebeck 809
2004     // next byte unknown
2005    
2006     {
2007     uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
2008     if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
2009     if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
2010     if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
2011 persson 1179 pData[112] = lfo3ctrl;
2012 schoenebeck 809 }
2013    
2014     const uint8_t attenctl = EncodeLeverageController(AttenuationController);
2015 persson 1179 pData[113] = attenctl;
2016 schoenebeck 809
2017     {
2018     uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
2019     if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
2020     if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
2021     if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
2022 persson 1179 pData[114] = lfo2ctrl;
2023 schoenebeck 809 }
2024    
2025     {
2026     uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
2027     if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
2028     if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
2029     if (VCFResonanceController != vcf_res_ctrl_none)
2030     lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
2031 persson 1179 pData[115] = lfo1ctrl;
2032 schoenebeck 809 }
2033    
2034     const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2035 persson 2402 : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2036 persson 1869 store16(&pData[116], eg3depth);
2037 schoenebeck 809
2038     // next 2 bytes unknown
2039    
2040     const uint8_t channeloffset = ChannelOffset * 4;
2041 persson 1179 pData[120] = channeloffset;
2042 schoenebeck 809
2043     {
2044     uint8_t regoptions = 0;
2045     if (MSDecode) regoptions |= 0x01; // bit 0
2046     if (SustainDefeat) regoptions |= 0x02; // bit 1
2047 persson 1179 pData[121] = regoptions;
2048 schoenebeck 809 }
2049    
2050     // next 2 bytes unknown
2051    
2052 persson 1179 pData[124] = VelocityUpperLimit;
2053 schoenebeck 809
2054     // next 3 bytes unknown
2055    
2056 persson 1179 pData[128] = ReleaseTriggerDecay;
2057 schoenebeck 809
2058     // next 2 bytes unknown
2059    
2060     const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2061 persson 1179 pData[131] = eg1hold;
2062 schoenebeck 809
2063 persson 1266 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2064 persson 918 (VCFCutoff & 0x7f); /* lower 7 bits */
2065 persson 1179 pData[132] = vcfcutoff;
2066 schoenebeck 809
2067 persson 1179 pData[133] = VCFCutoffController;
2068 schoenebeck 809
2069 persson 1266 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2070 persson 918 (VCFVelocityScale & 0x7f); /* lower 7 bits */
2071 persson 1179 pData[134] = vcfvelscale;
2072 schoenebeck 809
2073     // next byte unknown
2074    
2075 persson 1266 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2076 persson 918 (VCFResonance & 0x7f); /* lower 7 bits */
2077 persson 1179 pData[136] = vcfresonance;
2078 schoenebeck 809
2079 persson 1266 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2080 persson 918 (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2081 persson 1179 pData[137] = vcfbreakpoint;
2082 schoenebeck 809
2083 persson 2152 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2084 schoenebeck 809 VCFVelocityCurve * 5;
2085 persson 1179 pData[138] = vcfvelocity;
2086 schoenebeck 809
2087     const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2088 persson 1179 pData[139] = vcftype;
2089 persson 1070
2090     if (chunksize >= 148) {
2091     memcpy(&pData[140], DimensionUpperLimits, 8);
2092     }
2093 schoenebeck 809 }
2094    
2095 schoenebeck 1358 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2096     curve_type_t curveType = releaseVelocityResponseCurve;
2097     uint8_t depth = releaseVelocityResponseDepth;
2098     // this models a strange behaviour or bug in GSt: two of the
2099     // velocity response curves for release time are not used even
2100     // if specified, instead another curve is chosen.
2101     if ((curveType == curve_type_nonlinear && depth == 0) ||
2102     (curveType == curve_type_special && depth == 4)) {
2103     curveType = curve_type_nonlinear;
2104     depth = 3;
2105     }
2106     return GetVelocityTable(curveType, depth, 0);
2107     }
2108    
2109     double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2110     uint8_t vcfVelocityDynamicRange,
2111     uint8_t vcfVelocityScale,
2112     vcf_cutoff_ctrl_t vcfCutoffController)
2113     {
2114     curve_type_t curveType = vcfVelocityCurve;
2115     uint8_t depth = vcfVelocityDynamicRange;
2116     // even stranger GSt: two of the velocity response curves for
2117     // filter cutoff are not used, instead another special curve
2118     // is chosen. This curve is not used anywhere else.
2119     if ((curveType == curve_type_nonlinear && depth == 0) ||
2120     (curveType == curve_type_special && depth == 4)) {
2121     curveType = curve_type_special;
2122     depth = 5;
2123     }
2124     return GetVelocityTable(curveType, depth,
2125     (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2126     ? vcfVelocityScale : 0);
2127     }
2128    
2129 persson 613 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2130     double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2131     {
2132     double* table;
2133     uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2134 schoenebeck 16 if (pVelocityTables->count(tableKey)) { // if key exists
2135 persson 613 table = (*pVelocityTables)[tableKey];
2136 schoenebeck 16 }
2137     else {
2138 persson 613 table = CreateVelocityTable(curveType, depth, scaling);
2139     (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2140 schoenebeck 16 }
2141 persson 613 return table;
2142 schoenebeck 2 }
2143 schoenebeck 55
2144 schoenebeck 1316 Region* DimensionRegion::GetParent() const {
2145     return pRegion;
2146     }
2147    
2148 schoenebeck 2540 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2149     // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2150     // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2151     //#pragma GCC diagnostic push
2152     //#pragma GCC diagnostic error "-Wswitch"
2153    
2154 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2155     leverage_ctrl_t decodedcontroller;
2156     switch (EncodedController) {
2157     // special controller
2158     case _lev_ctrl_none:
2159     decodedcontroller.type = leverage_ctrl_t::type_none;
2160     decodedcontroller.controller_number = 0;
2161     break;
2162     case _lev_ctrl_velocity:
2163     decodedcontroller.type = leverage_ctrl_t::type_velocity;
2164     decodedcontroller.controller_number = 0;
2165     break;
2166     case _lev_ctrl_channelaftertouch:
2167     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2168     decodedcontroller.controller_number = 0;
2169     break;
2170 schoenebeck 55
2171 schoenebeck 36 // ordinary MIDI control change controller
2172     case _lev_ctrl_modwheel:
2173     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2174     decodedcontroller.controller_number = 1;
2175     break;
2176     case _lev_ctrl_breath:
2177     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178     decodedcontroller.controller_number = 2;
2179     break;
2180     case _lev_ctrl_foot:
2181     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2182     decodedcontroller.controller_number = 4;
2183     break;
2184     case _lev_ctrl_effect1:
2185     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186     decodedcontroller.controller_number = 12;
2187     break;
2188     case _lev_ctrl_effect2:
2189     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190     decodedcontroller.controller_number = 13;
2191     break;
2192     case _lev_ctrl_genpurpose1:
2193     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194     decodedcontroller.controller_number = 16;
2195     break;
2196     case _lev_ctrl_genpurpose2:
2197     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198     decodedcontroller.controller_number = 17;
2199     break;
2200     case _lev_ctrl_genpurpose3:
2201     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202     decodedcontroller.controller_number = 18;
2203     break;
2204     case _lev_ctrl_genpurpose4:
2205     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206     decodedcontroller.controller_number = 19;
2207     break;
2208     case _lev_ctrl_portamentotime:
2209     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2210     decodedcontroller.controller_number = 5;
2211     break;
2212     case _lev_ctrl_sustainpedal:
2213     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214     decodedcontroller.controller_number = 64;
2215     break;
2216     case _lev_ctrl_portamento:
2217     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218     decodedcontroller.controller_number = 65;
2219     break;
2220     case _lev_ctrl_sostenutopedal:
2221     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222     decodedcontroller.controller_number = 66;
2223     break;
2224     case _lev_ctrl_softpedal:
2225     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226     decodedcontroller.controller_number = 67;
2227     break;
2228     case _lev_ctrl_genpurpose5:
2229     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230     decodedcontroller.controller_number = 80;
2231     break;
2232     case _lev_ctrl_genpurpose6:
2233     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234     decodedcontroller.controller_number = 81;
2235     break;
2236     case _lev_ctrl_genpurpose7:
2237     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238     decodedcontroller.controller_number = 82;
2239     break;
2240     case _lev_ctrl_genpurpose8:
2241     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242     decodedcontroller.controller_number = 83;
2243     break;
2244     case _lev_ctrl_effect1depth:
2245     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246     decodedcontroller.controller_number = 91;
2247     break;
2248     case _lev_ctrl_effect2depth:
2249     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250     decodedcontroller.controller_number = 92;
2251     break;
2252     case _lev_ctrl_effect3depth:
2253     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254     decodedcontroller.controller_number = 93;
2255     break;
2256     case _lev_ctrl_effect4depth:
2257     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258     decodedcontroller.controller_number = 94;
2259     break;
2260     case _lev_ctrl_effect5depth:
2261     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262     decodedcontroller.controller_number = 95;
2263     break;
2264 schoenebeck 55
2265 schoenebeck 2540 // format extension (these controllers are so far only supported by
2266     // LinuxSampler & gigedit) they will *NOT* work with
2267     // Gigasampler/GigaStudio !
2268     case _lev_ctrl_CC3_EXT:
2269     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270     decodedcontroller.controller_number = 3;
2271     break;
2272     case _lev_ctrl_CC6_EXT:
2273     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274     decodedcontroller.controller_number = 6;
2275     break;
2276     case _lev_ctrl_CC7_EXT:
2277     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278     decodedcontroller.controller_number = 7;
2279     break;
2280     case _lev_ctrl_CC8_EXT:
2281     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282     decodedcontroller.controller_number = 8;
2283     break;
2284     case _lev_ctrl_CC9_EXT:
2285     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286     decodedcontroller.controller_number = 9;
2287     break;
2288     case _lev_ctrl_CC10_EXT:
2289     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290     decodedcontroller.controller_number = 10;
2291     break;
2292     case _lev_ctrl_CC11_EXT:
2293     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294     decodedcontroller.controller_number = 11;
2295     break;
2296     case _lev_ctrl_CC14_EXT:
2297     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298     decodedcontroller.controller_number = 14;
2299     break;
2300     case _lev_ctrl_CC15_EXT:
2301     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302     decodedcontroller.controller_number = 15;
2303     break;
2304     case _lev_ctrl_CC20_EXT:
2305     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306     decodedcontroller.controller_number = 20;
2307     break;
2308     case _lev_ctrl_CC21_EXT:
2309     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310     decodedcontroller.controller_number = 21;
2311     break;
2312     case _lev_ctrl_CC22_EXT:
2313     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314     decodedcontroller.controller_number = 22;
2315     break;
2316     case _lev_ctrl_CC23_EXT:
2317     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318     decodedcontroller.controller_number = 23;
2319     break;
2320     case _lev_ctrl_CC24_EXT:
2321     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322     decodedcontroller.controller_number = 24;
2323     break;
2324     case _lev_ctrl_CC25_EXT:
2325     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326     decodedcontroller.controller_number = 25;
2327     break;
2328     case _lev_ctrl_CC26_EXT:
2329     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330     decodedcontroller.controller_number = 26;
2331     break;
2332     case _lev_ctrl_CC27_EXT:
2333     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334     decodedcontroller.controller_number = 27;
2335     break;
2336     case _lev_ctrl_CC28_EXT:
2337     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338     decodedcontroller.controller_number = 28;
2339     break;
2340     case _lev_ctrl_CC29_EXT:
2341     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342     decodedcontroller.controller_number = 29;
2343     break;
2344     case _lev_ctrl_CC30_EXT:
2345     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346     decodedcontroller.controller_number = 30;
2347     break;
2348     case _lev_ctrl_CC31_EXT:
2349     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350     decodedcontroller.controller_number = 31;
2351     break;
2352     case _lev_ctrl_CC68_EXT:
2353     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354     decodedcontroller.controller_number = 68;
2355     break;
2356     case _lev_ctrl_CC69_EXT:
2357     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358     decodedcontroller.controller_number = 69;
2359     break;
2360     case _lev_ctrl_CC70_EXT:
2361     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362     decodedcontroller.controller_number = 70;
2363     break;
2364     case _lev_ctrl_CC71_EXT:
2365     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366     decodedcontroller.controller_number = 71;
2367     break;
2368     case _lev_ctrl_CC72_EXT:
2369     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370     decodedcontroller.controller_number = 72;
2371     break;
2372     case _lev_ctrl_CC73_EXT:
2373     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374     decodedcontroller.controller_number = 73;
2375     break;
2376     case _lev_ctrl_CC74_EXT:
2377     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378     decodedcontroller.controller_number = 74;
2379     break;
2380     case _lev_ctrl_CC75_EXT:
2381     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382     decodedcontroller.controller_number = 75;
2383     break;
2384     case _lev_ctrl_CC76_EXT:
2385     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386     decodedcontroller.controller_number = 76;
2387     break;
2388     case _lev_ctrl_CC77_EXT:
2389     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390     decodedcontroller.controller_number = 77;
2391     break;
2392     case _lev_ctrl_CC78_EXT:
2393     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394     decodedcontroller.controller_number = 78;
2395     break;
2396     case _lev_ctrl_CC79_EXT:
2397     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398     decodedcontroller.controller_number = 79;
2399     break;
2400     case _lev_ctrl_CC84_EXT:
2401     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402     decodedcontroller.controller_number = 84;
2403     break;
2404     case _lev_ctrl_CC85_EXT:
2405     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406     decodedcontroller.controller_number = 85;
2407     break;
2408     case _lev_ctrl_CC86_EXT:
2409     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410     decodedcontroller.controller_number = 86;
2411     break;
2412     case _lev_ctrl_CC87_EXT:
2413     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414     decodedcontroller.controller_number = 87;
2415     break;
2416     case _lev_ctrl_CC89_EXT:
2417     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418     decodedcontroller.controller_number = 89;
2419     break;
2420     case _lev_ctrl_CC90_EXT:
2421     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2422     decodedcontroller.controller_number = 90;
2423     break;
2424     case _lev_ctrl_CC96_EXT:
2425     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2426     decodedcontroller.controller_number = 96;
2427     break;
2428     case _lev_ctrl_CC97_EXT:
2429     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2430     decodedcontroller.controller_number = 97;
2431     break;
2432     case _lev_ctrl_CC102_EXT:
2433     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2434     decodedcontroller.controller_number = 102;
2435     break;
2436     case _lev_ctrl_CC103_EXT:
2437     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2438     decodedcontroller.controller_number = 103;
2439     break;
2440     case _lev_ctrl_CC104_EXT:
2441     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2442     decodedcontroller.controller_number = 104;
2443     break;
2444     case _lev_ctrl_CC105_EXT:
2445     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2446     decodedcontroller.controller_number = 105;
2447     break;
2448     case _lev_ctrl_CC106_EXT:
2449     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2450     decodedcontroller.controller_number = 106;
2451     break;
2452     case _lev_ctrl_CC107_EXT:
2453     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2454     decodedcontroller.controller_number = 107;
2455     break;
2456     case _lev_ctrl_CC108_EXT:
2457     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2458     decodedcontroller.controller_number = 108;
2459     break;
2460     case _lev_ctrl_CC109_EXT:
2461     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2462     decodedcontroller.controller_number = 109;
2463     break;
2464     case _lev_ctrl_CC110_EXT:
2465     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2466     decodedcontroller.controller_number = 110;
2467     break;
2468     case _lev_ctrl_CC111_EXT:
2469     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2470     decodedcontroller.controller_number = 111;
2471     break;
2472     case _lev_ctrl_CC112_EXT:
2473     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2474     decodedcontroller.controller_number = 112;
2475     break;
2476     case _lev_ctrl_CC113_EXT:
2477     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2478     decodedcontroller.controller_number = 113;
2479     break;
2480     case _lev_ctrl_CC114_EXT:
2481     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2482     decodedcontroller.controller_number = 114;
2483     break;
2484     case _lev_ctrl_CC115_EXT:
2485     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2486     decodedcontroller.controller_number = 115;
2487     break;
2488     case _lev_ctrl_CC116_EXT:
2489     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2490     decodedcontroller.controller_number = 116;
2491     break;
2492     case _lev_ctrl_CC117_EXT:
2493     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2494     decodedcontroller.controller_number = 117;
2495     break;
2496     case _lev_ctrl_CC118_EXT:
2497     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2498     decodedcontroller.controller_number = 118;
2499     break;
2500     case _lev_ctrl_CC119_EXT:
2501     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2502     decodedcontroller.controller_number = 119;
2503     break;
2504    
2505 schoenebeck 36 // unknown controller type
2506     default:
2507     throw gig::Exception("Unknown leverage controller type.");
2508     }
2509     return decodedcontroller;
2510     }
2511 schoenebeck 2540
2512     // see above (diagnostic push not supported prior GCC 4.6)
2513     //#pragma GCC diagnostic pop
2514 schoenebeck 2
2515 schoenebeck 809 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2516     _lev_ctrl_t encodedcontroller;
2517     switch (DecodedController.type) {
2518     // special controller
2519     case leverage_ctrl_t::type_none:
2520     encodedcontroller = _lev_ctrl_none;
2521     break;
2522     case leverage_ctrl_t::type_velocity:
2523     encodedcontroller = _lev_ctrl_velocity;
2524     break;
2525     case leverage_ctrl_t::type_channelaftertouch:
2526     encodedcontroller = _lev_ctrl_channelaftertouch;
2527     break;
2528    
2529     // ordinary MIDI control change controller
2530     case leverage_ctrl_t::type_controlchange:
2531     switch (DecodedController.controller_number) {
2532     case 1:
2533     encodedcontroller = _lev_ctrl_modwheel;
2534     break;
2535     case 2:
2536     encodedcontroller = _lev_ctrl_breath;
2537     break;
2538     case 4:
2539     encodedcontroller = _lev_ctrl_foot;
2540     break;
2541     case 12:
2542     encodedcontroller = _lev_ctrl_effect1;
2543     break;
2544     case 13:
2545     encodedcontroller = _lev_ctrl_effect2;
2546     break;
2547     case 16:
2548     encodedcontroller = _lev_ctrl_genpurpose1;
2549     break;
2550     case 17:
2551     encodedcontroller = _lev_ctrl_genpurpose2;
2552     break;
2553     case 18:
2554     encodedcontroller = _lev_ctrl_genpurpose3;
2555     break;
2556     case 19:
2557     encodedcontroller = _lev_ctrl_genpurpose4;
2558     break;
2559     case 5:
2560     encodedcontroller = _lev_ctrl_portamentotime;
2561     break;
2562     case 64:
2563     encodedcontroller = _lev_ctrl_sustainpedal;
2564     break;
2565     case 65:
2566     encodedcontroller = _lev_ctrl_portamento;
2567     break;
2568     case 66:
2569     encodedcontroller = _lev_ctrl_sostenutopedal;
2570     break;
2571     case 67:
2572     encodedcontroller = _lev_ctrl_softpedal;
2573     break;
2574     case 80:
2575     encodedcontroller = _lev_ctrl_genpurpose5;
2576     break;
2577     case 81:
2578     encodedcontroller = _lev_ctrl_genpurpose6;
2579     break;
2580     case 82:
2581     encodedcontroller = _lev_ctrl_genpurpose7;
2582     break;
2583     case 83:
2584     encodedcontroller = _lev_ctrl_genpurpose8;
2585     break;
2586     case 91:
2587     encodedcontroller = _lev_ctrl_effect1depth;
2588     break;
2589     case 92:
2590     encodedcontroller = _lev_ctrl_effect2depth;
2591     break;
2592     case 93:
2593     encodedcontroller = _lev_ctrl_effect3depth;
2594     break;
2595     case 94:
2596     encodedcontroller = _lev_ctrl_effect4depth;
2597     break;
2598     case 95:
2599     encodedcontroller = _lev_ctrl_effect5depth;
2600     break;
2601 schoenebeck 2540
2602     // format extension (these controllers are so far only
2603     // supported by LinuxSampler & gigedit) they will *NOT*
2604     // work with Gigasampler/GigaStudio !
2605     case 3:
2606     encodedcontroller = _lev_ctrl_CC3_EXT;
2607     break;
2608     case 6:
2609     encodedcontroller = _lev_ctrl_CC6_EXT;
2610     break;
2611     case 7:
2612     encodedcontroller = _lev_ctrl_CC7_EXT;
2613     break;
2614     case 8:
2615     encodedcontroller = _lev_ctrl_CC8_EXT;
2616     break;
2617     case 9:
2618     encodedcontroller = _lev_ctrl_CC9_EXT;
2619     break;
2620     case 10:
2621     encodedcontroller = _lev_ctrl_CC10_EXT;
2622     break;
2623     case 11:
2624     encodedcontroller = _lev_ctrl_CC11_EXT;
2625     break;
2626     case 14:
2627     encodedcontroller = _lev_ctrl_CC14_EXT;
2628     break;
2629     case 15:
2630     encodedcontroller = _lev_ctrl_CC15_EXT;
2631     break;
2632     case 20:
2633     encodedcontroller = _lev_ctrl_CC20_EXT;
2634     break;
2635     case 21:
2636     encodedcontroller = _lev_ctrl_CC21_EXT;
2637     break;
2638     case 22:
2639     encodedcontroller = _lev_ctrl_CC22_EXT;
2640     break;
2641     case 23:
2642     encodedcontroller = _lev_ctrl_CC23_EXT;
2643     break;
2644     case 24:
2645     encodedcontroller = _lev_ctrl_CC24_EXT;
2646     break;
2647     case 25:
2648     encodedcontroller = _lev_ctrl_CC25_EXT;
2649     break;
2650     case 26:
2651     encodedcontroller = _lev_ctrl_CC26_EXT;
2652     break;
2653     case 27:
2654     encodedcontroller = _lev_ctrl_CC27_EXT;
2655     break;
2656     case 28:
2657     encodedcontroller = _lev_ctrl_CC28_EXT;
2658     break;
2659     case 29:
2660     encodedcontroller = _lev_ctrl_CC29_EXT;
2661     break;
2662     case 30:
2663     encodedcontroller = _lev_ctrl_CC30_EXT;
2664     break;
2665     case 31:
2666     encodedcontroller = _lev_ctrl_CC31_EXT;
2667     break;
2668     case 68:
2669     encodedcontroller = _lev_ctrl_CC68_EXT;
2670     break;
2671     case 69:
2672     encodedcontroller = _lev_ctrl_CC69_EXT;
2673     break;
2674     case 70:
2675     encodedcontroller = _lev_ctrl_CC70_EXT;
2676     break;
2677     case 71:
2678     encodedcontroller = _lev_ctrl_CC71_EXT;
2679     break;
2680     case 72:
2681     encodedcontroller = _lev_ctrl_CC72_EXT;
2682     break;
2683     case 73:
2684     encodedcontroller = _lev_ctrl_CC73_EXT;
2685     break;
2686     case 74:
2687     encodedcontroller = _lev_ctrl_CC74_EXT;
2688     break;
2689     case 75:
2690     encodedcontroller = _lev_ctrl_CC75_EXT;
2691     break;
2692     case 76:
2693     encodedcontroller = _lev_ctrl_CC76_EXT;
2694     break;
2695     case 77:
2696     encodedcontroller = _lev_ctrl_CC77_EXT;
2697     break;
2698     case 78:
2699     encodedcontroller = _lev_ctrl_CC78_EXT;
2700     break;
2701     case 79:
2702     encodedcontroller = _lev_ctrl_CC79_EXT;
2703     break;
2704     case 84:
2705     encodedcontroller = _lev_ctrl_CC84_EXT;
2706     break;
2707     case 85:
2708     encodedcontroller = _lev_ctrl_CC85_EXT;
2709     break;
2710     case 86:
2711     encodedcontroller = _lev_ctrl_CC86_EXT;
2712     break;
2713     case 87:
2714     encodedcontroller = _lev_ctrl_CC87_EXT;
2715     break;
2716     case 89:
2717     encodedcontroller = _lev_ctrl_CC89_EXT;
2718     break;
2719     case 90:
2720     encodedcontroller = _lev_ctrl_CC90_EXT;
2721     break;
2722     case 96:
2723     encodedcontroller = _lev_ctrl_CC96_EXT;
2724     break;
2725     case 97:
2726     encodedcontroller = _lev_ctrl_CC97_EXT;
2727     break;
2728     case 102:
2729     encodedcontroller = _lev_ctrl_CC102_EXT;
2730     break;
2731     case 103:
2732     encodedcontroller = _lev_ctrl_CC103_EXT;
2733     break;
2734     case 104:
2735     encodedcontroller = _lev_ctrl_CC104_EXT;
2736     break;
2737     case 105:
2738     encodedcontroller = _lev_ctrl_CC105_EXT;
2739     break;
2740     case 106:
2741     encodedcontroller = _lev_ctrl_CC106_EXT;
2742     break;
2743     case 107:
2744     encodedcontroller = _lev_ctrl_CC107_EXT;
2745     break;
2746     case 108:
2747     encodedcontroller = _lev_ctrl_CC108_EXT;
2748     break;
2749     case 109:
2750     encodedcontroller = _lev_ctrl_CC109_EXT;
2751     break;
2752     case 110:
2753     encodedcontroller = _lev_ctrl_CC110_EXT;
2754     break;
2755     case 111:
2756     encodedcontroller = _lev_ctrl_CC111_EXT;
2757     break;
2758     case 112:
2759     encodedcontroller = _lev_ctrl_CC112_EXT;
2760     break;
2761     case 113:
2762     encodedcontroller = _lev_ctrl_CC113_EXT;
2763     break;
2764     case 114:
2765     encodedcontroller = _lev_ctrl_CC114_EXT;
2766     break;
2767     case 115:
2768     encodedcontroller = _lev_ctrl_CC115_EXT;
2769     break;
2770     case 116:
2771     encodedcontroller = _lev_ctrl_CC116_EXT;
2772     break;
2773     case 117:
2774     encodedcontroller = _lev_ctrl_CC117_EXT;
2775     break;
2776     case 118:
2777     encodedcontroller = _lev_ctrl_CC118_EXT;
2778     break;
2779     case 119:
2780     encodedcontroller = _lev_ctrl_CC119_EXT;
2781     break;
2782    
2783 schoenebeck 809 default:
2784     throw gig::Exception("leverage controller number is not supported by the gig format");
2785     }
2786 persson 1182 break;
2787 schoenebeck 809 default:
2788     throw gig::Exception("Unknown leverage controller type.");
2789     }
2790     return encodedcontroller;
2791     }
2792    
2793 schoenebeck 16 DimensionRegion::~DimensionRegion() {
2794     Instances--;
2795     if (!Instances) {
2796     // delete the velocity->volume tables
2797     VelocityTableMap::iterator iter;
2798     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2799     double* pTable = iter->second;
2800     if (pTable) delete[] pTable;
2801     }
2802     pVelocityTables->clear();
2803     delete pVelocityTables;
2804     pVelocityTables = NULL;
2805     }
2806 persson 858 if (VelocityTable) delete[] VelocityTable;
2807 schoenebeck 16 }
2808 schoenebeck 2
2809 schoenebeck 16 /**
2810     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
2811     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
2812     * and VelocityResponseCurveScaling) involved are taken into account to
2813     * calculate the amplitude factor. Use this method when a key was
2814     * triggered to get the volume with which the sample should be played
2815     * back.
2816     *
2817 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
2818     * @returns amplitude factor (between 0.0 and 1.0)
2819 schoenebeck 16 */
2820     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2821     return pVelocityAttenuationTable[MIDIKeyVelocity];
2822     }
2823 schoenebeck 2
2824 persson 613 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2825     return pVelocityReleaseTable[MIDIKeyVelocity];
2826     }
2827    
2828 persson 728 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2829     return pVelocityCutoffTable[MIDIKeyVelocity];
2830     }
2831    
2832 schoenebeck 1358 /**
2833     * Updates the respective member variable and the lookup table / cache
2834     * that depends on this value.
2835     */
2836     void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2837     pVelocityAttenuationTable =
2838     GetVelocityTable(
2839     curve, VelocityResponseDepth, VelocityResponseCurveScaling
2840     );
2841     VelocityResponseCurve = curve;
2842     }
2843    
2844     /**
2845     * Updates the respective member variable and the lookup table / cache
2846     * that depends on this value.
2847     */
2848     void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2849     pVelocityAttenuationTable =
2850     GetVelocityTable(
2851     VelocityResponseCurve, depth, VelocityResponseCurveScaling
2852     );
2853     VelocityResponseDepth = depth;
2854     }
2855    
2856     /**
2857     * Updates the respective member variable and the lookup table / cache
2858     * that depends on this value.
2859     */
2860     void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2861     pVelocityAttenuationTable =
2862     GetVelocityTable(
2863     VelocityResponseCurve, VelocityResponseDepth, scaling
2864     );
2865     VelocityResponseCurveScaling = scaling;
2866     }
2867    
2868     /**
2869     * Updates the respective member variable and the lookup table / cache
2870     * that depends on this value.
2871     */
2872     void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2873     pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2874     ReleaseVelocityResponseCurve = curve;
2875     }
2876    
2877     /**
2878     * Updates the respective member variable and the lookup table / cache
2879     * that depends on this value.
2880     */
2881     void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2882     pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2883     ReleaseVelocityResponseDepth = depth;
2884     }
2885    
2886     /**
2887     * Updates the respective member variable and the lookup table / cache
2888     * that depends on this value.
2889     */
2890     void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2891     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2892     VCFCutoffController = controller;
2893     }
2894    
2895     /**
2896     * Updates the respective member variable and the lookup table / cache
2897     * that depends on this value.
2898     */
2899     void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2900     pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2901     VCFVelocityCurve = curve;
2902     }
2903    
2904     /**
2905     * Updates the respective member variable and the lookup table / cache
2906     * that depends on this value.
2907     */
2908     void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2909     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2910     VCFVelocityDynamicRange = range;
2911     }
2912    
2913     /**
2914     * Updates the respective member variable and the lookup table / cache
2915     * that depends on this value.
2916     */
2917     void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2918     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2919     VCFVelocityScale = scaling;
2920     }
2921    
2922 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2923 schoenebeck 317
2924 schoenebeck 308 // line-segment approximations of the 15 velocity curves
2925 schoenebeck 16
2926 schoenebeck 308 // linear
2927     const int lin0[] = { 1, 1, 127, 127 };
2928     const int lin1[] = { 1, 21, 127, 127 };
2929     const int lin2[] = { 1, 45, 127, 127 };
2930     const int lin3[] = { 1, 74, 127, 127 };
2931     const int lin4[] = { 1, 127, 127, 127 };
2932 schoenebeck 16
2933 schoenebeck 308 // non-linear
2934     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2935 schoenebeck 317 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2936 schoenebeck 308 127, 127 };
2937     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2938     127, 127 };
2939     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2940     127, 127 };
2941     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2942 schoenebeck 317
2943 schoenebeck 308 // special
2944 schoenebeck 317 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2945 schoenebeck 308 113, 127, 127, 127 };
2946     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2947     118, 127, 127, 127 };
2948 schoenebeck 317 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2949 schoenebeck 308 85, 90, 91, 127, 127, 127 };
2950 schoenebeck 317 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2951 schoenebeck 308 117, 127, 127, 127 };
2952 schoenebeck 317 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2953 schoenebeck 308 127, 127 };
2954 schoenebeck 317
2955 persson 728 // this is only used by the VCF velocity curve
2956     const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2957     91, 127, 127, 127 };
2958    
2959 schoenebeck 308 const int* const curves[] = { non0, non1, non2, non3, non4,
2960 schoenebeck 317 lin0, lin1, lin2, lin3, lin4,
2961 persson 728 spe0, spe1, spe2, spe3, spe4, spe5 };
2962 schoenebeck 317
2963 schoenebeck 308 double* const table = new double[128];
2964    
2965     const int* curve = curves[curveType * 5 + depth];
2966     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2967 schoenebeck 317
2968 schoenebeck 308 table[0] = 0;
2969     for (int x = 1 ; x < 128 ; x++) {
2970    
2971     if (x > curve[2]) curve += 2;
2972 schoenebeck 317 double y = curve[1] + (x - curve[0]) *
2973 schoenebeck 308 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2974     y = y / 127;
2975    
2976     // Scale up for s > 20, down for s < 20. When
2977     // down-scaling, the curve still ends at 1.0.
2978     if (s < 20 && y >= 0.5)
2979     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2980     else
2981     y = y * (s / 20.0);
2982     if (y > 1) y = 1;
2983    
2984     table[x] = y;
2985     }
2986     return table;
2987     }
2988    
2989    
2990 schoenebeck 2 // *************** Region ***************
2991     // *
2992    
2993     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2994     // Initialization
2995     Dimensions = 0;
2996 schoenebeck 347 for (int i = 0; i < 256; i++) {
2997 schoenebeck 2 pDimensionRegions[i] = NULL;
2998     }
2999 schoenebeck 282 Layers = 1;
3000 schoenebeck 347 File* file = (File*) GetParent()->GetParent();
3001     int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3002 schoenebeck 2
3003     // Actual Loading
3004    
3005 schoenebeck 1524 if (!file->GetAutoLoad()) return;
3006    
3007 schoenebeck 2 LoadDimensionRegions(rgnList);
3008    
3009     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
3010     if (_3lnk) {
3011     DimensionRegions = _3lnk->ReadUint32();
3012 schoenebeck 347 for (int i = 0; i < dimensionBits; i++) {
3013 schoenebeck 2 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
3014     uint8_t bits = _3lnk->ReadUint8();
3015 persson 1199 _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
3016     _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
3017 persson 774 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
3018 schoenebeck 2 if (dimension == dimension_none) { // inactive dimension
3019     pDimensionDefinitions[i].dimension = dimension_none;
3020     pDimensionDefinitions[i].bits = 0;
3021     pDimensionDefinitions[i].zones = 0;
3022     pDimensionDefinitions[i].split_type = split_type_bit;
3023     pDimensionDefinitions[i].zone_size = 0;
3024     }
3025     else { // active dimension
3026     pDimensionDefinitions[i].dimension = dimension;
3027     pDimensionDefinitions[i].bits = bits;
3028 persson 774 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
3029 schoenebeck 1113 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
3030     pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
3031 schoenebeck 2 Dimensions++;
3032 schoenebeck 282
3033     // if this is a layer dimension, remember the amount of layers
3034     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
3035 schoenebeck 2 }
3036 persson 774 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
3037 schoenebeck 2 }
3038 persson 834 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
3039 schoenebeck 2
3040 persson 858 // if there's a velocity dimension and custom velocity zone splits are used,
3041     // update the VelocityTables in the dimension regions
3042     UpdateVelocityTable();
3043 schoenebeck 2
3044 schoenebeck 317 // jump to start of the wave pool indices (if not already there)
3045     if (file->pVersion && file->pVersion->major == 3)
3046     _3lnk->SetPos(68); // version 3 has a different 3lnk structure
3047     else
3048     _3lnk->SetPos(44);
3049    
3050 schoenebeck 1524 // load sample references (if auto loading is enabled)
3051     if (file->GetAutoLoad()) {
3052     for (uint i = 0; i < DimensionRegions; i++) {
3053     uint32_t wavepoolindex = _3lnk->ReadUint32();
3054     if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3055     }
3056     GetSample(); // load global region sample reference
3057 schoenebeck 2 }
3058 persson 1102 } else {
3059     DimensionRegions = 0;
3060 persson 1182 for (int i = 0 ; i < 8 ; i++) {
3061     pDimensionDefinitions[i].dimension = dimension_none;
3062     pDimensionDefinitions[i].bits = 0;
3063     pDimensionDefinitions[i].zones = 0;
3064     }
3065 schoenebeck 2 }
3066 schoenebeck 823
3067     // make sure there is at least one dimension region
3068     if (!DimensionRegions) {
3069     RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3070     if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3071     RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3072 schoenebeck 1316 pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3073 schoenebeck 823 DimensionRegions = 1;
3074     }
3075 schoenebeck 2 }
3076    
3077 schoenebeck 809 /**
3078     * Apply Region settings and all its DimensionRegions to the respective
3079     * RIFF chunks. You have to call File::Save() to make changes persistent.
3080     *
3081     * Usually there is absolutely no need to call this method explicitly.
3082     * It will be called automatically when File::Save() was called.
3083     *
3084 schoenebeck 2682 * @param pProgress - callback function for progress notification
3085 schoenebeck 809 * @throws gig::Exception if samples cannot be dereferenced
3086     */
3087 schoenebeck 2682 void Region::UpdateChunks(progress_t* pProgress) {
3088 schoenebeck 1106 // in the gig format we don't care about the Region's sample reference
3089     // but we still have to provide some existing one to not corrupt the
3090     // file, so to avoid the latter we simply always assign the sample of
3091     // the first dimension region of this region
3092     pSample = pDimensionRegions[0]->pSample;
3093    
3094 schoenebeck 809 // first update base class's chunks
3095 schoenebeck 2682 DLS::Region::UpdateChunks(pProgress);
3096 schoenebeck 809
3097     // update dimension region's chunks
3098 schoenebeck 823 for (int i = 0; i < DimensionRegions; i++) {
3099 schoenebeck 2682 pDimensionRegions[i]->UpdateChunks(pProgress);
3100 schoenebeck 823 }
3101 schoenebeck 809
3102 persson 1317 File* pFile = (File*) GetParent()->GetParent();
3103     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3104 persson 1247 const int iMaxDimensions = version3 ? 8 : 5;
3105     const int iMaxDimensionRegions = version3 ? 256 : 32;
3106 schoenebeck 809
3107     // make sure '3lnk' chunk exists
3108     RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3109     if (!_3lnk) {
3110 persson 1247 const int _3lnkChunkSize = version3 ? 1092 : 172;
3111 schoenebeck 809 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3112 persson 1182 memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3113 persson 1192
3114     // move 3prg to last position
3115 schoenebeck 2584 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3116 schoenebeck 809 }
3117    
3118     // update dimension definitions in '3lnk' chunk
3119     uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3120 persson 1179 store32(&pData[0], DimensionRegions);
3121 persson 1199 int shift = 0;
3122 schoenebeck 809 for (int i = 0; i < iMaxDimensions; i++) {
3123 persson 918 pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3124     pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3125 persson 1266 pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3126 persson 1199 pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3127 persson 918 pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3128 persson 1199 // next 3 bytes unknown, always zero?
3129    
3130     shift += pDimensionDefinitions[i].bits;
3131 schoenebeck 809 }
3132    
3133     // update wave pool table in '3lnk' chunk
3134 persson 1247 const int iWavePoolOffset = version3 ? 68 : 44;
3135 schoenebeck 809 for (uint i = 0; i < iMaxDimensionRegions; i++) {
3136     int iWaveIndex = -1;
3137     if (i < DimensionRegions) {
3138 schoenebeck 823 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3139     File::SampleList::iterator iter = pFile->pSamples->begin();
3140     File::SampleList::iterator end = pFile->pSamples->end();
3141 schoenebeck 809 for (int index = 0; iter != end; ++iter, ++index) {
3142 schoenebeck 823 if (*iter == pDimensionRegions[i]->pSample) {
3143     iWaveIndex = index;
3144     break;
3145     }
3146 schoenebeck 809 }
3147     }
3148 persson 1179 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3149 schoenebeck 809 }
3150     }
3151    
3152 schoenebeck 2 void Region::LoadDimensionRegions(RIFF::List* rgn) {
3153     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3154     if (_3prg) {
3155     int dimensionRegionNr = 0;
3156     RIFF::List* _3ewl = _3prg->GetFirstSubList();
3157     while (_3ewl) {
3158     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3159 schoenebeck 1316 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3160 schoenebeck 2 dimensionRegionNr++;
3161     }
3162     _3ewl = _3prg->GetNextSubList();
3163     }
3164     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3165     }
3166     }
3167    
3168 schoenebeck 1335 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3169     // update KeyRange struct and make sure regions are in correct order
3170     DLS::Region::SetKeyRange(Low, High);
3171     // update Region key table for fast lookup
3172     ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3173     }
3174    
3175 persson 858 void Region::UpdateVelocityTable() {
3176     // get velocity dimension's index
3177     int veldim = -1;
3178     for (int i = 0 ; i < Dimensions ; i++) {
3179     if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3180     veldim = i;
3181 schoenebeck 809 break;
3182     }
3183     }
3184 persson 858 if (veldim == -1) return;
3185 schoenebeck 809
3186 persson 858 int step = 1;
3187     for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3188     int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3189 schoenebeck 809
3190 persson 858 // loop through all dimension regions for all dimensions except the velocity dimension
3191     int dim[8] = { 0 };
3192     for (int i = 0 ; i < DimensionRegions ; i++) {
3193 schoenebeck 2923 const int end = i + step * pDimensionDefinitions[veldim].zones;
3194 persson 858
3195 schoenebeck 2923 // create a velocity table for all cases where the velocity zone is zero
3196 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3197     pDimensionRegions[i]->VelocityUpperLimit) {
3198 persson 858 // create the velocity table
3199     uint8_t* table = pDimensionRegions[i]->VelocityTable;
3200     if (!table) {
3201     table = new uint8_t[128];
3202     pDimensionRegions[i]->VelocityTable = table;
3203     }
3204     int tableidx = 0;
3205     int velocityZone = 0;
3206 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3207     for (int k = i ; k < end ; k += step) {
3208     DimensionRegion *d = pDimensionRegions[k];
3209     for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3210     velocityZone++;
3211     }
3212     } else { // gig2
3213     for (int k = i ; k < end ; k += step) {
3214     DimensionRegion *d = pDimensionRegions[k];
3215     for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3216     velocityZone++;
3217     }
3218 persson 858 }
3219     } else {
3220     if (pDimensionRegions[i]->VelocityTable) {
3221     delete[] pDimensionRegions[i]->VelocityTable;
3222     pDimensionRegions[i]->VelocityTable = 0;
3223     }
3224 schoenebeck 809 }
3225 persson 858
3226 schoenebeck 2923 // jump to the next case where the velocity zone is zero
3227 persson 858 int j;
3228     int shift = 0;
3229     for (j = 0 ; j < Dimensions ; j++) {
3230     if (j == veldim) i += skipveldim; // skip velocity dimension
3231     else {
3232     dim[j]++;
3233     if (dim[j] < pDimensionDefinitions[j].zones) break;
3234     else {
3235     // skip unused dimension regions
3236     dim[j] = 0;
3237     i += ((1 << pDimensionDefinitions[j].bits) -
3238     pDimensionDefinitions[j].zones) << shift;
3239     }
3240     }
3241     shift += pDimensionDefinitions[j].bits;
3242     }
3243     if (j == Dimensions) break;
3244 schoenebeck 809 }
3245     }
3246    
3247     /** @brief Einstein would have dreamed of it - create a new dimension.
3248     *
3249     * Creates a new dimension with the dimension definition given by
3250     * \a pDimDef. The appropriate amount of DimensionRegions will be created.
3251     * There is a hard limit of dimensions and total amount of "bits" all
3252     * dimensions can have. This limit is dependant to what gig file format
3253     * version this file refers to. The gig v2 (and lower) format has a
3254     * dimension limit and total amount of bits limit of 5, whereas the gig v3
3255     * format has a limit of 8.
3256     *
3257     * @param pDimDef - defintion of the new dimension
3258     * @throws gig::Exception if dimension of the same type exists already
3259     * @throws gig::Exception if amount of dimensions or total amount of
3260     * dimension bits limit is violated
3261     */
3262     void Region::AddDimension(dimension_def_t* pDimDef) {
3263 schoenebeck 2547 // some initial sanity checks of the given dimension definition
3264     if (pDimDef->zones < 2)
3265     throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3266     if (pDimDef->bits < 1)
3267     throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3268     if (pDimDef->dimension == dimension_samplechannel) {
3269     if (pDimDef->zones != 2)
3270     throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3271     if (pDimDef->bits != 1)
3272     throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3273     }
3274    
3275 schoenebeck 809 // check if max. amount of dimensions reached
3276     File* file = (File*) GetParent()->GetParent();
3277     const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3278     if (Dimensions >= iMaxDimensions)
3279     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3280     // check if max. amount of dimension bits reached
3281     int iCurrentBits = 0;
3282     for (int i = 0; i < Dimensions; i++)
3283     iCurrentBits += pDimensionDefinitions[i].bits;
3284     if (iCurrentBits >= iMaxDimensions)
3285     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3286     const int iNewBits = iCurrentBits + pDimDef->bits;
3287     if (iNewBits > iMaxDimensions)
3288     throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3289     // check if there's already a dimensions of the same type
3290     for (int i = 0; i < Dimensions; i++)
3291     if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3292     throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3293    
3294 persson 1301 // pos is where the new dimension should be placed, normally
3295     // last in list, except for the samplechannel dimension which
3296     // has to be first in list
3297     int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3298     int bitpos = 0;
3299     for (int i = 0 ; i < pos ; i++)
3300     bitpos += pDimensionDefinitions[i].bits;
3301    
3302     // make room for the new dimension
3303     for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3304     for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3305     for (int j = Dimensions ; j > pos ; j--) {
3306     pDimensionRegions[i]->DimensionUpperLimits[j] =
3307     pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3308     }
3309     }
3310    
3311 schoenebeck 809 // assign definition of new dimension
3312 persson 1301 pDimensionDefinitions[pos] = *pDimDef;
3313 schoenebeck 809
3314 schoenebeck 1113 // auto correct certain dimension definition fields (where possible)
3315 persson 1301 pDimensionDefinitions[pos].split_type =
3316     __resolveSplitType(pDimensionDefinitions[pos].dimension);
3317     pDimensionDefinitions[pos].zone_size =
3318     __resolveZoneSize(pDimensionDefinitions[pos]);
3319 schoenebeck 1113
3320 persson 1301 // create new dimension region(s) for this new dimension, and make
3321     // sure that the dimension regions are placed correctly in both the
3322     // RIFF list and the pDimensionRegions array
3323     RIFF::Chunk* moveTo = NULL;
3324     RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3325     for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3326     for (int k = 0 ; k < (1 << bitpos) ; k++) {
3327     pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3328     }
3329     for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3330     for (int k = 0 ; k < (1 << bitpos) ; k++) {
3331     RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3332     if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3333     // create a new dimension region and copy all parameter values from
3334     // an existing dimension region
3335     pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3336     new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3337 persson 1247
3338 persson 1301 DimensionRegions++;
3339     }
3340     }
3341     moveTo = pDimensionRegions[i]->pParentList;
3342 schoenebeck 809 }
3343    
3344 persson 1247 // initialize the upper limits for this dimension
3345 persson 1301 int mask = (1 << bitpos) - 1;
3346     for (int z = 0 ; z < pDimDef->zones ; z++) {
3347 persson 1264 uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3348 persson 1247 for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3349 persson 1301 pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3350     (z << bitpos) |
3351     (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3352 persson 1247 }
3353     }
3354    
3355 schoenebeck 809 Dimensions++;
3356    
3357     // if this is a layer dimension, update 'Layers' attribute
3358     if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3359    
3360 persson 858 UpdateVelocityTable();
3361 schoenebeck 809 }
3362    
3363     /** @brief Delete an existing dimension.
3364     *
3365     * Deletes the dimension given by \a pDimDef and deletes all respective
3366     * dimension regions, that is all dimension regions where the dimension's
3367     * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
3368     * for example this would delete all dimension regions for the case(s)
3369     * where the sustain pedal is pressed down.
3370     *
3371     * @param pDimDef - dimension to delete
3372     * @throws gig::Exception if given dimension cannot be found
3373     */
3374     void Region::DeleteDimension(dimension_def_t* pDimDef) {
3375     // get dimension's index
3376     int iDimensionNr = -1;
3377     for (int i = 0; i < Dimensions; i++) {
3378     if (&pDimensionDefinitions[i] == pDimDef) {
3379     iDimensionNr = i;
3380     break;
3381     }
3382     }
3383     if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3384    
3385     // get amount of bits below the dimension to delete
3386     int iLowerBits = 0;
3387     for (int i = 0; i < iDimensionNr; i++)
3388     iLowerBits += pDimensionDefinitions[i].bits;
3389    
3390     // get amount ot bits above the dimension to delete
3391     int iUpperBits = 0;
3392     for (int i = iDimensionNr + 1; i < Dimensions; i++)
3393     iUpperBits += pDimensionDefinitions[i].bits;
3394    
3395 persson 1247 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3396    
3397 schoenebeck 809 // delete dimension regions which belong to the given dimension
3398     // (that is where the dimension's bit > 0)
3399     for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3400     for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3401     for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3402     int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3403     iObsoleteBit << iLowerBits |
3404     iLowerBit;
3405 persson 1247
3406     _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3407 schoenebeck 809 delete pDimensionRegions[iToDelete];
3408     pDimensionRegions[iToDelete] = NULL;
3409     DimensionRegions--;
3410     }
3411     }
3412     }
3413    
3414     // defrag pDimensionRegions array
3415     // (that is remove the NULL spaces within the pDimensionRegions array)
3416     for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3417     if (!pDimensionRegions[iTo]) {
3418     if (iFrom <= iTo) iFrom = iTo + 1;
3419     while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3420     if (iFrom < 256 && pDimensionRegions[iFrom]) {
3421     pDimensionRegions[iTo] = pDimensionRegions[iFrom];
3422     pDimensionRegions[iFrom] = NULL;
3423     }
3424     }
3425     }
3426    
3427 persson 1247 // remove the this dimension from the upper limits arrays
3428     for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3429     DimensionRegion* d = pDimensionRegions[j];
3430     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3431     d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3432     }
3433     d->DimensionUpperLimits[Dimensions - 1] = 127;
3434     }
3435    
3436 schoenebeck 809 // 'remove' dimension definition
3437     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3438     pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
3439     }
3440     pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3441     pDimensionDefinitions[Dimensions - 1].bits = 0;
3442     pDimensionDefinitions[Dimensions - 1].zones = 0;
3443    
3444     Dimensions--;
3445    
3446     // if this was a layer dimension, update 'Layers' attribute
3447     if (pDimDef->dimension == dimension_layer) Layers = 1;
3448     }
3449    
3450 schoenebeck 2555 /** @brief Delete one split zone of a dimension (decrement zone amount).
3451     *
3452     * Instead of deleting an entire dimensions, this method will only delete
3453     * one particular split zone given by @a zone of the Region's dimension
3454     * given by @a type. So this method will simply decrement the amount of
3455     * zones by one of the dimension in question. To be able to do that, the
3456     * respective dimension must exist on this Region and it must have at least
3457     * 3 zones. All DimensionRegion objects associated with the zone will be
3458     * deleted.
3459     *
3460     * @param type - identifies the dimension where a zone shall be deleted
3461     * @param zone - index of the dimension split zone that shall be deleted
3462     * @throws gig::Exception if requested zone could not be deleted
3463     */
3464     void Region::DeleteDimensionZone(dimension_t type, int zone) {
3465     dimension_def_t* oldDef = GetDimensionDefinition(type);
3466     if (!oldDef)
3467     throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3468     if (oldDef->zones <= 2)
3469     throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3470     if (zone < 0 || zone >= oldDef->zones)
3471     throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3472    
3473     const int newZoneSize = oldDef->zones - 1;
3474    
3475     // create a temporary Region which just acts as a temporary copy
3476     // container and will be deleted at the end of this function and will
3477     // also not be visible through the API during this process
3478     gig::Region* tempRgn = NULL;
3479     {
3480     // adding these temporary chunks is probably not even necessary
3481     Instrument* instr = static_cast<Instrument*>(GetParent());
3482     RIFF::List* pCkInstrument = instr->pCkInstrument;
3483     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3484     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3485     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3486     tempRgn = new Region(instr, rgn);
3487     }
3488    
3489     // copy this region's dimensions (with already the dimension split size
3490     // requested by the arguments of this method call) to the temporary
3491     // region, and don't use Region::CopyAssign() here for this task, since
3492     // it would also alter fast lookup helper variables here and there
3493     dimension_def_t newDef;
3494     for (int i = 0; i < Dimensions; ++i) {
3495     dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3496     // is this the dimension requested by the method arguments? ...
3497     if (def.dimension == type) { // ... if yes, decrement zone amount by one
3498     def.zones = newZoneSize;
3499     if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3500     newDef = def;
3501     }
3502     tempRgn->AddDimension(&def);
3503     }
3504    
3505     // find the dimension index in the tempRegion which is the dimension
3506     // type passed to this method (paranoidly expecting different order)
3507     int tempReducedDimensionIndex = -1;
3508     for (int d = 0; d < tempRgn->Dimensions; ++d) {
3509     if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3510     tempReducedDimensionIndex = d;
3511     break;
3512     }
3513     }
3514    
3515     // copy dimension regions from this region to the temporary region
3516     for (int iDst = 0; iDst < 256; ++iDst) {
3517     DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3518     if (!dstDimRgn) continue;
3519     std::map<dimension_t,int> dimCase;
3520     bool isValidZone = true;
3521     for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3522     const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3523     dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3524     (iDst >> baseBits) & ((1 << dstBits) - 1);
3525     baseBits += dstBits;
3526     // there are also DimensionRegion objects of unused zones, skip them
3527     if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3528     isValidZone = false;
3529     break;
3530     }
3531     }
3532     if (!isValidZone) continue;
3533     // a bit paranoid: cope with the chance that the dimensions would
3534     // have different order in source and destination regions
3535     const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3536     if (dimCase[type] >= zone) dimCase[type]++;
3537     DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3538     dstDimRgn->CopyAssign(srcDimRgn);
3539     // if this is the upper most zone of the dimension passed to this
3540     // method, then correct (raise) its upper limit to 127
3541     if (newDef.split_type == split_type_normal && isLastZone)
3542     dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3543     }
3544    
3545     // now tempRegion's dimensions and DimensionRegions basically reflect
3546     // what we wanted to get for this actual Region here, so we now just
3547     // delete and recreate the dimension in question with the new amount
3548     // zones and then copy back from tempRegion
3549     DeleteDimension(oldDef);
3550     AddDimension(&newDef);
3551     for (int iSrc = 0; iSrc < 256; ++iSrc) {
3552     DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3553     if (!srcDimRgn) continue;
3554     std::map<dimension_t,int> dimCase;
3555     for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3556     const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3557     dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3558     (iSrc >> baseBits) & ((1 << srcBits) - 1);
3559     baseBits += srcBits;
3560     }
3561     // a bit paranoid: cope with the chance that the dimensions would
3562     // have different order in source and destination regions
3563     DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3564     if (!dstDimRgn) continue;
3565     dstDimRgn->CopyAssign(srcDimRgn);
3566     }
3567    
3568     // delete temporary region
3569     delete tempRgn;
3570 schoenebeck 2557
3571     UpdateVelocityTable();
3572 schoenebeck 2555 }
3573    
3574     /** @brief Divide split zone of a dimension in two (increment zone amount).
3575     *
3576     * This will increment the amount of zones for the dimension (given by
3577     * @a type) by one. It will do so by dividing the zone (given by @a zone)
3578     * in the middle of its zone range in two. So the two zones resulting from
3579     * the zone being splitted, will be an equivalent copy regarding all their
3580     * articulation informations and sample reference. The two zones will only
3581     * differ in their zone's upper limit
3582     * (DimensionRegion::DimensionUpperLimits).
3583     *
3584     * @param type - identifies the dimension where a zone shall be splitted
3585     * @param zone - index of the dimension split zone that shall be splitted
3586     * @throws gig::Exception if requested zone could not be splitted
3587     */
3588     void Region::SplitDimensionZone(dimension_t type, int zone) {
3589     dimension_def_t* oldDef = GetDimensionDefinition(type);
3590     if (!oldDef)
3591     throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3592     if (zone < 0 || zone >= oldDef->zones)
3593     throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3594    
3595     const int newZoneSize = oldDef->zones + 1;
3596    
3597     // create a temporary Region which just acts as a temporary copy
3598     // container and will be deleted at the end of this function and will
3599     // also not be visible through the API during this process
3600     gig::Region* tempRgn = NULL;
3601     {
3602     // adding these temporary chunks is probably not even necessary
3603     Instrument* instr = static_cast<Instrument*>(GetParent());
3604     RIFF::List* pCkInstrument = instr->pCkInstrument;
3605     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3606     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3607     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3608     tempRgn = new Region(instr, rgn);
3609     }
3610    
3611     // copy this region's dimensions (with already the dimension split size
3612     // requested by the arguments of this method call) to the temporary
3613     // region, and don't use Region::CopyAssign() here for this task, since
3614     // it would also alter fast lookup helper variables here and there
3615     dimension_def_t newDef;
3616     for (int i = 0; i < Dimensions; ++i) {
3617     dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3618     // is this the dimension requested by the method arguments? ...
3619     if (def.dimension == type) { // ... if yes, increment zone amount by one
3620     def.zones = newZoneSize;
3621     if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3622     newDef = def;
3623     }
3624     tempRgn->AddDimension(&def);
3625     }
3626    
3627     // find the dimension index in the tempRegion which is the dimension
3628     // type passed to this method (paranoidly expecting different order)
3629     int tempIncreasedDimensionIndex = -1;
3630     for (int d = 0; d < tempRgn->Dimensions; ++d) {
3631     if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3632     tempIncreasedDimensionIndex = d;
3633     break;
3634     }
3635     }
3636    
3637     // copy dimension regions from this region to the temporary region
3638     for (int iSrc = 0; iSrc < 256; ++iSrc) {
3639     DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3640     if (!srcDimRgn) continue;
3641     std::map<dimension_t,int> dimCase;
3642     bool isValidZone = true;
3643     for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3644     const int srcBits = pDimensionDefinitions[d].bits;
3645     dimCase[pDimensionDefinitions[d].dimension] =
3646     (iSrc >> baseBits) & ((1 << srcBits) - 1);
3647     // there are also DimensionRegion objects for unused zones, skip them
3648     if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3649     isValidZone = false;
3650     break;
3651     }
3652     baseBits += srcBits;
3653     }
3654     if (!isValidZone) continue;
3655     // a bit paranoid: cope with the chance that the dimensions would
3656     // have different order in source and destination regions
3657     if (dimCase[type] > zone) dimCase[type]++;
3658     DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3659     dstDimRgn->CopyAssign(srcDimRgn);
3660     // if this is the requested zone to be splitted, then also copy
3661     // the source DimensionRegion to the newly created target zone
3662     // and set the old zones upper limit lower
3663     if (dimCase[type] == zone) {
3664     // lower old zones upper limit
3665     if (newDef.split_type == split_type_normal) {
3666     const int high =
3667     dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3668     int low = 0;
3669     if (zone > 0) {
3670     std::map<dimension_t,int> lowerCase = dimCase;
3671     lowerCase[type]--;
3672     DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3673     low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3674     }
3675     dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3676     }
3677     // fill the newly created zone of the divided zone as well
3678     dimCase[type]++;
3679     dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3680     dstDimRgn->CopyAssign(srcDimRgn);
3681     }
3682     }
3683    
3684     // now tempRegion's dimensions and DimensionRegions basically reflect
3685     // what we wanted to get for this actual Region here, so we now just
3686     // delete and recreate the dimension in question with the new amount
3687     // zones and then copy back from tempRegion
3688     DeleteDimension(oldDef);
3689     AddDimension(&newDef);
3690     for (int iSrc = 0; iSrc < 256; ++iSrc) {
3691     DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3692     if (!srcDimRgn) continue;
3693     std::map<dimension_t,int> dimCase;
3694     for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3695     const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3696     dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3697     (iSrc >> baseBits) & ((1 << srcBits) - 1);
3698     baseBits += srcBits;
3699     }
3700     // a bit paranoid: cope with the chance that the dimensions would
3701     // have different order in source and destination regions
3702     DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3703     if (!dstDimRgn) continue;
3704     dstDimRgn->CopyAssign(srcDimRgn);
3705     }
3706    
3707     // delete temporary region
3708     delete tempRgn;
3709 schoenebeck 2557
3710     UpdateVelocityTable();
3711 schoenebeck 2555 }
3712    
3713 schoenebeck 2639 /** @brief Change type of an existing dimension.
3714     *
3715     * Alters the dimension type of a dimension already existing on this
3716     * region. If there is currently no dimension on this Region with type
3717     * @a oldType, then this call with throw an Exception. Likewise there are
3718     * cases where the requested dimension type cannot be performed. For example
3719     * if the new dimension type shall be gig::dimension_samplechannel, and the
3720     * current dimension has more than 2 zones. In such cases an Exception is
3721     * thrown as well.
3722     *
3723     * @param oldType - identifies the existing dimension to be changed
3724     * @param newType - to which dimension type it should be changed to
3725     * @throws gig::Exception if requested change cannot be performed
3726     */
3727     void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3728     if (oldType == newType) return;
3729     dimension_def_t* def = GetDimensionDefinition(oldType);
3730     if (!def)
3731     throw gig::Exception("No dimension with provided old dimension type exists on this region");
3732     if (newType == dimension_samplechannel && def->zones != 2)
3733     throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3734 schoenebeck 2640 if (GetDimensionDefinition(newType))
3735     throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3736     def->dimension = newType;
3737 schoenebeck 2639 def->split_type = __resolveSplitType(newType);
3738     }
3739    
3740 schoenebeck 2555 DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3741     uint8_t bits[8] = {};
3742     for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3743     it != DimCase.end(); ++it)
3744     {
3745     for (int d = 0; d < Dimensions; ++d) {
3746     if (pDimensionDefinitions[d].dimension == it->first) {
3747     bits[d] = it->second;
3748     goto nextDimCaseSlice;
3749     }
3750     }
3751     assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3752     nextDimCaseSlice:
3753     ; // noop
3754     }
3755     return GetDimensionRegionByBit(bits);
3756     }
3757    
3758 schoenebeck 2547 /**
3759     * Searches in the current Region for a dimension of the given dimension
3760     * type and returns the precise configuration of that dimension in this
3761     * Region.
3762     *
3763     * @param type - dimension type of the sought dimension
3764     * @returns dimension definition or NULL if there is no dimension with
3765     * sought type in this Region.
3766     */
3767     dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3768     for (int i = 0; i < Dimensions; ++i)
3769     if (pDimensionDefinitions[i].dimension == type)
3770     return &pDimensionDefinitions[i];
3771     return NULL;
3772     }
3773    
3774 schoenebeck 2 Region::~Region() {
3775 schoenebeck 350 for (int i = 0; i < 256; i++) {
3776 schoenebeck 2 if (pDimensionRegions[i]) delete pDimensionRegions[i];
3777     }
3778     }
3779    
3780     /**
3781     * Use this method in your audio engine to get the appropriate dimension
3782     * region with it's articulation data for the current situation. Just
3783     * call the method with the current MIDI controller values and you'll get
3784     * the DimensionRegion with the appropriate articulation data for the
3785     * current situation (for this Region of course only). To do that you'll
3786     * first have to look which dimensions with which controllers and in
3787     * which order are defined for this Region when you load the .gig file.
3788     * Special cases are e.g. layer or channel dimensions where you just put
3789     * in the index numbers instead of a MIDI controller value (means 0 for
3790     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
3791     * etc.).
3792     *
3793 schoenebeck 347 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
3794 schoenebeck 2 * @returns adress to the DimensionRegion for the given situation
3795     * @see pDimensionDefinitions
3796     * @see Dimensions
3797     */
3798 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3799 persson 858 uint8_t bits;
3800     int veldim = -1;
3801 schoenebeck 3053 int velbitpos = 0;
3802 persson 858 int bitpos = 0;
3803     int dimregidx = 0;
3804 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
3805 persson 858 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3806     // the velocity dimension must be handled after the other dimensions
3807     veldim = i;
3808     velbitpos = bitpos;
3809     } else {
3810     switch (pDimensionDefinitions[i].split_type) {
3811     case split_type_normal:
3812 persson 1070 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3813     // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3814     for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3815     if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3816     }
3817     } else {
3818     // gig2: evenly sized zones
3819     bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3820     }
3821 persson 858 break;
3822     case split_type_bit: // the value is already the sought dimension bit number
3823     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3824     bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3825     break;
3826     }
3827     dimregidx |= bits << bitpos;
3828 schoenebeck 2 }
3829 persson 858 bitpos += pDimensionDefinitions[i].bits;
3830 schoenebeck 2 }
3831 schoenebeck 2564 DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3832     if (!dimreg) return NULL;
3833 persson 858 if (veldim != -1) {
3834     // (dimreg is now the dimension region for the lowest velocity)
3835 persson 1070 if (dimreg->VelocityTable) // custom defined zone ranges
3836 schoenebeck 2564 bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3837 persson 858 else // normal split type
3838 schoenebeck 2564 bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3839 persson 858
3840 schoenebeck 2564 const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3841     dimregidx |= (bits & limiter_mask) << velbitpos;
3842     dimreg = pDimensionRegions[dimregidx & 255];
3843 persson 858 }
3844     return dimreg;
3845 schoenebeck 2 }
3846    
3847 schoenebeck 2599 int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3848     uint8_t bits;
3849     int veldim = -1;
3850 schoenebeck 3053 int velbitpos = 0;
3851 schoenebeck 2599 int bitpos = 0;
3852     int dimregidx = 0;
3853     for (uint i = 0; i < Dimensions; i++) {
3854     if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3855     // the velocity dimension must be handled after the other dimensions
3856     veldim = i;
3857     velbitpos = bitpos;
3858     } else {
3859     switch (pDimensionDefinitions[i].split_type) {
3860     case split_type_normal:
3861     if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3862     // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3863     for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3864     if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3865     }
3866     } else {
3867     // gig2: evenly sized zones
3868     bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3869     }
3870     break;
3871     case split_type_bit: // the value is already the sought dimension bit number
3872     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3873     bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3874     break;
3875     }
3876     dimregidx |= bits << bitpos;
3877     }
3878     bitpos += pDimensionDefinitions[i].bits;
3879     }
3880     dimregidx &= 255;
3881     DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3882     if (!dimreg) return -1;
3883     if (veldim != -1) {
3884     // (dimreg is now the dimension region for the lowest velocity)
3885     if (dimreg->VelocityTable) // custom defined zone ranges
3886     bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3887     else // normal split type
3888     bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3889    
3890     const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3891     dimregidx |= (bits & limiter_mask) << velbitpos;
3892     dimregidx &= 255;
3893     }
3894     return dimregidx;
3895     }
3896    
3897 schoenebeck 2 /**
3898     * Returns the appropriate DimensionRegion for the given dimension bit
3899     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
3900     * instead of calling this method directly!
3901     *
3902 schoenebeck 347 * @param DimBits Bit numbers for dimension 0 to 7
3903 schoenebeck 2 * @returns adress to the DimensionRegion for the given dimension
3904     * bit numbers
3905     * @see GetDimensionRegionByValue()
3906     */
3907 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
3908     return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3909     << pDimensionDefinitions[5].bits | DimBits[5])
3910     << pDimensionDefinitions[4].bits | DimBits[4])
3911     << pDimensionDefinitions[3].bits | DimBits[3])
3912     << pDimensionDefinitions[2].bits | DimBits[2])
3913     << pDimensionDefinitions[1].bits | DimBits[1])
3914     << pDimensionDefinitions[0].bits | DimBits[0]];
3915 schoenebeck 2 }
3916    
3917     /**
3918     * Returns pointer address to the Sample referenced with this region.
3919     * This is the global Sample for the entire Region (not sure if this is
3920     * actually used by the Gigasampler engine - I would only use the Sample
3921     * referenced by the appropriate DimensionRegion instead of this sample).
3922     *
3923     * @returns address to Sample or NULL if there is no reference to a
3924     * sample saved in the .gig file
3925     */
3926     Sample* Region::GetSample() {
3927     if (pSample) return static_cast<gig::Sample*>(pSample);
3928     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3929     }
3930    
3931 schoenebeck 515 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3932 schoenebeck 352 if ((int32_t)WavePoolTableIndex == -1) return NULL;
3933 schoenebeck 2 File* file = (File*) GetParent()->GetParent();
3934 persson 902 if (!file->pWavePoolTable) return NULL;
3935 schoenebeck 2913 // for new files or files >= 2 GB use 64 bit wave pool offsets
3936     if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3937     // use 64 bit wave pool offsets (treating this as large file)
3938 schoenebeck 2912 uint64_t soughtoffset =
3939     uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3940     uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3941     Sample* sample = file->GetFirstSample(pProgress);
3942     while (sample) {
3943     if (sample->ullWavePoolOffset == soughtoffset)
3944     return static_cast<gig::Sample*>(sample);
3945     sample = file->GetNextSample();
3946     }
3947     } else {
3948 schoenebeck 2913 // use extension files and 32 bit wave pool offsets
3949 schoenebeck 2912 file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3950     file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3951     Sample* sample = file->GetFirstSample(pProgress);
3952     while (sample) {
3953     if (sample->ullWavePoolOffset == soughtoffset &&
3954     sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3955     sample = file->GetNextSample();
3956     }
3957 schoenebeck 2 }
3958     return NULL;
3959     }
3960 schoenebeck 2394
3961     /**
3962     * Make a (semi) deep copy of the Region object given by @a orig
3963     * and assign it to this object.
3964     *
3965     * Note that all sample pointers referenced by @a orig are simply copied as
3966     * memory address. Thus the respective samples are shared, not duplicated!
3967     *
3968     * @param orig - original Region object to be copied from
3969     */
3970     void Region::CopyAssign(const Region* orig) {
3971 schoenebeck 2482 CopyAssign(orig, NULL);
3972     }
3973    
3974     /**
3975     * Make a (semi) deep copy of the Region object given by @a orig and
3976     * assign it to this object
3977     *
3978     * @param mSamples - crosslink map between the foreign file's samples and
3979     * this file's samples
3980     */
3981     void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3982 schoenebeck 2394 // handle base classes
3983     DLS::Region::CopyAssign(orig);
3984    
3985 schoenebeck 2482 if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3986     pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3987     }
3988    
3989 schoenebeck 2394 // handle own member variables
3990     for (int i = Dimensions - 1; i >= 0; --i) {
3991     DeleteDimension(&pDimensionDefinitions[i]);
3992     }
3993     Layers = 0; // just to be sure
3994     for (int i = 0; i < orig->Dimensions; i++) {
3995     // we need to copy the dim definition here, to avoid the compiler
3996     // complaining about const-ness issue
3997     dimension_def_t def = orig->pDimensionDefinitions[i];
3998     AddDimension(&def);
3999     }
4000     for (int i = 0; i < 256; i++) {
4001     if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4002     pDimensionRegions[i]->CopyAssign(
4003 schoenebeck 2482 orig->pDimensionRegions[i],
4004     mSamples
4005 schoenebeck 2394 );
4006     }
4007     }
4008     Layers = orig->Layers;
4009     }
4010 schoenebeck 2
4011    
4012 persson 1627 // *************** MidiRule ***************
4013     // *
4014 schoenebeck 2
4015 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4016     _3ewg->SetPos(36);
4017     Triggers = _3ewg->ReadUint8();
4018     _3ewg->SetPos(40);
4019     ControllerNumber = _3ewg->ReadUint8();
4020     _3ewg->SetPos(46);
4021     for (int i = 0 ; i < Triggers ; i++) {
4022     pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4023     pTriggers[i].Descending = _3ewg->ReadUint8();
4024     pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4025     pTriggers[i].Key = _3ewg->ReadUint8();
4026     pTriggers[i].NoteOff = _3ewg->ReadUint8();
4027     pTriggers[i].Velocity = _3ewg->ReadUint8();
4028     pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4029     _3ewg->ReadUint8();
4030     }
4031 persson 1627 }
4032    
4033 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4034     ControllerNumber(0),
4035     Triggers(0) {
4036     }
4037 persson 1627
4038 persson 2450 void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4039     pData[32] = 4;
4040     pData[33] = 16;
4041     pData[36] = Triggers;
4042     pData[40] = ControllerNumber;
4043     for (int i = 0 ; i < Triggers ; i++) {
4044     pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4045     pData[47 + i * 8] = pTriggers[i].Descending;
4046     pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4047     pData[49 + i * 8] = pTriggers[i].Key;
4048     pData[50 + i * 8] = pTriggers[i].NoteOff;
4049     pData[51 + i * 8] = pTriggers[i].Velocity;
4050     pData[52 + i * 8] = pTriggers[i].OverridePedal;
4051     }
4052     }
4053    
4054     MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4055     _3ewg->SetPos(36);
4056     LegatoSamples = _3ewg->ReadUint8(); // always 12
4057     _3ewg->SetPos(40);
4058     BypassUseController = _3ewg->ReadUint8();
4059     BypassKey = _3ewg->ReadUint8();
4060     BypassController = _3ewg->ReadUint8();
4061     ThresholdTime = _3ewg->ReadUint16();
4062     _3ewg->ReadInt16();
4063     ReleaseTime = _3ewg->ReadUint16();
4064     _3ewg->ReadInt16();
4065     KeyRange.low = _3ewg->ReadUint8();
4066     KeyRange.high = _3ewg->ReadUint8();
4067     _3ewg->SetPos(64);
4068     ReleaseTriggerKey = _3ewg->ReadUint8();
4069     AltSustain1Key = _3ewg->ReadUint8();
4070     AltSustain2Key = _3ewg->ReadUint8();
4071     }
4072    
4073     MidiRuleLegato::MidiRuleLegato() :
4074     LegatoSamples(12),
4075     BypassUseController(false),
4076     BypassKey(0),
4077     BypassController(1),
4078     ThresholdTime(20),
4079     ReleaseTime(20),
4080     ReleaseTriggerKey(0),
4081     AltSustain1Key(0),
4082     AltSustain2Key(0)
4083     {
4084     KeyRange.low = KeyRange.high = 0;
4085     }
4086    
4087     void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4088     pData[32] = 0;
4089     pData[33] = 16;
4090     pData[36] = LegatoSamples;
4091     pData[40] = BypassUseController;
4092     pData[41] = BypassKey;
4093     pData[42] = BypassController;
4094     store16(&pData[43], ThresholdTime);
4095     store16(&pData[47], ReleaseTime);
4096     pData[51] = KeyRange.low;
4097     pData[52] = KeyRange.high;
4098     pData[64] = ReleaseTriggerKey;
4099     pData[65] = AltSustain1Key;
4100     pData[66] = AltSustain2Key;
4101     }
4102    
4103     MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4104     _3ewg->SetPos(36);
4105     Articulations = _3ewg->ReadUint8();
4106     int flags = _3ewg->ReadUint8();
4107     Polyphonic = flags & 8;
4108     Chained = flags & 4;
4109     Selector = (flags & 2) ? selector_controller :
4110     (flags & 1) ? selector_key_switch : selector_none;
4111     Patterns = _3ewg->ReadUint8();
4112     _3ewg->ReadUint8(); // chosen row
4113     _3ewg->ReadUint8(); // unknown
4114     _3ewg->ReadUint8(); // unknown
4115     _3ewg->ReadUint8(); // unknown
4116     KeySwitchRange.low = _3ewg->ReadUint8();
4117     KeySwitchRange.high = _3ewg->ReadUint8();
4118     Controller = _3ewg->ReadUint8();
4119     PlayRange.low = _3ewg->ReadUint8();
4120     PlayRange.high = _3ewg->ReadUint8();
4121    
4122     int n = std::min(int(Articulations), 32);
4123     for (int i = 0 ; i < n ; i++) {
4124     _3ewg->ReadString(pArticulations[i], 32);
4125     }
4126     _3ewg->SetPos(1072);
4127     n = std::min(int(Patterns), 32);
4128     for (int i = 0 ; i < n ; i++) {
4129     _3ewg->ReadString(pPatterns[i].Name, 16);
4130     pPatterns[i].Size = _3ewg->ReadUint8();
4131     _3ewg->Read(&pPatterns[i][0], 1, 32);
4132     }
4133     }
4134    
4135     MidiRuleAlternator::MidiRuleAlternator() :
4136     Articulations(0),
4137     Patterns(0),
4138     Selector(selector_none),
4139     Controller(0),
4140     Polyphonic(false),
4141     Chained(false)
4142     {
4143     PlayRange.low = PlayRange.high = 0;
4144     KeySwitchRange.low = KeySwitchRange.high = 0;
4145     }
4146    
4147     void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4148     pData[32] = 3;
4149     pData[33] = 16;
4150     pData[36] = Articulations;
4151     pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4152     (Selector == selector_controller ? 2 :
4153     (Selector == selector_key_switch ? 1 : 0));
4154     pData[38] = Patterns;
4155    
4156     pData[43] = KeySwitchRange.low;
4157     pData[44] = KeySwitchRange.high;
4158     pData[45] = Controller;
4159     pData[46] = PlayRange.low;
4160     pData[47] = PlayRange.high;
4161    
4162     char* str = reinterpret_cast<char*>(pData);
4163     int pos = 48;
4164     int n = std::min(int(Articulations), 32);
4165     for (int i = 0 ; i < n ; i++, pos += 32) {
4166     strncpy(&str[pos], pArticulations[i].c_str(), 32);
4167     }
4168    
4169     pos = 1072;
4170     n = std::min(int(Patterns), 32);
4171     for (int i = 0 ; i < n ; i++, pos += 49) {
4172     strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4173     pData[pos + 16] = pPatterns[i].Size;
4174     memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4175     }
4176     }
4177    
4178 schoenebeck 2584 // *************** Script ***************
4179     // *
4180    
4181     Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4182     pGroup = group;
4183     pChunk = ckScri;
4184     if (ckScri) { // object is loaded from file ...
4185     // read header
4186     uint32_t headerSize = ckScri->ReadUint32();
4187     Compression = (Compression_t) ckScri->ReadUint32();
4188     Encoding = (Encoding_t) ckScri->ReadUint32();
4189     Language = (Language_t) ckScri->ReadUint32();
4190     Bypass = (Language_t) ckScri->ReadUint32() & 1;
4191     crc = ckScri->ReadUint32();
4192     uint32_t nameSize = ckScri->ReadUint32();
4193     Name.resize(nameSize, ' ');
4194     for (int i = 0; i < nameSize; ++i)
4195     Name[i] = ckScri->ReadUint8();
4196     // to handle potential future extensions of the header
4197 schoenebeck 2602 ckScri->SetPos(sizeof(int32_t) + headerSize);
4198 schoenebeck 2584 // read actual script data
4199 schoenebeck 3053 uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4200 schoenebeck 2584 data.resize(scriptSize);
4201     for (int i = 0; i < scriptSize; ++i)
4202     data[i] = ckScri->ReadUint8();
4203     } else { // this is a new script object, so just initialize it as such ...
4204     Compression = COMPRESSION_NONE;
4205     Encoding = ENCODING_ASCII;
4206     Language = LANGUAGE_NKSP;
4207     Bypass = false;
4208     crc = 0;
4209     Name = "Unnamed Script";
4210     }
4211     }
4212    
4213     Script::~Script() {
4214     }
4215    
4216     /**
4217     * Returns the current script (i.e. as source code) in text format.
4218     */
4219     String Script::GetScriptAsText() {
4220     String s;
4221     s.resize(data.size(), ' ');
4222     memcpy(&s[0], &data[0], data.size());
4223     return s;
4224     }
4225    
4226     /**
4227     * Replaces the current script with the new script source code text given
4228     * by @a text.
4229     *
4230     * @param text - new script source code
4231     */
4232     void Script::SetScriptAsText(const String& text) {
4233     data.resize(text.size());
4234     memcpy(&data[0], &text[0], text.size());
4235     }
4236    
4237 schoenebeck 2682 /**
4238     * Apply this script to the respective RIFF chunks. You have to call
4239     * File::Save() to make changes persistent.
4240     *
4241     * Usually there is absolutely no need to call this method explicitly.
4242     * It will be called automatically when File::Save() was called.
4243     *
4244     * @param pProgress - callback function for progress notification
4245     */
4246     void Script::UpdateChunks(progress_t* pProgress) {
4247 schoenebeck 2584 // recalculate CRC32 check sum
4248     __resetCRC(crc);
4249     __calculateCRC(&data[0], data.size(), crc);
4250 schoenebeck 3115 __finalizeCRC(crc);
4251 schoenebeck 2584 // make sure chunk exists and has the required size
4252 schoenebeck 3053 const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4253 schoenebeck 2584 if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4254     else pChunk->Resize(chunkSize);
4255     // fill the chunk data to be written to disk
4256     uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4257     int pos = 0;
4258 schoenebeck 3053 store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4259 schoenebeck 2584 pos += sizeof(int32_t);
4260     store32(&pData[pos], Compression);
4261     pos += sizeof(int32_t);
4262     store32(&pData[pos], Encoding);
4263     pos += sizeof(int32_t);
4264     store32(&pData[pos], Language);
4265     pos += sizeof(int32_t);
4266     store32(&pData[pos], Bypass ? 1 : 0);
4267     pos += sizeof(int32_t);
4268     store32(&pData[pos], crc);
4269     pos += sizeof(int32_t);
4270 schoenebeck 3053 store32(&pData[pos], (uint32_t) Name.size());
4271 schoenebeck 2584 pos += sizeof(int32_t);
4272     for (int i = 0; i < Name.size(); ++i, ++pos)
4273     pData[pos] = Name[i];
4274     for (int i = 0; i < data.size(); ++i, ++pos)
4275     pData[pos] = data[i];
4276     }
4277    
4278     /**
4279     * Move this script from its current ScriptGroup to another ScriptGroup
4280     * given by @a pGroup.
4281     *
4282     * @param pGroup - script's new group
4283     */
4284     void Script::SetGroup(ScriptGroup* pGroup) {
4285 persson 2836 if (this->pGroup == pGroup) return;
4286 schoenebeck 2584 if (pChunk)
4287     pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4288     this->pGroup = pGroup;
4289     }
4290    
4291 schoenebeck 2601 /**
4292     * Returns the script group this script currently belongs to. Each script
4293     * is a member of exactly one ScriptGroup.
4294     *
4295     * @returns current script group
4296     */
4297     ScriptGroup* Script::GetGroup() const {
4298     return pGroup;
4299     }
4300    
4301 schoenebeck 2584 void Script::RemoveAllScriptReferences() {
4302     File* pFile = pGroup->pFile;
4303     for (int i = 0; pFile->GetInstrument(i); ++i) {
4304     Instrument* instr = pFile->GetInstrument(i);
4305     instr->RemoveScript(this);
4306     }
4307     }
4308    
4309     // *************** ScriptGroup ***************
4310     // *
4311    
4312     ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4313     pFile = file;
4314     pList = lstRTIS;
4315     pScripts = NULL;
4316     if (lstRTIS) {
4317     RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4318     ::LoadString(ckName, Name);
4319     } else {
4320     Name = "Default Group";
4321     }
4322     }
4323    
4324     ScriptGroup::~ScriptGroup() {
4325     if (pScripts) {
4326     std::list<Script*>::iterator iter = pScripts->begin();
4327     std::list<Script*>::iterator end = pScripts->end();
4328     while (iter != end) {
4329     delete *iter;
4330     ++iter;
4331     }
4332     delete pScripts;
4333     }
4334     }
4335    
4336 schoenebeck 2682 /**
4337     * Apply this script group to the respective RIFF chunks. You have to call
4338     * File::Save() to make changes persistent.
4339     *
4340     * Usually there is absolutely no need to call this method explicitly.
4341     * It will be called automatically when File::Save() was called.
4342     *
4343     * @param pProgress - callback function for progress notification
4344     */
4345     void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4346 schoenebeck 2584 if (pScripts) {
4347     if (!pList)
4348     pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4349    
4350     // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4351     ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4352    
4353     for (std::list<Script*>::iterator it = pScripts->begin();
4354     it != pScripts->end(); ++it)
4355     {
4356 schoenebeck 2682 (*it)->UpdateChunks(pProgress);
4357 schoenebeck 2584 }
4358     }
4359     }
4360    
4361     /** @brief Get instrument script.
4362     *
4363     * Returns the real-time instrument script with the given index.
4364     *
4365     * @param index - number of the sought script (0..n)
4366     * @returns sought script or NULL if there's no such script
4367     */
4368     Script* ScriptGroup::GetScript(uint index) {
4369     if (!pScripts) LoadScripts();
4370     std::list<Script*>::iterator it = pScripts->begin();
4371     for (uint i = 0; it != pScripts->end(); ++i, ++it)
4372     if (i == index) return *it;
4373     return NULL;
4374     }
4375    
4376     /** @brief Add new instrument script.
4377     *
4378     * Adds a new real-time instrument script to the file. The script is not
4379     * actually used / executed unless it is referenced by an instrument to be
4380     * used. This is similar to samples, which you can add to a file, without
4381     * an instrument necessarily actually using it.
4382     *
4383     * You have to call Save() to make this persistent to the file.
4384     *
4385     * @return new empty script object
4386     */
4387     Script* ScriptGroup::AddScript() {
4388     if (!pScripts) LoadScripts();
4389     Script* pScript = new Script(this, NULL);
4390     pScripts->push_back(pScript);
4391     return pScript;
4392     }
4393    
4394     /** @brief Delete an instrument script.
4395     *
4396     * This will delete the given real-time instrument script. References of
4397     * instruments that are using that script will be removed accordingly.
4398     *
4399     * You have to call Save() to make this persistent to the file.
4400     *
4401     * @param pScript - script to delete
4402     * @throws gig::Exception if given script could not be found
4403     */
4404     void ScriptGroup::DeleteScript(Script* pScript) {
4405     if (!pScripts) LoadScripts();
4406     std::list<Script*>::iterator iter =
4407     find(pScripts->begin(), pScripts->end(), pScript);
4408     if (iter == pScripts->end())
4409     throw gig::Exception("Could not delete script, could not find given script");
4410     pScripts->erase(iter);
4411     pScript->RemoveAllScriptReferences();
4412     if (pScript->pChunk)
4413     pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4414     delete pScript;
4415     }
4416    
4417     void ScriptGroup::LoadScripts() {
4418     if (pScripts) return;
4419     pScripts = new std::list<Script*>;
4420     if (!pList) return;
4421    
4422     for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4423     ck = pList->GetNextSubChunk())
4424     {
4425     if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4426     pScripts->push_back(new Script(this, ck));
4427     }
4428     }
4429     }
4430    
4431 schoenebeck 2 // *************** Instrument ***************
4432     // *
4433    
4434 schoenebeck 515 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4435 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
4436 persson 1180 { CHUNK_ID_INAM, 64 },
4437     { CHUNK_ID_ISFT, 12 },
4438     { 0, 0 }
4439     };
4440 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
4441 persson 918
4442 schoenebeck 2 // Initialization
4443     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4444 persson 1182 EffectSend = 0;
4445     Attenuation = 0;
4446     FineTune = 0;
4447 schoenebeck 3112 PitchbendRange = 2;
4448 persson 1182 PianoReleaseMode = false;
4449     DimensionKeyRange.low = 0;
4450     DimensionKeyRange.high = 0;
4451 persson 1678 pMidiRules = new MidiRule*[3];
4452     pMidiRules[0] = NULL;
4453 schoenebeck 2584 pScriptRefs = NULL;
4454 schoenebeck 2
4455     // Loading
4456     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
4457     if (lart) {
4458     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4459     if (_3ewg) {
4460     EffectSend = _3ewg->ReadUint16();
4461     Attenuation = _3ewg->ReadInt32();
4462     FineTune = _3ewg->ReadInt16();
4463     PitchbendRange = _3ewg->ReadInt16();
4464     uint8_t dimkeystart = _3ewg->ReadUint8();
4465     PianoReleaseMode = dimkeystart & 0x01;
4466     DimensionKeyRange.low = dimkeystart >> 1;
4467     DimensionKeyRange.high = _3ewg->ReadUint8();
4468 persson 1627
4469     if (_3ewg->GetSize() > 32) {
4470     // read MIDI rules
4471 persson 1678 int i = 0;
4472 persson 1627 _3ewg->SetPos(32);
4473     uint8_t id1 = _3ewg->ReadUint8();
4474     uint8_t id2 = _3ewg->ReadUint8();
4475    
4476 persson 2450 if (id2 == 16) {
4477     if (id1 == 4) {
4478     pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4479     } else if (id1 == 0) {
4480     pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4481     } else if (id1 == 3) {
4482     pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4483     } else {
4484     pMidiRules[i++] = new MidiRuleUnknown;
4485     }
4486 persson 1627 }
4487 persson 2450 else if (id1 != 0 || id2 != 0) {
4488     pMidiRules[i++] = new MidiRuleUnknown;
4489     }
4490 persson 1627 //TODO: all the other types of rules
4491 persson 1678
4492     pMidiRules[i] = NULL;
4493 persson 1627 }
4494 schoenebeck 2 }
4495     }
4496    
4497 schoenebeck 1524 if (pFile->GetAutoLoad()) {
4498     if (!pRegions) pRegions = new RegionList;
4499     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4500     if (lrgn) {
4501     RIFF::List* rgn = lrgn->GetFirstSubList();
4502     while (rgn) {
4503     if (rgn->GetListType() == LIST_TYPE_RGN) {
4504     __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4505     pRegions->push_back(new Region(this, rgn));
4506     }
4507     rgn = lrgn->GetNextSubList();
4508 schoenebeck 809 }
4509 schoenebeck 1524 // Creating Region Key Table for fast lookup
4510     UpdateRegionKeyTable();
4511 schoenebeck 2 }
4512     }
4513    
4514 schoenebeck 2584 // own gig format extensions
4515     RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4516     if (lst3LS) {
4517     RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4518     if (ckSCSL) {
4519 schoenebeck 2609 int headerSize = ckSCSL->ReadUint32();
4520     int slotCount = ckSCSL->ReadUint32();
4521     if (slotCount) {
4522     int slotSize = ckSCSL->ReadUint32();
4523     ckSCSL->SetPos(headerSize); // in case of future header extensions
4524     int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4525     for (int i = 0; i < slotCount; ++i) {
4526     _ScriptPooolEntry e;
4527     e.fileOffset = ckSCSL->ReadUint32();
4528     e.bypass = ckSCSL->ReadUint32() & 1;
4529     if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4530     scriptPoolFileOffsets.push_back(e);
4531     }
4532 schoenebeck 2584 }
4533     }
4534     }
4535    
4536 schoenebeck 809 __notify_progress(pProgress, 1.0f); // notify done
4537     }
4538    
4539     void Instrument::UpdateRegionKeyTable() {
4540 schoenebeck 1335 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4541 schoenebeck 823 RegionList::iterator iter = pRegions->begin();
4542     RegionList::iterator end = pRegions->end();
4543     for (; iter != end; ++iter) {
4544     gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4545     for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
4546     RegionKeyTable[iKey] = pRegion;
4547 schoenebeck 2 }
4548     }
4549     }
4550    
4551     Instrument::~Instrument() {
4552 persson 1950 for (int i = 0 ; pMidiRules[i] ; i++) {
4553     delete pMidiRules[i];
4554     }
4555 persson 1678 delete[] pMidiRules;
4556 schoenebeck 2584 if (pScriptRefs) delete pScriptRefs;
4557 schoenebeck 2 }
4558    
4559     /**
4560 schoenebeck 809 * Apply Instrument with all its Regions to the respective RIFF chunks.
4561     * You have to call File::Save() to make changes persistent.
4562     *
4563     * Usually there is absolutely no need to call this method explicitly.
4564     * It will be called automatically when File::Save() was called.
4565     *
4566 schoenebeck 2682 * @param pProgress - callback function for progress notification
4567 schoenebeck 809 * @throws gig::Exception if samples cannot be dereferenced
4568     */
4569 schoenebeck 2682 void Instrument::UpdateChunks(progress_t* pProgress) {
4570 schoenebeck 809 // first update base classes' chunks
4571 schoenebeck 2682 DLS::Instrument::UpdateChunks(pProgress);
4572 schoenebeck 809
4573     // update Regions' chunks
4574 schoenebeck 823 {
4575     RegionList::iterator iter = pRegions->begin();
4576     RegionList::iterator end = pRegions->end();
4577     for (; iter != end; ++iter)
4578 schoenebeck 2682 (*iter)->UpdateChunks(pProgress);
4579 schoenebeck 823 }
4580 schoenebeck 809
4581     // make sure 'lart' RIFF list chunk exists
4582     RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
4583     if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4584     // make sure '3ewg' RIFF chunk exists
4585     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4586 persson 1264 if (!_3ewg) {
4587     File* pFile = (File*) GetParent();
4588    
4589     // 3ewg is bigger in gig3, as it includes the iMIDI rules
4590     int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4591     _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4592     memset(_3ewg->LoadChunkData(), 0, size);
4593     }
4594 schoenebeck 809 // update '3ewg' RIFF chunk
4595     uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4596 persson 1179 store16(&pData[0], EffectSend);
4597     store32(&pData[2], Attenuation);
4598     store16(&pData[6], FineTune);
4599     store16(&pData[8], PitchbendRange);
4600 persson 1266 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4601 schoenebeck 809 DimensionKeyRange.low << 1;
4602 persson 1179 pData[10] = dimkeystart;
4603     pData[11] = DimensionKeyRange.high;
4604 persson 2450
4605     if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4606     pData[32] = 0;
4607     pData[33] = 0;
4608     } else {
4609     for (int i = 0 ; pMidiRules[i] ; i++) {
4610     pMidiRules[i]->UpdateChunks(pData);
4611     }
4612     }
4613 schoenebeck 2584
4614     // own gig format extensions
4615 schoenebeck 2648 if (ScriptSlotCount()) {
4616     // make sure we have converted the original loaded script file
4617     // offsets into valid Script object pointers
4618     LoadScripts();
4619    
4620 schoenebeck 2584 RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4621     if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4622 schoenebeck 3053 const int slotCount = (int) pScriptRefs->size();
4623 schoenebeck 2609 const int headerSize = 3 * sizeof(uint32_t);
4624     const int slotSize = 2 * sizeof(uint32_t);
4625     const int totalChunkSize = headerSize + slotCount * slotSize;
4626 schoenebeck 2584 RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4627 schoenebeck 2609 if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4628     else ckSCSL->Resize(totalChunkSize);
4629 schoenebeck 2584 uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4630 schoenebeck 2609 int pos = 0;
4631     store32(&pData[pos], headerSize);
4632     pos += sizeof(uint32_t);
4633     store32(&pData[pos], slotCount);
4634     pos += sizeof(uint32_t);
4635     store32(&pData[pos], slotSize);
4636     pos += sizeof(uint32_t);
4637     for (int i = 0; i < slotCount; ++i) {
4638     // arbitrary value, the actual file offset will be updated in
4639     // UpdateScriptFileOffsets() after the file has been resized
4640     int bogusFileOffset = 0;
4641     store32(&pData[pos], bogusFileOffset);
4642 schoenebeck 2584 pos += sizeof(uint32_t);
4643     store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4644     pos += sizeof(uint32_t);
4645     }
4646 schoenebeck 2648 } else {
4647     // no script slots, so get rid of any LS custom RIFF chunks (if any)
4648     RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4649     if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4650 schoenebeck 2584 }
4651 schoenebeck 809 }
4652    
4653 schoenebeck 2609 void Instrument::UpdateScriptFileOffsets() {
4654     // own gig format extensions
4655 schoenebeck 2667 if (pScriptRefs && pScriptRefs->size() > 0) {
4656 schoenebeck 2609 RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4657     RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4658 schoenebeck 3053 const int slotCount = (int) pScriptRefs->size();
4659 schoenebeck 2609 const int headerSize = 3 * sizeof(uint32_t);
4660     ckSCSL->SetPos(headerSize);
4661     for (int i = 0; i < slotCount; ++i) {
4662 schoenebeck 3053 uint32_t fileOffset = uint32_t(
4663 schoenebeck 2609 (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4664     (*pScriptRefs)[i].script->pChunk->GetPos() -
4665 schoenebeck 3053 CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4666     );
4667 schoenebeck 2609 ckSCSL->WriteUint32(&fileOffset);
4668     // jump over flags entry (containing the bypass flag)
4669     ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4670     }
4671     }
4672     }
4673    
4674 schoenebeck 809 /**
4675 schoenebeck 2 * Returns the appropriate Region for a triggered note.
4676     *
4677     * @param Key MIDI Key number of triggered note / key (0 - 127)
4678     * @returns pointer adress to the appropriate Region or NULL if there
4679     * there is no Region defined for the given \a Key
4680     */
4681     Region* Instrument::GetRegion(unsigned int Key) {
4682 schoenebeck 1335 if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4683 schoenebeck 2 return RegionKeyTable[Key];
4684 schoenebeck 823
4685 schoenebeck 2 /*for (int i = 0; i < Regions; i++) {
4686     if (Key <= pRegions[i]->KeyRange.high &&
4687     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
4688     }
4689     return NULL;*/
4690     }
4691    
4692     /**
4693     * Returns the first Region of the instrument. You have to call this
4694     * method once before you use GetNextRegion().
4695     *
4696     * @returns pointer address to first region or NULL if there is none
4697     * @see GetNextRegion()
4698     */
4699     Region* Instrument::GetFirstRegion() {
4700 schoenebeck 823 if (!pRegions) return NULL;
4701     RegionsIterator = pRegions->begin();
4702     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4703 schoenebeck 2 }
4704    
4705     /**
4706     * Returns the next Region of the instrument. You have to call
4707     * GetFirstRegion() once before you can use this method. By calling this
4708     * method multiple times it iterates through the available Regions.
4709     *
4710     * @returns pointer address to the next region or NULL if end reached
4711     * @see GetFirstRegion()
4712     */
4713     Region* Instrument::GetNextRegion() {
4714 schoenebeck 823 if (!pRegions) return NULL;
4715     RegionsIterator++;
4716     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4717 schoenebeck 2 }
4718    
4719 schoenebeck 809 Region* Instrument::AddRegion() {
4720     // create new Region object (and its RIFF chunks)
4721     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
4722     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4723     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4724     Region* pNewRegion = new Region(this, rgn);
4725 schoenebeck 823 pRegions->push_back(pNewRegion);
4726 schoenebeck 3053 Regions = (uint32_t) pRegions->size();
4727 schoenebeck 809 // update Region key table for fast lookup
4728     UpdateRegionKeyTable();
4729     // done
4730     return pNewRegion;
4731     }
4732 schoenebeck 2
4733 schoenebeck 809 void Instrument::DeleteRegion(Region* pRegion) {
4734     if (!pRegions) return;
4735 schoenebeck 823 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
4736 schoenebeck 809 // update Region key table for fast lookup
4737     UpdateRegionKeyTable();
4738     }
4739 schoenebeck 2
4740 persson 1627 /**
4741 schoenebeck 2700 * Move this instrument at the position before @arg dst.
4742     *
4743     * This method can be used to reorder the sequence of instruments in a
4744     * .gig file. This might be helpful especially on large .gig files which
4745     * contain a large number of instruments within the same .gig file. So
4746     * grouping such instruments to similar ones, can help to keep track of them
4747     * when working with such complex .gig files.
4748     *
4749     * When calling this method, this instrument will be removed from in its
4750     * current position in the instruments list and moved to the requested
4751     * target position provided by @param dst. You may also pass NULL as
4752     * argument to this method, in that case this intrument will be moved to the
4753     * very end of the .gig file's instrument list.
4754     *
4755     * You have to call Save() to make the order change persistent to the .gig
4756     * file.
4757     *
4758     * Currently this method is limited to moving the instrument within the same
4759     * .gig file. Trying to move it to another .gig file by calling this method
4760     * will throw an exception.
4761     *
4762     * @param dst - destination instrument at which this instrument will be
4763     * moved to, or pass NULL for moving to end of list
4764     * @throw gig::Exception if this instrument and target instrument are not
4765     * part of the same file
4766     */
4767     void Instrument::MoveTo(Instrument* dst) {
4768     if (dst && GetParent() != dst->GetParent())
4769     throw Exception(
4770     "gig::Instrument::MoveTo() can only be used for moving within "
4771     "the same gig file."
4772     );
4773    
4774     File* pFile = (File*) GetParent();
4775    
4776     // move this instrument within the instrument list
4777     {
4778 persson 2836 File::InstrumentList& list = *pFile->pInstruments;
4779 schoenebeck 2700
4780 persson 2836 File::InstrumentList::iterator itFrom =
4781 schoenebeck 2700 std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4782    
4783 persson 2836 File::InstrumentList::iterator itTo =
4784 schoenebeck 2700 std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4785    
4786     list.splice(itTo, list, itFrom);
4787     }
4788    
4789     // move the instrument's actual list RIFF chunk appropriately
4790     RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4791     lstCkInstruments->MoveSubChunk(
4792     this->pCkInstrument,
4793 schoenebeck 2702 (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4794 schoenebeck 2700 );
4795     }
4796    
4797     /**
4798 persson 1678 * Returns a MIDI rule of the instrument.
4799 persson 1627 *
4800     * The list of MIDI rules, at least in gig v3, always contains at
4801     * most two rules. The second rule can only be the DEF filter
4802     * (which currently isn't supported by libgig).
4803     *
4804 persson 1678 * @param i - MIDI rule number
4805     * @returns pointer address to MIDI rule number i or NULL if there is none
4806 persson 1627 */
4807 persson 1678 MidiRule* Instrument::GetMidiRule(int i) {
4808     return pMidiRules[i];
4809 persson 1627 }
4810 persson 2450
4811 schoenebeck 2394 /**
4812 persson 2450 * Adds the "controller trigger" MIDI rule to the instrument.
4813     *
4814     * @returns the new MIDI rule
4815     */
4816     MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4817     delete pMidiRules[0];
4818     MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4819     pMidiRules[0] = r;
4820     pMidiRules[1] = 0;
4821     return r;
4822     }
4823    
4824     /**
4825     * Adds the legato MIDI rule to the instrument.
4826     *
4827     * @returns the new MIDI rule
4828     */
4829     MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4830     delete pMidiRules[0];
4831     MidiRuleLegato* r = new MidiRuleLegato;
4832     pMidiRules[0] = r;
4833     pMidiRules[1] = 0;
4834     return r;
4835     }
4836    
4837     /**
4838     * Adds the alternator MIDI rule to the instrument.
4839     *
4840     * @returns the new MIDI rule
4841     */
4842     MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4843     delete pMidiRules[0];
4844     MidiRuleAlternator* r = new MidiRuleAlternator;
4845     pMidiRules[0] = r;
4846     pMidiRules[1] = 0;
4847     return r;
4848     }
4849    
4850     /**
4851     * Deletes a MIDI rule from the instrument.
4852     *
4853     * @param i - MIDI rule number
4854     */
4855     void Instrument::DeleteMidiRule(int i) {
4856     delete pMidiRules[i];
4857     pMidiRules[i] = 0;
4858     }
4859    
4860 schoenebeck 2584 void Instrument::LoadScripts() {
4861     if (pScriptRefs) return;
4862     pScriptRefs = new std::vector<_ScriptPooolRef>;
4863     if (scriptPoolFileOffsets.empty()) return;
4864     File* pFile = (File*) GetParent();
4865     for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4866 schoenebeck 2609 uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4867 schoenebeck 2584 for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4868     ScriptGroup* group = pFile->GetScriptGroup(i);
4869     for (uint s = 0; group->GetScript(s); ++s) {
4870     Script* script = group->GetScript(s);
4871     if (script->pChunk) {
4872 schoenebeck 3053 uint32_t offset = uint32_t(
4873     script->pChunk->GetFilePos() -
4874     script->pChunk->GetPos() -
4875     CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
4876     );
4877 schoenebeck 2609 if (offset == soughtOffset)
4878 schoenebeck 2584 {
4879     _ScriptPooolRef ref;
4880     ref.script = script;
4881     ref.bypass = scriptPoolFileOffsets[k].bypass;
4882     pScriptRefs->push_back(ref);
4883     break;
4884     }
4885     }
4886     }
4887     }
4888     }
4889     // we don't need that anymore
4890     scriptPoolFileOffsets.clear();
4891     }
4892    
4893 schoenebeck 2593 /** @brief Get instrument script (gig format extension).
4894 schoenebeck 2584 *
4895 schoenebeck 2593 * Returns the real-time instrument script of instrument script slot
4896     * @a index.
4897     *
4898     * @note This is an own format extension which did not exist i.e. in the
4899     * GigaStudio 4 software. It will currently only work with LinuxSampler and
4900     * gigedit.
4901     *
4902     * @param index - instrument script slot index
4903     * @returns script or NULL if index is out of bounds
4904     */
4905     Script* Instrument::GetScriptOfSlot(uint index) {
4906     LoadScripts();
4907     if (index >= pScriptRefs->size()) return NULL;
4908     return pScriptRefs->at(index).script;
4909     }
4910    
4911     /** @brief Add new instrument script slot (gig format extension).
4912     *
4913 schoenebeck 2584 * Add the given real-time instrument script reference to this instrument,
4914     * which shall be executed by the sampler for for this instrument. The
4915     * script will be added to the end of the script list of this instrument.
4916     * The positions of the scripts in the Instrument's Script list are
4917     * relevant, because they define in which order they shall be executed by
4918     * the sampler. For this reason it is also legal to add the same script
4919     * twice to an instrument, for example you might have a script called
4920     * "MyFilter" which performs an event filter task, and you might have
4921     * another script called "MyNoteTrigger" which triggers new notes, then you
4922     * might for example have the following list of scripts on the instrument:
4923     *
4924     * 1. Script "MyFilter"
4925     * 2. Script "MyNoteTrigger"
4926     * 3. Script "MyFilter"
4927     *
4928     * Which would make sense, because the 2nd script launched new events, which
4929     * you might need to filter as well.
4930     *
4931     * There are two ways to disable / "bypass" scripts. You can either disable
4932     * a script locally for the respective script slot on an instrument (i.e. by
4933     * passing @c false to the 2nd argument of this method, or by calling
4934     * SetScriptBypassed()). Or you can disable a script globally for all slots
4935     * and all instruments by setting Script::Bypass.
4936     *
4937     * @note This is an own format extension which did not exist i.e. in the
4938     * GigaStudio 4 software. It will currently only work with LinuxSampler and
4939     * gigedit.
4940     *
4941     * @param pScript - script that shall be executed for this instrument
4942     * @param bypass - if enabled, the sampler shall skip executing this
4943     * script (in the respective list position)
4944     * @see SetScriptBypassed()
4945     */
4946     void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4947     LoadScripts();
4948     _ScriptPooolRef ref = { pScript, bypass };
4949     pScriptRefs->push_back(ref);
4950     }
4951    
4952     /** @brief Flip two script slots with each other (gig format extension).
4953     *
4954     * Swaps the position of the two given scripts in the Instrument's Script
4955     * list. The positions of the scripts in the Instrument's Script list are
4956     * relevant, because they define in which order they shall be executed by
4957     * the sampler.
4958     *
4959     * @note This is an own format extension which did not exist i.e. in the
4960     * GigaStudio 4 software. It will currently only work with LinuxSampler and
4961     * gigedit.
4962     *
4963     * @param index1 - index of the first script slot to swap
4964     * @param index2 - index of the second script slot to swap
4965     */
4966     void Instrument::SwapScriptSlots(uint index1, uint index2) {
4967     LoadScripts();
4968     if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4969     return;
4970     _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4971     (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4972     (*pScriptRefs)[index2] = tmp;
4973     }
4974    
4975     /** @brief Remove script slot.
4976     *
4977     * Removes the script slot with the given slot index.
4978     *
4979     * @param index - index of script slot to remove
4980     */
4981     void Instrument::RemoveScriptSlot(uint index) {
4982     LoadScripts();
4983     if (index >= pScriptRefs->size()) return;
4984     pScriptRefs->erase( pScriptRefs->begin() + index );
4985     }
4986    
4987     /** @brief Remove reference to given Script (gig format extension).
4988     *
4989     * This will remove all script slots on the instrument which are referencing
4990     * the given script.
4991     *
4992     * @note This is an own format extension which did not exist i.e. in the
4993     * GigaStudio 4 software. It will currently only work with LinuxSampler and
4994     * gigedit.
4995     *
4996     * @param pScript - script reference to remove from this instrument
4997     * @see RemoveScriptSlot()
4998     */
4999     void Instrument::RemoveScript(Script* pScript) {
5000     LoadScripts();
5001 schoenebeck 3053 for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5002 schoenebeck 2584 if ((*pScriptRefs)[i].script == pScript) {
5003     pScriptRefs->erase( pScriptRefs->begin() + i );
5004     }
5005     }
5006     }
5007    
5008     /** @brief Instrument's amount of script slots.
5009     *
5010     * This method returns the amount of script slots this instrument currently
5011     * uses.
5012     *
5013     * A script slot is a reference of a real-time instrument script to be
5014     * executed by the sampler. The scripts will be executed by the sampler in
5015     * sequence of the slots. One (same) script may be referenced multiple
5016     * times in different slots.
5017     *
5018     * @note This is an own format extension which did not exist i.e. in the
5019     * GigaStudio 4 software. It will currently only work with LinuxSampler and
5020     * gigedit.
5021     */
5022     uint Instrument::ScriptSlotCount() const {
5023 schoenebeck 3053 return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5024 schoenebeck 2584 }
5025    
5026     /** @brief Whether script execution shall be skipped.
5027     *
5028     * Defines locally for the Script reference slot in the Instrument's Script
5029     * list, whether the script shall be skipped by the sampler regarding
5030     * execution.
5031     *
5032     * It is also possible to ignore exeuction of the script globally, for all
5033     * slots and for all instruments by setting Script::Bypass.
5034     *
5035     * @note This is an own format extension which did not exist i.e. in the
5036     * GigaStudio 4 software. It will currently only work with LinuxSampler and
5037     * gigedit.
5038     *
5039     * @param index - index of the script slot on this instrument
5040     * @see Script::Bypass
5041     */
5042     bool Instrument::IsScriptSlotBypassed(uint index) {
5043     if (index >= ScriptSlotCount()) return false;
5044     return pScriptRefs ? pScriptRefs->at(index).bypass
5045     : scriptPoolFileOffsets.at(index).bypass;
5046    
5047     }
5048    
5049     /** @brief Defines whether execution shall be skipped.
5050     *
5051     * You can call this method to define locally whether or whether not the
5052     * given script slot shall be executed by the sampler.
5053     *
5054     * @note This is an own format extension which did not exist i.e. in the
5055     * GigaStudio 4 software. It will currently only work with LinuxSampler and
5056     * gigedit.
5057     *
5058     * @param index - script slot index on this instrument
5059     * @param bBypass - if true, the script slot will be skipped by the sampler
5060     * @see Script::Bypass
5061     */
5062     void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5063     if (index >= ScriptSlotCount()) return;
5064     if (pScriptRefs)
5065     pScriptRefs->at(index).bypass = bBypass;
5066     else
5067     scriptPoolFileOffsets.at(index).bypass = bBypass;
5068     }
5069    
5070 persson 2450 /**
5071 schoenebeck 2394 * Make a (semi) deep copy of the Instrument object given by @a orig
5072     * and assign it to this object.
5073     *
5074     * Note that all sample pointers referenced by @a orig are simply copied as
5075     * memory address. Thus the respective samples are shared, not duplicated!
5076     *
5077     * @param orig - original Instrument object to be copied from
5078     */
5079     void Instrument::CopyAssign(const Instrument* orig) {
5080 schoenebeck 2482 CopyAssign(orig, NULL);
5081     }
5082    
5083     /**
5084     * Make a (semi) deep copy of the Instrument object given by @a orig
5085     * and assign it to this object.
5086     *
5087     * @param orig - original Instrument object to be copied from
5088     * @param mSamples - crosslink map between the foreign file's samples and
5089     * this file's samples
5090     */
5091     void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5092 schoenebeck 2394 // handle base class
5093     // (without copying DLS region stuff)
5094     DLS::Instrument::CopyAssignCore(orig);
5095    
5096     // handle own member variables
5097     Attenuation = orig->Attenuation;
5098     EffectSend = orig->EffectSend;
5099     FineTune = orig->FineTune;
5100     PitchbendRange = orig->PitchbendRange;
5101     PianoReleaseMode = orig->PianoReleaseMode;
5102     DimensionKeyRange = orig->DimensionKeyRange;
5103 schoenebeck 2584 scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5104     pScriptRefs = orig->pScriptRefs;
5105 schoenebeck 2394
5106     // free old midi rules
5107     for (int i = 0 ; pMidiRules[i] ; i++) {
5108     delete pMidiRules[i];
5109     }
5110     //TODO: MIDI rule copying
5111     pMidiRules[0] = NULL;
5112    
5113     // delete all old regions
5114     while (Regions) DeleteRegion(GetFirstRegion());
5115     // create new regions and copy them from original
5116     {
5117     RegionList::const_iterator it = orig->pRegions->begin();
5118     for (int i = 0; i < orig->Regions; ++i, ++it) {
5119     Region* dstRgn = AddRegion();
5120     //NOTE: Region does semi-deep copy !
5121     dstRgn->CopyAssign(
5122 schoenebeck 2482 static_cast<gig::Region*>(*it),
5123     mSamples
5124 schoenebeck 2394 );
5125     }
5126     }
5127 schoenebeck 809
5128 schoenebeck 2394 UpdateRegionKeyTable();
5129     }
5130 schoenebeck 809
5131 schoenebeck 2394
5132 schoenebeck 929 // *************** Group ***************
5133     // *
5134    
5135     /** @brief Constructor.
5136     *
5137 schoenebeck 930 * @param file - pointer to the gig::File object
5138     * @param ck3gnm - pointer to 3gnm chunk associated with this group or
5139     * NULL if this is a new Group
5140 schoenebeck 929 */
5141 schoenebeck 930 Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5142 schoenebeck 929 pFile = file;
5143     pNameChunk = ck3gnm;
5144     ::LoadString(pNameChunk, Name);
5145     }
5146    
5147     Group::~Group() {
5148 schoenebeck 1099 // remove the chunk associated with this group (if any)
5149     if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5150 schoenebeck 929 }
5151    
5152     /** @brief Update chunks with current group settings.
5153     *
5154 schoenebeck 1098 * Apply current Group field values to the respective chunks. You have
5155     * to call File::Save() to make changes persistent.
5156     *
5157     * Usually there is absolutely no need to call this method explicitly.
5158     * It will be called automatically when File::Save() was called.
5159 schoenebeck 2682 *
5160     * @param pProgress - callback function for progress notification
5161 schoenebeck 929 */
5162 schoenebeck 2682 void Group::UpdateChunks(progress_t* pProgress) {
5163 schoenebeck 929 // make sure <3gri> and <3gnl> list chunks exist
5164 schoenebeck 930 RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5165 persson 1192 if (!_3gri) {
5166     _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5167     pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5168     }
5169 schoenebeck 929 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5170 persson 1182 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5171 persson 1266
5172     if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5173     // v3 has a fixed list of 128 strings, find a free one
5174     for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5175     if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5176     pNameChunk = ck;
5177     break;
5178     }
5179     }
5180     }
5181    
5182 schoenebeck 929 // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5183     ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5184     }
5185    
5186 schoenebeck 930 /**
5187     * Returns the first Sample of this Group. You have to call this method
5188     * once before you use GetNextSample().
5189     *
5190     * <b>Notice:</b> this method might block for a long time, in case the
5191     * samples of this .gig file were not scanned yet
5192     *
5193     * @returns pointer address to first Sample or NULL if there is none
5194     * applied to this Group
5195     * @see GetNextSample()
5196     */
5197     Sample* Group::GetFirstSample() {
5198     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5199     for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5200     if (pSample->GetGroup() == this) return pSample;
5201     }
5202     return NULL;
5203     }
5204 schoenebeck 929
5205 schoenebeck 930 /**
5206     * Returns the next Sample of the Group. You have to call
5207     * GetFirstSample() once before you can use this method. By calling this
5208     * method multiple times it iterates through the Samples assigned to
5209     * this Group.
5210     *
5211     * @returns pointer address to the next Sample of this Group or NULL if
5212     * end reached
5213     * @see GetFirstSample()
5214     */
5215     Sample* Group::GetNextSample() {
5216     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5217     for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5218     if (pSample->GetGroup() == this) return pSample;
5219     }
5220     return NULL;
5221     }
5222 schoenebeck 929
5223 schoenebeck 930 /**
5224     * Move Sample given by \a pSample from another Group to this Group.
5225     */
5226     void Group::AddSample(Sample* pSample) {
5227     pSample->pGroup = this;
5228     }
5229    
5230     /**
5231     * Move all members of this group to another group (preferably the 1st
5232     * one except this). This method is called explicitly by
5233     * File::DeleteGroup() thus when a Group was deleted. This code was
5234     * intentionally not placed in the destructor!
5235     */
5236     void Group::MoveAll() {
5237     // get "that" other group first
5238     Group* pOtherGroup = NULL;
5239     for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5240     if (pOtherGroup != this) break;
5241     }
5242     if (!pOtherGroup) throw Exception(
5243     "Could not move samples to another group, since there is no "
5244     "other Group. This is a bug, report it!"
5245     );
5246     // now move all samples of this group to the other group
5247     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5248     pOtherGroup->AddSample(pSample);
5249     }
5250     }
5251    
5252    
5253    
5254 schoenebeck 2 // *************** File ***************
5255     // *
5256    
5257 schoenebeck 1384 /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5258 persson 1199 const DLS::version_t File::VERSION_2 = {
5259     0, 2, 19980628 & 0xffff, 19980628 >> 16
5260     };
5261    
5262 schoenebeck 1384 /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5263 persson 1199 const DLS::version_t File::VERSION_3 = {
5264     0, 3, 20030331 & 0xffff, 20030331 >> 16
5265     };
5266    
5267 schoenebeck 1416 static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5268 persson 1180 { CHUNK_ID_IARL, 256 },
5269     { CHUNK_ID_IART, 128 },
5270     { CHUNK_ID_ICMS, 128 },
5271     { CHUNK_ID_ICMT, 1024 },
5272     { CHUNK_ID_ICOP, 128 },
5273     { CHUNK_ID_ICRD, 128 },
5274     { CHUNK_ID_IENG, 128 },
5275     { CHUNK_ID_IGNR, 128 },
5276     { CHUNK_ID_IKEY, 128 },
5277     { CHUNK_ID_IMED, 128 },
5278     { CHUNK_ID_INAM, 128 },
5279     { CHUNK_ID_IPRD, 128 },
5280     { CHUNK_ID_ISBJ, 128 },
5281     { CHUNK_ID_ISFT, 128 },
5282     { CHUNK_ID_ISRC, 128 },
5283     { CHUNK_ID_ISRF, 128 },
5284     { CHUNK_ID_ITCH, 128 },
5285     { 0, 0 }
5286     };
5287    
5288 schoenebeck 809 File::File() : DLS::File() {
5289 schoenebeck 1524 bAutoLoad = true;
5290 persson 1264 *pVersion = VERSION_3;
5291 schoenebeck 929 pGroups = NULL;
5292 schoenebeck 2584 pScriptGroups = NULL;
5293 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5294 persson 1182 pInfo->ArchivalLocation = String(256, ' ');
5295 persson 1192
5296     // add some mandatory chunks to get the file chunks in right
5297     // order (INFO chunk will be moved to first position later)
5298     pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5299     pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5300 persson 1209 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5301    
5302     GenerateDLSID();
5303 schoenebeck 809 }
5304    
5305 schoenebeck 2 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5306 schoenebeck 1524 bAutoLoad = true;
5307 schoenebeck 929 pGroups = NULL;
5308 schoenebeck 2584 pScriptGroups = NULL;
5309 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5310 schoenebeck 2 }
5311    
5312 schoenebeck 929 File::~File() {
5313     if (pGroups) {
5314     std::list<Group*>::iterator iter = pGroups->begin();
5315     std::list<Group*>::iterator end = pGroups->end();
5316     while (iter != end) {
5317     delete *iter;
5318     ++iter;
5319     }
5320     delete pGroups;
5321     }
5322 schoenebeck 2584 if (pScriptGroups) {
5323     std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5324     std::list<ScriptGroup*>::iterator end = pScriptGroups->end();
5325     while (iter != end) {
5326     delete *iter;
5327     ++iter;
5328     }
5329     delete pScriptGroups;
5330     }
5331 schoenebeck 929 }
5332    
5333 schoenebeck 515 Sample* File::GetFirstSample(progress_t* pProgress) {
5334     if (!pSamples) LoadSamples(pProgress);
5335 schoenebeck 2 if (!pSamples) return NULL;
5336     SamplesIterator = pSamples->begin();
5337     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5338     }
5339    
5340     Sample* File::GetNextSample() {
5341     if (!pSamples) return NULL;
5342     SamplesIterator++;
5343     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5344     }
5345 schoenebeck 2482
5346     /**
5347     * Returns Sample object of @a index.
5348     *
5349     * @returns sample object or NULL if index is out of bounds
5350     */
5351     Sample* File::GetSample(uint index) {
5352     if (!pSamples) LoadSamples();
5353     if (!pSamples) return NULL;
5354     DLS::File::SampleList::iterator it = pSamples->begin();
5355     for (int i = 0; i < index; ++i) {
5356     ++it;
5357     if (it == pSamples->end()) return NULL;
5358     }
5359     if (it == pSamples->end()) return NULL;
5360     return static_cast<gig::Sample*>( *it );
5361     }
5362 schoenebeck 2
5363 schoenebeck 809 /** @brief Add a new sample.
5364     *
5365     * This will create a new Sample object for the gig file. You have to
5366     * call Save() to make this persistent to the file.
5367     *
5368     * @returns pointer to new Sample object
5369     */
5370     Sample* File::AddSample() {
5371     if (!pSamples) LoadSamples();
5372     __ensureMandatoryChunksExist();
5373     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
5374     // create new Sample object and its respective 'wave' list chunk
5375     RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5376     Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5377 persson 1192
5378     // add mandatory chunks to get the chunks in right order
5379     wave->AddSubChunk(CHUNK_ID_FMT, 16);
5380     wave->AddSubList(LIST_TYPE_INFO);
5381    
5382 schoenebeck 809 pSamples->push_back(pSample);
5383     return pSample;
5384     }
5385    
5386     /** @brief Delete a sample.
5387     *
5388 schoenebeck 1292 * This will delete the given Sample object from the gig file. Any
5389     * references to this sample from Regions and DimensionRegions will be
5390     * removed. You have to call Save() to make this persistent to the file.
5391 schoenebeck 809 *
5392     * @param pSample - sample to delete
5393     * @throws gig::Exception if given sample could not be found
5394     */
5395     void File::DeleteSample(Sample* pSample) {
5396 schoenebeck 823 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5397     SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5398 schoenebeck 809 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5399 schoenebeck 1083 if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5400 schoenebeck 809 pSamples->erase(iter);
5401     delete pSample;
5402 persson 1266
5403 persson 1678 SampleList::iterator tmp = SamplesIterator;
5404 persson 1266 // remove all references to the sample
5405     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5406     instrument = GetNextInstrument()) {
5407     for (Region* region = instrument->GetFirstRegion() ; region ;
5408     region = instrument->GetNextRegion()) {
5409    
5410     if (region->GetSample() == pSample) region->SetSample(NULL);
5411    
5412     for (int i = 0 ; i < region->DimensionRegions ; i++) {
5413     gig::DimensionRegion *d = region->pDimensionRegions[i];
5414     if (d->pSample == pSample) d->pSample = NULL;
5415     }
5416     }
5417     }
5418 persson 1678 SamplesIterator = tmp; // restore iterator
5419 schoenebeck 809 }
5420    
5421 schoenebeck 823 void File::LoadSamples() {
5422     LoadSamples(NULL);
5423     }
5424    
5425 schoenebeck 515 void File::LoadSamples(progress_t* pProgress) {
5426 schoenebeck 930 // Groups must be loaded before samples, because samples will try
5427     // to resolve the group they belong to
5428 schoenebeck 1158 if (!pGroups) LoadGroups();
5429 schoenebeck 930
5430 schoenebeck 823 if (!pSamples) pSamples = new SampleList;
5431    
5432 persson 666 RIFF::File* file = pRIFF;
5433 schoenebeck 515
5434 persson 666 // just for progress calculation
5435     int iSampleIndex = 0;
5436     int iTotalSamples = WavePoolCount;
5437 schoenebeck 515
5438 persson 666 // check if samples should be loaded from extension files
5439 schoenebeck 2913 // (only for old gig files < 2 GB)
5440 persson 666 int lastFileNo = 0;
5441 schoenebeck 2913 if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5442 schoenebeck 2912 for (int i = 0 ; i < WavePoolCount ; i++) {
5443     if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5444     }
5445 persson 666 }
5446 schoenebeck 780 String name(pRIFF->GetFileName());
5447 schoenebeck 3053 int nameLen = (int) name.length();
5448 persson 666 char suffix[6];
5449 schoenebeck 780 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5450 schoenebeck 515
5451 persson 666 for (int fileNo = 0 ; ; ) {
5452     RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5453     if (wvpl) {
5454 schoenebeck 2912 file_offset_t wvplFileOffset = wvpl->GetFilePos();
5455 persson 666 RIFF::List* wave = wvpl->GetFirstSubList();
5456     while (wave) {
5457     if (wave->GetListType() == LIST_TYPE_WAVE) {
5458     // notify current progress
5459     const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5460     __notify_progress(pProgress, subprogress);
5461    
5462 schoenebeck 2912 file_offset_t waveFileOffset = wave->GetFilePos();
5463 schoenebeck 2989 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5464 persson 666
5465     iSampleIndex++;
5466     }
5467     wave = wvpl->GetNextSubList();
5468 schoenebeck 2 }
5469 persson 666
5470     if (fileNo == lastFileNo) break;
5471    
5472     // open extension file (*.gx01, *.gx02, ...)
5473     fileNo++;
5474     sprintf(suffix, ".gx%02d", fileNo);
5475     name.replace(nameLen, 5, suffix);
5476     file = new RIFF::File(name);
5477     ExtensionFiles.push_back(file);
5478 schoenebeck 823 } else break;
5479 schoenebeck 2 }
5480 persson 666
5481     __notify_progress(pProgress, 1.0); // notify done
5482 schoenebeck 2 }
5483    
5484     Instrument* File::GetFirstInstrument() {
5485     if (!pInstruments) LoadInstruments();
5486     if (!pInstruments) return NULL;
5487     InstrumentsIterator = pInstruments->begin();
5488 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5489 schoenebeck 2 }
5490    
5491     Instrument* File::GetNextInstrument() {
5492     if (!pInstruments) return NULL;
5493     InstrumentsIterator++;
5494 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5495 schoenebeck 2 }
5496    
5497 schoenebeck 21 /**
5498     * Returns the instrument with the given index.
5499     *
5500 schoenebeck 515 * @param index - number of the sought instrument (0..n)
5501     * @param pProgress - optional: callback function for progress notification
5502 schoenebeck 21 * @returns sought instrument or NULL if there's no such instrument
5503     */
5504 schoenebeck 515 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
5505     if (!pInstruments) {
5506     // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
5507    
5508     // sample loading subtask
5509     progress_t subprogress;
5510     __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5511     __notify_progress(&subprogress, 0.0f);
5512 schoenebeck 1524 if (GetAutoLoad())
5513     GetFirstSample(&subprogress); // now force all samples to be loaded
5514 schoenebeck 515 __notify_progress(&subprogress, 1.0f);
5515    
5516     // instrument loading subtask
5517     if (pProgress && pProgress->callback) {
5518     subprogress.__range_min = subprogress.__range_max;
5519     subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
5520     }
5521     __notify_progress(&subprogress, 0.0f);
5522     LoadInstruments(&subprogress);
5523     __notify_progress(&subprogress, 1.0f);
5524     }
5525 schoenebeck 21 if (!pInstruments) return NULL;
5526     InstrumentsIterator = pInstruments->begin();
5527     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5528 schoenebeck 823 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5529 schoenebeck 21 InstrumentsIterator++;
5530     }
5531     return NULL;
5532     }
5533    
5534 schoenebeck 809 /** @brief Add a new instrument definition.
5535     *
5536     * This will create a new Instrument object for the gig file. You have
5537     * to call Save() to make this persistent to the file.
5538     *
5539     * @returns pointer to new Instrument object
5540     */
5541     Instrument* File::AddInstrument() {
5542     if (!pInstruments) LoadInstruments();
5543     __ensureMandatoryChunksExist();
5544     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5545     RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5546 persson 1192
5547     // add mandatory chunks to get the chunks in right order
5548     lstInstr->AddSubList(LIST_TYPE_INFO);
5549 persson 1209 lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5550 persson 1192
5551 schoenebeck 809 Instrument* pInstrument = new Instrument(this, lstInstr);
5552 persson 1209 pInstrument->GenerateDLSID();
5553 persson 1182
5554 persson 1192 lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5555    
5556 persson 1182 // this string is needed for the gig to be loadable in GSt:
5557     pInstrument->pInfo->Software = "Endless Wave";
5558    
5559 schoenebeck 809 pInstruments->push_back(pInstrument);
5560     return pInstrument;
5561     }
5562 schoenebeck 2394
5563     /** @brief Add a duplicate of an existing instrument.
5564     *
5565     * Duplicates the instrument definition given by @a orig and adds it
5566     * to this file. This allows in an instrument editor application to
5567     * easily create variations of an instrument, which will be stored in
5568     * the same .gig file, sharing i.e. the same samples.
5569     *
5570     * Note that all sample pointers referenced by @a orig are simply copied as
5571     * memory address. Thus the respective samples are shared, not duplicated!
5572     *
5573     * You have to call Save() to make this persistent to the file.
5574     *
5575     * @param orig - original instrument to be copied
5576     * @returns duplicated copy of the given instrument
5577     */
5578     Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5579     Instrument* instr = AddInstrument();
5580     instr->CopyAssign(orig);
5581     return instr;
5582     }
5583 schoenebeck 2482
5584     /** @brief Add content of another existing file.
5585     *
5586     * Duplicates the samples, groups and instruments of the original file
5587     * given by @a pFile and adds them to @c this File. In case @c this File is
5588     * a new one that you haven't saved before, then you have to call
5589     * SetFileName() before calling AddContentOf(), because this method will
5590     * automatically save this file during operation, which is required for
5591     * writing the sample waveform data by disk streaming.
5592     *
5593     * @param pFile - original file whose's content shall be copied from
5594     */
5595     void File::AddContentOf(File* pFile) {
5596     static int iCallCount = -1;
5597     iCallCount++;
5598     std::map<Group*,Group*> mGroups;
5599     std::map<Sample*,Sample*> mSamples;
5600    
5601     // clone sample groups
5602     for (int i = 0; pFile->GetGroup(i); ++i) {
5603     Group* g = AddGroup();
5604     g->Name =
5605     "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5606     mGroups[pFile->GetGroup(i)] = g;
5607     }
5608    
5609     // clone samples (not waveform data here yet)
5610     for (int i = 0; pFile->GetSample(i); ++i) {
5611     Sample* s = AddSample();
5612     s->CopyAssignMeta(pFile->GetSample(i));
5613     mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5614     mSamples[pFile->GetSample(i)] = s;
5615     }
5616    
5617     //BUG: For some reason this method only works with this additional
5618     // Save() call in between here.
5619     //
5620     // Important: The correct one of the 2 Save() methods has to be called
5621     // here, depending on whether the file is completely new or has been
5622     // saved to disk already, otherwise it will result in data corruption.
5623     if (pRIFF->IsNew())
5624     Save(GetFileName());
5625     else
5626     Save();
5627    
5628     // clone instruments
5629     // (passing the crosslink table here for the cloned samples)
5630     for (int i = 0; pFile->GetInstrument(i); ++i) {
5631     Instrument* instr = AddInstrument();
5632     instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5633     }
5634    
5635     // Mandatory: file needs to be saved to disk at this point, so this
5636     // file has the correct size and data layout for writing the samples'
5637     // waveform data to disk.
5638     Save();
5639    
5640     // clone samples' waveform data
5641     // (using direct read & write disk streaming)
5642     for (int i = 0; pFile->GetSample(i); ++i) {
5643     mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5644     }
5645     }
5646 schoenebeck 809
5647     /** @brief Delete an instrument.
5648     *
5649     * This will delete the given Instrument object from the gig file. You
5650     * have to call Save() to make this persistent to the file.
5651     *
5652     * @param pInstrument - instrument to delete
5653 schoenebeck 1081 * @throws gig::Exception if given instrument could not be found
5654 schoenebeck 809 */
5655     void File::DeleteInstrument(Instrument* pInstrument) {
5656     if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5657 schoenebeck 823 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5658 schoenebeck 809 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5659     pInstruments->erase(iter);
5660     delete pInstrument;
5661     }
5662    
5663 schoenebeck 823 void File::LoadInstruments() {
5664     LoadInstruments(NULL);
5665     }
5666    
5667 schoenebeck 515 void File::LoadInstruments(progress_t* pProgress) {
5668 schoenebeck 823 if (!pInstruments) pInstruments = new InstrumentList;
5669 schoenebeck 2 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5670     if (lstInstruments) {
5671 schoenebeck 515 int iInstrumentIndex = 0;
5672 schoenebeck 2 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
5673     while (lstInstr) {
5674     if (lstInstr->GetListType() == LIST_TYPE_INS) {
5675 schoenebeck 515 // notify current progress
5676     const float localProgress = (float) iInstrumentIndex / (float) Instruments;
5677     __notify_progress(pProgress, localProgress);
5678    
5679     // divide local progress into subprogress for loading current Instrument
5680     progress_t subprogress;
5681     __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5682    
5683     pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5684    
5685     iInstrumentIndex++;
5686 schoenebeck 2 }
5687     lstInstr = lstInstruments->GetNextSubList();
5688     }
5689 schoenebeck 515 __notify_progress(pProgress, 1.0); // notify done
5690 schoenebeck 2 }
5691     }
5692    
5693 persson 1207 /// Updates the 3crc chunk with the checksum of a sample. The
5694     /// update is done directly to disk, as this method is called
5695     /// after File::Save()
5696 persson 1199 void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5697     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5698     if (!_3crc) return;
5699 persson 1207
5700     // get the index of the sample
5701 schoenebeck 2985 int iWaveIndex = GetWaveTableIndexOf(pSample);
5702 persson 1199 if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5703    
5704 persson 1207 // write the CRC-32 checksum to disk
5705 persson 1199 _3crc->SetPos(iWaveIndex * 8);
5706 schoenebeck 2985 uint32_t one = 1;
5707     _3crc->WriteUint32(&one); // always 1
5708 persson 1199 _3crc->WriteUint32(&crc);
5709 schoenebeck 2989 }
5710 schoenebeck 2985
5711 schoenebeck 2989 uint32_t File::GetSampleChecksum(Sample* pSample) {
5712     // get the index of the sample
5713     int iWaveIndex = GetWaveTableIndexOf(pSample);
5714     if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5715    
5716     return GetSampleChecksumByIndex(iWaveIndex);
5717 persson 1199 }
5718    
5719 schoenebeck 2989 uint32_t File::GetSampleChecksumByIndex(int index) {
5720     if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5721    
5722 schoenebeck 2985 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5723     if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5724     uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5725     if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5726    
5727     // read the CRC-32 checksum directly from disk
5728 schoenebeck 2989 size_t pos = index * 8;
5729 schoenebeck 2985 if (pos + 8 > _3crc->GetNewSize())
5730     throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5731    
5732     uint32_t one = load32(&pData[pos]); // always 1
5733     if (one != 1)
5734 schoenebeck 2989 throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5735 schoenebeck 2985
5736     return load32(&pData[pos+4]);
5737     }
5738 schoenebeck 2989
5739 schoenebeck 2985 int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5740     if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5741     File::SampleList::iterator iter = pSamples->begin();
5742     File::SampleList::iterator end = pSamples->end();
5743     for (int index = 0; iter != end; ++iter, ++index)
5744     if (*iter == pSample)
5745     return index;
5746     return -1;
5747     }
5748    
5749     /**
5750     * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5751     * the CRC32 check sums of all samples' raw wave data.
5752     *
5753     * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5754     */
5755     bool File::VerifySampleChecksumTable() {
5756     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5757     if (!_3crc) return false;
5758     if (_3crc->GetNewSize() <= 0) return false;
5759     if (_3crc->GetNewSize() % 8) return false;
5760     if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5761     if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5762    
5763 schoenebeck 3053 const file_offset_t n = _3crc->GetNewSize() / 8;
5764 schoenebeck 2985
5765     uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5766     if (!pData) return false;
5767    
5768 schoenebeck 3053 for (file_offset_t i = 0; i < n; ++i) {
5769 schoenebeck 2985 uint32_t one = pData[i*2];
5770     if (one != 1) return false;
5771     }
5772    
5773     return true;
5774     }
5775    
5776     /**
5777     * Recalculates CRC32 checksums for all samples and rebuilds this gig
5778     * file's checksum table with those new checksums. This might usually
5779     * just be necessary if the checksum table was damaged.
5780     *
5781     * @e IMPORTANT: The current implementation of this method only works
5782     * with files that have not been modified since it was loaded, because
5783     * it expects that no externally caused file structure changes are
5784     * required!
5785     *
5786     * Due to the expectation above, this method is currently protected
5787     * and actually only used by the command line tool "gigdump" yet.
5788     *
5789     * @returns true if Save() is required to be called after this call,
5790     * false if no further action is required
5791     */
5792     bool File::RebuildSampleChecksumTable() {
5793     // make sure sample chunks were scanned
5794     if (!pSamples) GetFirstSample();
5795    
5796     bool bRequiresSave = false;
5797    
5798     // make sure "3CRC" chunk exists with required size
5799     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5800     if (!_3crc) {
5801     _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5802 schoenebeck 2989 // the order of einf and 3crc is not the same in v2 and v3
5803     RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5804     if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5805 schoenebeck 2985 bRequiresSave = true;
5806     } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5807     _3crc->Resize(pSamples->size() * 8);
5808     bRequiresSave = true;
5809     }
5810    
5811     if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5812     uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5813     {
5814     File::SampleList::iterator iter = pSamples->begin();
5815     File::SampleList::iterator end = pSamples->end();
5816     for (; iter != end; ++iter) {
5817     gig::Sample* pSample = (gig::Sample*) *iter;
5818     int index = GetWaveTableIndexOf(pSample);
5819     if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5820     pData[index*2] = 1; // always 1
5821     pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5822     }
5823     }
5824     } else { // no file structure changes necessary, so directly write to disk and we are done ...
5825     // make sure file is in write mode
5826     pRIFF->SetMode(RIFF::stream_mode_read_write);
5827     {
5828     File::SampleList::iterator iter = pSamples->begin();
5829     File::SampleList::iterator end = pSamples->end();
5830     for (; iter != end; ++iter) {
5831     gig::Sample* pSample = (gig::Sample*) *iter;
5832     int index = GetWaveTableIndexOf(pSample);
5833     if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5834 schoenebeck 2989 pSample->crc = pSample->CalculateWaveDataChecksum();
5835     SetSampleChecksum(pSample, pSample->crc);
5836 schoenebeck 2985 }
5837     }
5838     }
5839    
5840     return bRequiresSave;
5841     }
5842    
5843 schoenebeck 929 Group* File::GetFirstGroup() {
5844     if (!pGroups) LoadGroups();
5845 schoenebeck 930 // there must always be at least one group
5846 schoenebeck 929 GroupsIterator = pGroups->begin();
5847 schoenebeck 930 return *GroupsIterator;
5848 schoenebeck 929 }
5849 schoenebeck 2
5850 schoenebeck 929 Group* File::GetNextGroup() {
5851     if (!pGroups) return NULL;
5852     ++GroupsIterator;
5853     return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5854     }
5855 schoenebeck 2
5856 schoenebeck 929 /**
5857     * Returns the group with the given index.
5858     *
5859     * @param index - number of the sought group (0..n)
5860     * @returns sought group or NULL if there's no such group
5861     */
5862     Group* File::GetGroup(uint index) {
5863     if (!pGroups) LoadGroups();
5864     GroupsIterator = pGroups->begin();
5865     for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5866     if (i == index) return *GroupsIterator;
5867     ++GroupsIterator;
5868     }
5869     return NULL;
5870     }
5871    
5872 schoenebeck 2543 /**
5873     * Returns the group with the given group name.
5874     *
5875     * Note: group names don't have to be unique in the gig format! So there
5876     * can be multiple groups with the same name. This method will simply
5877     * return the first group found with the given name.
5878     *
5879     * @param name - name of the sought group
5880     * @returns sought group or NULL if there's no group with that name
5881     */
5882     Group* File::GetGroup(String name) {
5883     if (!pGroups) LoadGroups();
5884     GroupsIterator = pGroups->begin();
5885     for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5886     if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5887     return NULL;
5888     }
5889    
5890 schoenebeck 929 Group* File::AddGroup() {
5891     if (!pGroups) LoadGroups();
5892 schoenebeck 930 // there must always be at least one group
5893 schoenebeck 929 __ensureMandatoryChunksExist();
5894 schoenebeck 930 Group* pGroup = new Group(this, NULL);
5895 schoenebeck 929 pGroups->push_back(pGroup);
5896     return pGroup;
5897     }
5898    
5899 schoenebeck 1081 /** @brief Delete a group and its samples.
5900     *
5901     * This will delete the given Group object and all the samples that
5902     * belong to this group from the gig file. You have to call Save() to
5903     * make this persistent to the file.
5904     *
5905     * @param pGroup - group to delete
5906     * @throws gig::Exception if given group could not be found
5907     */
5908 schoenebeck 929 void File::DeleteGroup(Group* pGroup) {
5909 schoenebeck 930 if (!pGroups) LoadGroups();
5910 schoenebeck 929 std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5911     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5912 schoenebeck 930 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5913 schoenebeck 1081 // delete all members of this group
5914     for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5915     DeleteSample(pSample);
5916     }
5917     // now delete this group object
5918     pGroups->erase(iter);
5919     delete pGroup;
5920     }
5921    
5922     /** @brief Delete a group.
5923     *
5924     * This will delete the given Group object from the gig file. All the
5925     * samples that belong to this group will not be deleted, but instead
5926     * be moved to another group. You have to call Save() to make this
5927     * persistent to the file.
5928     *
5929     * @param pGroup - group to delete
5930     * @throws gig::Exception if given group could not be found
5931     */
5932     void File::DeleteGroupOnly(Group* pGroup) {
5933     if (!pGroups) LoadGroups();
5934     std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5935     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5936     if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5937 schoenebeck 930 // move all members of this group to another group
5938     pGroup->MoveAll();
5939 schoenebeck 929 pGroups->erase(iter);
5940     delete pGroup;
5941     }
5942    
5943     void File::LoadGroups() {
5944     if (!pGroups) pGroups = new std::list<Group*>;
5945 schoenebeck 930 // try to read defined groups from file
5946 schoenebeck 929 RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5947 schoenebeck 930 if (lst3gri) {
5948     RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5949     if (lst3gnl) {
5950     RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5951     while (ck) {
5952     if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5953 persson 1266 if (pVersion && pVersion->major == 3 &&
5954     strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5955    
5956 schoenebeck 930 pGroups->push_back(new Group(this, ck));
5957     }
5958     ck = lst3gnl->GetNextSubChunk();
5959 schoenebeck 929 }
5960     }
5961     }
5962 schoenebeck 930 // if there were no group(s), create at least the mandatory default group
5963     if (!pGroups->size()) {
5964     Group* pGroup = new Group(this, NULL);
5965     pGroup->Name = "Default Group";
5966     pGroups->push_back(pGroup);
5967     }
5968 schoenebeck 929 }
5969    
5970 schoenebeck 2584 /** @brief Get instrument script group (by index).
5971     *
5972     * Returns the real-time instrument script group with the given index.
5973     *
5974     * @param index - number of the sought group (0..n)
5975     * @returns sought script group or NULL if there's no such group
5976     */
5977     ScriptGroup* File::GetScriptGroup(uint index) {
5978     if (!pScriptGroups) LoadScriptGroups();
5979     std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5980     for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5981     if (i == index) return *it;
5982     return NULL;
5983     }
5984    
5985     /** @brief Get instrument script group (by name).
5986     *
5987     * Returns the first real-time instrument script group found with the given
5988     * group name. Note that group names may not necessarily be unique.
5989     *
5990     * @param name - name of the sought script group
5991     * @returns sought script group or NULL if there's no such group
5992     */
5993     ScriptGroup* File::GetScriptGroup(const String& name) {
5994     if (!pScriptGroups) LoadScriptGroups();
5995     std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5996     for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5997     if ((*it)->Name == name) return *it;
5998     return NULL;
5999     }
6000    
6001     /** @brief Add new instrument script group.
6002     *
6003     * Adds a new, empty real-time instrument script group to the file.
6004     *
6005     * You have to call Save() to make this persistent to the file.
6006     *
6007     * @return new empty script group
6008     */
6009     ScriptGroup* File::AddScriptGroup() {
6010     if (!pScriptGroups) LoadScriptGroups();
6011     ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6012     pScriptGroups->push_back(pScriptGroup);
6013     return pScriptGroup;
6014     }
6015    
6016     /** @brief Delete an instrument script group.
6017     *
6018     * This will delete the given real-time instrument script group and all its
6019     * instrument scripts it contains. References inside instruments that are
6020     * using the deleted scripts will be removed from the respective instruments
6021     * accordingly.
6022     *
6023     * You have to call Save() to make this persistent to the file.
6024     *
6025     * @param pScriptGroup - script group to delete
6026     * @throws gig::Exception if given script group could not be found
6027     */
6028     void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6029     if (!pScriptGroups) LoadScriptGroups();
6030     std::list<ScriptGroup*>::iterator iter =
6031     find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6032     if (iter == pScriptGroups->end())
6033     throw gig::Exception("Could not delete script group, could not find given script group");
6034     pScriptGroups->erase(iter);
6035     for (int i = 0; pScriptGroup->GetScript(i); ++i)
6036     pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6037     if (pScriptGroup->pList)
6038     pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6039     delete pScriptGroup;
6040     }
6041    
6042     void File::LoadScriptGroups() {
6043     if (pScriptGroups) return;
6044     pScriptGroups = new std::list<ScriptGroup*>;
6045     RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6046     if (lstLS) {
6047     for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6048     lst = lstLS->GetNextSubList())
6049     {
6050     if (lst->GetListType() == LIST_TYPE_RTIS) {
6051     pScriptGroups->push_back(new ScriptGroup(this, lst));
6052     }
6053     }
6054     }
6055     }
6056    
6057 schoenebeck 1098 /**
6058     * Apply all the gig file's current instruments, samples, groups and settings
6059     * to the respective RIFF chunks. You have to call Save() to make changes
6060     * persistent.
6061     *
6062     * Usually there is absolutely no need to call this method explicitly.
6063     * It will be called automatically when File::Save() was called.
6064     *
6065 schoenebeck 2682 * @param pProgress - callback function for progress notification
6066 schoenebeck 1098 * @throws Exception - on errors
6067     */
6068 schoenebeck 2682 void File::UpdateChunks(progress_t* pProgress) {
6069 persson 1199 bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6070 persson 1192
6071 schoenebeck 2584 // update own gig format extension chunks
6072     // (not part of the GigaStudio 4 format)
6073 schoenebeck 2912 RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6074     if (!lst3LS) {
6075     lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6076     }
6077     // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6078 schoenebeck 2913 // location of <3LS > is irrelevant, however it should be located
6079     // before the actual wave data
6080 schoenebeck 2912 RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6081     pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6082    
6083 schoenebeck 2584 // This must be performed before writing the chunks for instruments,
6084     // because the instruments' script slots will write the file offsets
6085     // of the respective instrument script chunk as reference.
6086     if (pScriptGroups) {
6087 schoenebeck 2912 // Update instrument script (group) chunks.
6088     for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6089     it != pScriptGroups->end(); ++it)
6090     {
6091     (*it)->UpdateChunks(pProgress);
6092 schoenebeck 2584 }
6093     }
6094    
6095 schoenebeck 2913 // in case no libgig custom format data was added, then remove the
6096     // custom "3LS " chunk again
6097     if (!lst3LS->CountSubChunks()) {
6098     pRIFF->DeleteSubChunk(lst3LS);
6099     lst3LS = NULL;
6100     }
6101    
6102 schoenebeck 1098 // first update base class's chunks
6103 schoenebeck 2682 DLS::File::UpdateChunks(pProgress);
6104 schoenebeck 929
6105 persson 1199 if (newFile) {
6106 persson 1192 // INFO was added by Resource::UpdateChunks - make sure it
6107     // is placed first in file
6108 persson 1199 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
6109 persson 1192 RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
6110     if (first != info) {
6111     pRIFF->MoveSubChunk(info, first);
6112     }
6113     }
6114    
6115 schoenebeck 1098 // update group's chunks
6116     if (pGroups) {
6117 schoenebeck 2467 // make sure '3gri' and '3gnl' list chunks exist
6118     // (before updating the Group chunks)
6119     RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6120     if (!_3gri) {
6121     _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6122     pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6123 schoenebeck 1098 }
6124 schoenebeck 2467 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6125     if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6126 persson 1266
6127     // v3: make sure the file has 128 3gnm chunks
6128 schoenebeck 2467 // (before updating the Group chunks)
6129 persson 1266 if (pVersion && pVersion->major == 3) {
6130     RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6131     for (int i = 0 ; i < 128 ; i++) {
6132     if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6133     if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6134     }
6135     }
6136 schoenebeck 2467
6137     std::list<Group*>::iterator iter = pGroups->begin();
6138     std::list<Group*>::iterator end = pGroups->end();
6139     for (; iter != end; ++iter) {
6140 schoenebeck 2682 (*iter)->UpdateChunks(pProgress);
6141 schoenebeck 2467 }
6142 schoenebeck 1098 }
6143 persson 1199
6144     // update einf chunk
6145    
6146     // The einf chunk contains statistics about the gig file, such
6147     // as the number of regions and samples used by each
6148     // instrument. It is divided in equally sized parts, where the
6149     // first part contains information about the whole gig file,
6150     // and the rest of the parts map to each instrument in the
6151     // file.
6152     //
6153     // At the end of each part there is a bit map of each sample
6154     // in the file, where a set bit means that the sample is used
6155     // by the file/instrument.
6156     //
6157     // Note that there are several fields with unknown use. These
6158     // are set to zero.
6159    
6160 schoenebeck 3053 int sublen = int(pSamples->size() / 8 + 49);
6161 persson 1199 int einfSize = (Instruments + 1) * sublen;
6162    
6163     RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6164     if (einf) {
6165     if (einf->GetSize() != einfSize) {
6166     einf->Resize(einfSize);
6167     memset(einf->LoadChunkData(), 0, einfSize);
6168     }
6169     } else if (newFile) {
6170     einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
6171     }
6172     if (einf) {
6173     uint8_t* pData = (uint8_t*) einf->LoadChunkData();
6174    
6175     std::map<gig::Sample*,int> sampleMap;
6176     int sampleIdx = 0;
6177     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
6178     sampleMap[pSample] = sampleIdx++;
6179     }
6180    
6181     int totnbusedsamples = 0;
6182     int totnbusedchannels = 0;
6183     int totnbregions = 0;
6184     int totnbdimregions = 0;
6185 persson 1264 int totnbloops = 0;
6186 persson 1199 int instrumentIdx = 0;
6187    
6188     memset(&pData[48], 0, sublen - 48);
6189    
6190     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
6191     instrument = GetNextInstrument()) {
6192     int nbusedsamples = 0;
6193     int nbusedchannels = 0;
6194     int nbdimregions = 0;
6195 persson 1264 int nbloops = 0;
6196 persson 1199
6197     memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
6198    
6199     for (Region* region = instrument->GetFirstRegion() ; region ;
6200     region = instrument->GetNextRegion()) {
6201     for (int i = 0 ; i < region->DimensionRegions ; i++) {
6202     gig::DimensionRegion *d = region->pDimensionRegions[i];
6203     if (d->pSample) {
6204     int sampleIdx = sampleMap[d->pSample];
6205     int byte = 48 + sampleIdx / 8;
6206     int bit = 1 << (sampleIdx & 7);
6207     if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6208     pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6209     nbusedsamples++;
6210     nbusedchannels += d->pSample->Channels;
6211    
6212     if ((pData[byte] & bit) == 0) {
6213     pData[byte] |= bit;
6214     totnbusedsamples++;
6215     totnbusedchannels += d->pSample->Channels;
6216     }
6217     }
6218     }
6219 persson 1264 if (d->SampleLoops) nbloops++;
6220 persson 1199 }
6221     nbdimregions += region->DimensionRegions;
6222     }
6223     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6224     // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6225     store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6226     store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6227     store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6228     store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6229     store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6230 persson 1264 store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6231     // next 8 bytes unknown
6232 persson 1199 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6233 schoenebeck 3053 store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6234 persson 1199 // next 4 bytes unknown
6235    
6236     totnbregions += instrument->Regions;
6237     totnbdimregions += nbdimregions;
6238 persson 1264 totnbloops += nbloops;
6239 persson 1199 instrumentIdx++;
6240     }
6241     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6242     // store32(&pData[0], sublen);
6243     store32(&pData[4], totnbusedchannels);
6244     store32(&pData[8], totnbusedsamples);
6245     store32(&pData[12], Instruments);
6246     store32(&pData[16], totnbregions);
6247     store32(&pData[20], totnbdimregions);
6248 persson 1264 store32(&pData[24], totnbloops);
6249     // next 8 bytes unknown
6250     // next 4 bytes unknown, not always 0
6251 schoenebeck 3053 store32(&pData[40], (uint32_t) pSamples->size());
6252 persson 1199 // next 4 bytes unknown
6253     }
6254    
6255     // update 3crc chunk
6256    
6257     // The 3crc chunk contains CRC-32 checksums for the
6258 schoenebeck 2989 // samples. When saving a gig file to disk, we first update the 3CRC
6259     // chunk here (in RAM) with the old crc values which we read from the
6260     // 3CRC chunk when we opened the file (available with gig::Sample::crc
6261     // member variable). This step is required, because samples might have
6262     // been deleted by the user since the file was opened, which in turn
6263     // changes the order of the (i.e. old) checksums within the 3crc chunk.
6264     // If a sample was conciously modified by the user (that is if
6265     // Sample::Write() was called later on) then Sample::Write() will just
6266     // update the respective individual checksum(s) directly on disk and
6267     // leaves all other sample checksums untouched.
6268 persson 1199
6269 schoenebeck 2989 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6270 persson 1199 if (_3crc) {
6271     _3crc->Resize(pSamples->size() * 8);
6272 schoenebeck 2989 } else /*if (newFile)*/ {
6273 persson 1199 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6274 persson 1264 // the order of einf and 3crc is not the same in v2 and v3
6275     if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6276 persson 1199 }
6277 schoenebeck 2989 { // must be performed in RAM here ...
6278     uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6279     if (pData) {
6280     File::SampleList::iterator iter = pSamples->begin();
6281     File::SampleList::iterator end = pSamples->end();
6282     for (int index = 0; iter != end; ++iter, ++index) {
6283     gig::Sample* pSample = (gig::Sample*) *iter;
6284     pData[index*2] = 1; // always 1
6285     pData[index*2+1] = pSample->crc;
6286     }
6287     }
6288     }
6289 schoenebeck 1098 }
6290 schoenebeck 2609
6291     void File::UpdateFileOffsets() {
6292     DLS::File::UpdateFileOffsets();
6293 schoenebeck 929
6294 schoenebeck 2609 for (Instrument* instrument = GetFirstInstrument(); instrument;
6295     instrument = GetNextInstrument())
6296     {
6297     instrument->UpdateScriptFileOffsets();
6298     }
6299     }
6300    
6301 schoenebeck 1524 /**
6302     * Enable / disable automatic loading. By default this properyt is
6303     * enabled and all informations are loaded automatically. However
6304     * loading all Regions, DimensionRegions and especially samples might
6305     * take a long time for large .gig files, and sometimes one might only
6306     * be interested in retrieving very superficial informations like the
6307     * amount of instruments and their names. In this case one might disable
6308     * automatic loading to avoid very slow response times.
6309     *
6310     * @e CAUTION: by disabling this property many pointers (i.e. sample
6311     * references) and informations will have invalid or even undefined
6312     * data! This feature is currently only intended for retrieving very
6313     * superficial informations in a very fast way. Don't use it to retrieve
6314     * details like synthesis informations or even to modify .gig files!
6315     */
6316     void File::SetAutoLoad(bool b) {
6317     bAutoLoad = b;
6318     }
6319 schoenebeck 1098
6320 schoenebeck 1524 /**
6321     * Returns whether automatic loading is enabled.
6322     * @see SetAutoLoad()
6323     */
6324     bool File::GetAutoLoad() {
6325     return bAutoLoad;
6326     }
6327 schoenebeck 1098
6328 schoenebeck 1524
6329    
6330 schoenebeck 2 // *************** Exception ***************
6331     // *
6332    
6333     Exception::Exception(String Message) : DLS::Exception(Message) {
6334     }
6335    
6336     void Exception::PrintMessage() {
6337     std::cout << "gig::Exception: " << Message << std::endl;
6338     }
6339    
6340 schoenebeck 518
6341     // *************** functions ***************
6342     // *
6343    
6344     /**
6345     * Returns the name of this C++ library. This is usually "libgig" of
6346     * course. This call is equivalent to RIFF::libraryName() and
6347     * DLS::libraryName().
6348     */
6349     String libraryName() {
6350     return PACKAGE;
6351     }
6352    
6353     /**
6354     * Returns version of this C++ library. This call is equivalent to
6355     * RIFF::libraryVersion() and DLS::libraryVersion().
6356     */
6357     String libraryVersion() {
6358     return VERSION;
6359     }
6360    
6361 schoenebeck 2 } // namespace gig

  ViewVC Help
Powered by ViewVC