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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3198 - (hide annotations) (download)
Sun May 21 12:46:05 2017 UTC (6 years, 10 months ago) by schoenebeck
File size: 282020 byte(s)
* RIFF/DLS/gig/Serialization: Exception classes now have a variadic
  constructor which allows to add textual format specifiers like
  with printf().
* gig.cpp: On unknown leverage controller exception: show precise unknown
  leverage controller number found.

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

  ViewVC Help
Powered by ViewVC