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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3323 - (hide annotations) (download)
Thu Jul 20 22:09:54 2017 UTC (6 years, 8 months ago) by schoenebeck
File size: 284084 byte(s)
* gig.h/.cpp: Added new struct "eg_opt_t" and new class member variable
  "DimensionRegion::EGOptions" as an extension to the gig file format,
  which allows to override the default behavior of EGs' state machines.
* DLS.h: Got rid of C-style typedefs.
* src/tools/gigdump.cpp: Print the new EG behavior options.
* Bumped version (4.0.0.svn27).

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

  ViewVC Help
Powered by ViewVC