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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2602 - (hide annotations) (download)
Sat Jun 7 22:28:04 2014 UTC (9 years, 9 months ago) by schoenebeck
File size: 258583 byte(s)
* gig.cpp: Fixed loading instrument script from file.

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

  ViewVC Help
Powered by ViewVC