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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2702 - (hide annotations) (download)
Tue Jan 13 00:32:30 2015 UTC (9 years, 2 months ago) by schoenebeck
File size: 264840 byte(s)
* Bugfix of previous commit.
* Bumped version (3.3.0.svn27).

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

  ViewVC Help
Powered by ViewVC