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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2484 - (hide annotations) (download)
Tue Dec 31 00:13:20 2013 UTC (10 years, 3 months ago) by schoenebeck
File size: 196006 byte(s)
* Added new command line tool "gig2mono" (and a new man page for it).
* src/gig.cpp: Delete "ewav" chunk of Sample if "Compression" attribute was
  toggled to false.
* Bumped version to 3.3.0.svn7.

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2394 * Copyright (C) 2003-2013 by Christian Schoenebeck *
6 schoenebeck 384 * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8     * This library is free software; you can redistribute it and/or modify *
9     * it under the terms of the GNU General Public License as published by *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This library is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this library; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include "gig.h"
25    
26 schoenebeck 809 #include "helper.h"
27    
28 persson 1713 #include <algorithm>
29 schoenebeck 809 #include <math.h>
30 schoenebeck 384 #include <iostream>
31    
32 schoenebeck 809 /// Initial size of the sample buffer which is used for decompression of
33     /// compressed sample wave streams - this value should always be bigger than
34     /// the biggest sample piece expected to be read by the sampler engine,
35     /// otherwise the buffer size will be raised at runtime and thus the buffer
36     /// reallocated which is time consuming and unefficient.
37     #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
38    
39     /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
40     #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
41     #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
42     #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
43     #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
44     #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
45     #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
46     #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
47     #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
48     #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
49     #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
50     #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
51     #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
52    
53 schoenebeck 515 namespace gig {
54 schoenebeck 2
55 schoenebeck 515 // *************** progress_t ***************
56     // *
57    
58     progress_t::progress_t() {
59     callback = NULL;
60 schoenebeck 516 custom = NULL;
61 schoenebeck 515 __range_min = 0.0f;
62     __range_max = 1.0f;
63     }
64    
65     // private helper function to convert progress of a subprocess into the global progress
66     static void __notify_progress(progress_t* pProgress, float subprogress) {
67     if (pProgress && pProgress->callback) {
68     const float totalrange = pProgress->__range_max - pProgress->__range_min;
69     const float totalprogress = pProgress->__range_min + subprogress * totalrange;
70 schoenebeck 516 pProgress->factor = totalprogress;
71     pProgress->callback(pProgress); // now actually notify about the progress
72 schoenebeck 515 }
73     }
74    
75     // private helper function to divide a progress into subprogresses
76     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
77     if (pParentProgress && pParentProgress->callback) {
78     const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
79     pSubProgress->callback = pParentProgress->callback;
80 schoenebeck 516 pSubProgress->custom = pParentProgress->custom;
81 schoenebeck 515 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
82     pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
83     }
84     }
85    
86    
87 schoenebeck 809 // *************** Internal functions for sample decompression ***************
88 persson 365 // *
89    
90 schoenebeck 515 namespace {
91    
92 persson 365 inline int get12lo(const unsigned char* pSrc)
93     {
94     const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
95     return x & 0x800 ? x - 0x1000 : x;
96     }
97    
98     inline int get12hi(const unsigned char* pSrc)
99     {
100     const int x = pSrc[1] >> 4 | pSrc[2] << 4;
101     return x & 0x800 ? x - 0x1000 : x;
102     }
103    
104     inline int16_t get16(const unsigned char* pSrc)
105     {
106     return int16_t(pSrc[0] | pSrc[1] << 8);
107     }
108    
109     inline int get24(const unsigned char* pSrc)
110     {
111     const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
112     return x & 0x800000 ? x - 0x1000000 : x;
113     }
114    
115 persson 902 inline void store24(unsigned char* pDst, int x)
116     {
117     pDst[0] = x;
118     pDst[1] = x >> 8;
119     pDst[2] = x >> 16;
120     }
121    
122 persson 365 void Decompress16(int compressionmode, const unsigned char* params,
123 persson 372 int srcStep, int dstStep,
124     const unsigned char* pSrc, int16_t* pDst,
125 persson 365 unsigned long currentframeoffset,
126     unsigned long copysamples)
127     {
128     switch (compressionmode) {
129     case 0: // 16 bit uncompressed
130     pSrc += currentframeoffset * srcStep;
131     while (copysamples) {
132     *pDst = get16(pSrc);
133 persson 372 pDst += dstStep;
134 persson 365 pSrc += srcStep;
135     copysamples--;
136     }
137     break;
138    
139     case 1: // 16 bit compressed to 8 bit
140     int y = get16(params);
141     int dy = get16(params + 2);
142     while (currentframeoffset) {
143     dy -= int8_t(*pSrc);
144     y -= dy;
145     pSrc += srcStep;
146     currentframeoffset--;
147     }
148     while (copysamples) {
149     dy -= int8_t(*pSrc);
150     y -= dy;
151     *pDst = y;
152 persson 372 pDst += dstStep;
153 persson 365 pSrc += srcStep;
154     copysamples--;
155     }
156     break;
157     }
158     }
159    
160     void Decompress24(int compressionmode, const unsigned char* params,
161 persson 902 int dstStep, const unsigned char* pSrc, uint8_t* pDst,
162 persson 365 unsigned long currentframeoffset,
163 persson 437 unsigned long copysamples, int truncatedBits)
164 persson 365 {
165 persson 695 int y, dy, ddy, dddy;
166 persson 437
167 persson 695 #define GET_PARAMS(params) \
168     y = get24(params); \
169     dy = y - get24((params) + 3); \
170     ddy = get24((params) + 6); \
171     dddy = get24((params) + 9)
172 persson 365
173     #define SKIP_ONE(x) \
174 persson 695 dddy -= (x); \
175     ddy -= dddy; \
176     dy = -dy - ddy; \
177     y += dy
178 persson 365
179     #define COPY_ONE(x) \
180     SKIP_ONE(x); \
181 persson 902 store24(pDst, y << truncatedBits); \
182 persson 372 pDst += dstStep
183 persson 365
184     switch (compressionmode) {
185     case 2: // 24 bit uncompressed
186     pSrc += currentframeoffset * 3;
187     while (copysamples) {
188 persson 902 store24(pDst, get24(pSrc) << truncatedBits);
189 persson 372 pDst += dstStep;
190 persson 365 pSrc += 3;
191     copysamples--;
192     }
193     break;
194    
195     case 3: // 24 bit compressed to 16 bit
196     GET_PARAMS(params);
197     while (currentframeoffset) {
198     SKIP_ONE(get16(pSrc));
199     pSrc += 2;
200     currentframeoffset--;
201     }
202     while (copysamples) {
203     COPY_ONE(get16(pSrc));
204     pSrc += 2;
205     copysamples--;
206     }
207     break;
208    
209     case 4: // 24 bit compressed to 12 bit
210     GET_PARAMS(params);
211     while (currentframeoffset > 1) {
212     SKIP_ONE(get12lo(pSrc));
213     SKIP_ONE(get12hi(pSrc));
214     pSrc += 3;
215     currentframeoffset -= 2;
216     }
217     if (currentframeoffset) {
218     SKIP_ONE(get12lo(pSrc));
219     currentframeoffset--;
220     if (copysamples) {
221     COPY_ONE(get12hi(pSrc));
222     pSrc += 3;
223     copysamples--;
224     }
225     }
226     while (copysamples > 1) {
227     COPY_ONE(get12lo(pSrc));
228     COPY_ONE(get12hi(pSrc));
229     pSrc += 3;
230     copysamples -= 2;
231     }
232     if (copysamples) {
233     COPY_ONE(get12lo(pSrc));
234     }
235     break;
236    
237     case 5: // 24 bit compressed to 8 bit
238     GET_PARAMS(params);
239     while (currentframeoffset) {
240     SKIP_ONE(int8_t(*pSrc++));
241     currentframeoffset--;
242     }
243     while (copysamples) {
244     COPY_ONE(int8_t(*pSrc++));
245     copysamples--;
246     }
247     break;
248     }
249     }
250    
251     const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
252     const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
253     const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
254     const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
255     }
256    
257    
258 schoenebeck 1113
259 schoenebeck 1381 // *************** Internal CRC-32 (Cyclic Redundancy Check) functions ***************
260     // *
261    
262     static uint32_t* __initCRCTable() {
263     static uint32_t res[256];
264    
265     for (int i = 0 ; i < 256 ; i++) {
266     uint32_t c = i;
267     for (int j = 0 ; j < 8 ; j++) {
268     c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269     }
270     res[i] = c;
271     }
272     return res;
273     }
274    
275     static const uint32_t* __CRCTable = __initCRCTable();
276    
277     /**
278     * Initialize a CRC variable.
279     *
280     * @param crc - variable to be initialized
281     */
282     inline static void __resetCRC(uint32_t& crc) {
283     crc = 0xffffffff;
284     }
285    
286     /**
287     * Used to calculate checksums of the sample data in a gig file. The
288     * checksums are stored in the 3crc chunk of the gig file and
289     * automatically updated when a sample is written with Sample::Write().
290     *
291     * One should call __resetCRC() to initialize the CRC variable to be
292     * used before calling this function the first time.
293     *
294     * After initializing the CRC variable one can call this function
295     * arbitrary times, i.e. to split the overall CRC calculation into
296     * steps.
297     *
298     * Once the whole data was processed by __calculateCRC(), one should
299     * call __encodeCRC() to get the final CRC result.
300     *
301     * @param buf - pointer to data the CRC shall be calculated of
302     * @param bufSize - size of the data to be processed
303     * @param crc - variable the CRC sum shall be stored to
304     */
305     static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306     for (int i = 0 ; i < bufSize ; i++) {
307     crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308     }
309     }
310    
311     /**
312     * Returns the final CRC result.
313     *
314     * @param crc - variable previously passed to __calculateCRC()
315     */
316     inline static uint32_t __encodeCRC(const uint32_t& crc) {
317     return crc ^ 0xffffffff;
318     }
319    
320    
321    
322 schoenebeck 1113 // *************** Other Internal functions ***************
323     // *
324    
325     static split_type_t __resolveSplitType(dimension_t dimension) {
326     return (
327     dimension == dimension_layer ||
328     dimension == dimension_samplechannel ||
329     dimension == dimension_releasetrigger ||
330     dimension == dimension_keyboard ||
331     dimension == dimension_roundrobin ||
332     dimension == dimension_random ||
333     dimension == dimension_smartmidi ||
334     dimension == dimension_roundrobinkeyboard
335     ) ? split_type_bit : split_type_normal;
336     }
337    
338     static int __resolveZoneSize(dimension_def_t& dimension_definition) {
339     return (dimension_definition.split_type == split_type_normal)
340     ? int(128.0 / dimension_definition.zones) : 0;
341     }
342    
343    
344    
345 schoenebeck 2 // *************** Sample ***************
346     // *
347    
348 schoenebeck 384 unsigned int Sample::Instances = 0;
349     buffer_t Sample::InternalDecompressionBuffer;
350 schoenebeck 2
351 schoenebeck 809 /** @brief Constructor.
352     *
353     * Load an existing sample or create a new one. A 'wave' list chunk must
354     * be given to this constructor. In case the given 'wave' list chunk
355     * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
356     * format and sample data will be loaded from there, otherwise default
357     * values will be used and those chunks will be created when
358     * File::Save() will be called later on.
359     *
360     * @param pFile - pointer to gig::File where this sample is
361     * located (or will be located)
362     * @param waveList - pointer to 'wave' list chunk which is (or
363     * will be) associated with this sample
364     * @param WavePoolOffset - offset of this sample data from wave pool
365     * ('wvpl') list chunk
366     * @param fileNo - number of an extension file where this sample
367     * is located, 0 otherwise
368     */
369 persson 666 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
370 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
371 persson 1180 { CHUNK_ID_INAM, 64 },
372     { 0, 0 }
373     };
374 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
375 schoenebeck 2 Instances++;
376 persson 666 FileNo = fileNo;
377 schoenebeck 2
378 schoenebeck 1381 __resetCRC(crc);
379    
380 schoenebeck 809 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381     if (pCk3gix) {
382 schoenebeck 929 uint16_t iSampleGroup = pCk3gix->ReadInt16();
383 schoenebeck 930 pGroup = pFile->GetGroup(iSampleGroup);
384 schoenebeck 809 } else { // '3gix' chunk missing
385 schoenebeck 930 // by default assigned to that mandatory "Default Group"
386     pGroup = pFile->GetGroup(0);
387 schoenebeck 809 }
388 schoenebeck 2
389 schoenebeck 809 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
390     if (pCkSmpl) {
391     Manufacturer = pCkSmpl->ReadInt32();
392     Product = pCkSmpl->ReadInt32();
393     SamplePeriod = pCkSmpl->ReadInt32();
394     MIDIUnityNote = pCkSmpl->ReadInt32();
395     FineTune = pCkSmpl->ReadInt32();
396     pCkSmpl->Read(&SMPTEFormat, 1, 4);
397     SMPTEOffset = pCkSmpl->ReadInt32();
398     Loops = pCkSmpl->ReadInt32();
399     pCkSmpl->ReadInt32(); // manufByt
400     LoopID = pCkSmpl->ReadInt32();
401     pCkSmpl->Read(&LoopType, 1, 4);
402     LoopStart = pCkSmpl->ReadInt32();
403     LoopEnd = pCkSmpl->ReadInt32();
404     LoopFraction = pCkSmpl->ReadInt32();
405     LoopPlayCount = pCkSmpl->ReadInt32();
406     } else { // 'smpl' chunk missing
407     // use default values
408     Manufacturer = 0;
409     Product = 0;
410 persson 928 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
411 persson 1218 MIDIUnityNote = 60;
412 schoenebeck 809 FineTune = 0;
413 persson 1182 SMPTEFormat = smpte_format_no_offset;
414 schoenebeck 809 SMPTEOffset = 0;
415     Loops = 0;
416     LoopID = 0;
417 persson 1182 LoopType = loop_type_normal;
418 schoenebeck 809 LoopStart = 0;
419     LoopEnd = 0;
420     LoopFraction = 0;
421     LoopPlayCount = 0;
422     }
423 schoenebeck 2
424     FrameTable = NULL;
425     SamplePos = 0;
426     RAMCache.Size = 0;
427     RAMCache.pStart = NULL;
428     RAMCache.NullExtensionSize = 0;
429    
430 persson 365 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
431    
432 persson 437 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
433     Compressed = ewav;
434     Dithered = false;
435     TruncatedBits = 0;
436 schoenebeck 2 if (Compressed) {
437 persson 437 uint32_t version = ewav->ReadInt32();
438     if (version == 3 && BitDepth == 24) {
439     Dithered = ewav->ReadInt32();
440     ewav->SetPos(Channels == 2 ? 84 : 64);
441     TruncatedBits = ewav->ReadInt32();
442     }
443 schoenebeck 2 ScanCompressedSample();
444     }
445 schoenebeck 317
446     // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
447 schoenebeck 384 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
448     InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
449     InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
450 schoenebeck 317 }
451 persson 437 FrameOffset = 0; // just for streaming compressed samples
452 schoenebeck 21
453 persson 864 LoopSize = LoopEnd - LoopStart + 1;
454 schoenebeck 2 }
455    
456 schoenebeck 809 /**
457 schoenebeck 2482 * Make a (semi) deep copy of the Sample object given by @a orig (without
458     * the actual waveform data) and assign it to this object.
459     *
460     * Discussion: copying .gig samples is a bit tricky. It requires three
461     * steps:
462     * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463     * its new sample waveform data size.
464     * 2. Saving the file (done by File::Save()) so that it gains correct size
465     * and layout for writing the actual wave form data directly to disc
466     * in next step.
467     * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468     *
469     * @param orig - original Sample object to be copied from
470     */
471     void Sample::CopyAssignMeta(const Sample* orig) {
472     // handle base classes
473     DLS::Sample::CopyAssignCore(orig);
474    
475     // handle actual own attributes of this class
476     Manufacturer = orig->Manufacturer;
477     Product = orig->Product;
478     SamplePeriod = orig->SamplePeriod;
479     MIDIUnityNote = orig->MIDIUnityNote;
480     FineTune = orig->FineTune;
481     SMPTEFormat = orig->SMPTEFormat;
482     SMPTEOffset = orig->SMPTEOffset;
483     Loops = orig->Loops;
484     LoopID = orig->LoopID;
485     LoopType = orig->LoopType;
486     LoopStart = orig->LoopStart;
487     LoopEnd = orig->LoopEnd;
488     LoopSize = orig->LoopSize;
489     LoopFraction = orig->LoopFraction;
490     LoopPlayCount = orig->LoopPlayCount;
491    
492     // schedule resizing this sample to the given sample's size
493     Resize(orig->GetSize());
494     }
495    
496     /**
497     * Should be called after CopyAssignMeta() and File::Save() sequence.
498     * Read more about it in the discussion of CopyAssignMeta(). This method
499     * copies the actual waveform data by disk streaming.
500     *
501     * @e CAUTION: this method is currently not thread safe! During this
502     * operation the sample must not be used for other purposes by other
503     * threads!
504     *
505     * @param orig - original Sample object to be copied from
506     */
507     void Sample::CopyAssignWave(const Sample* orig) {
508     const int iReadAtOnce = 32*1024;
509     char* buf = new char[iReadAtOnce * orig->FrameSize];
510     Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511     unsigned long restorePos = pOrig->GetPos();
512     pOrig->SetPos(0);
513     SetPos(0);
514     for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515     n = pOrig->Read(buf, iReadAtOnce))
516     {
517     Write(buf, n);
518     }
519     pOrig->SetPos(restorePos);
520     delete [] buf;
521     }
522    
523     /**
524 schoenebeck 809 * Apply sample and its settings to the respective RIFF chunks. You have
525     * to call File::Save() to make changes persistent.
526     *
527     * Usually there is absolutely no need to call this method explicitly.
528     * It will be called automatically when File::Save() was called.
529     *
530 schoenebeck 1050 * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
531 schoenebeck 809 * was provided yet
532     * @throws gig::Exception if there is any invalid sample setting
533     */
534     void Sample::UpdateChunks() {
535     // first update base class's chunks
536     DLS::Sample::UpdateChunks();
537    
538     // make sure 'smpl' chunk exists
539     pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
540 persson 1182 if (!pCkSmpl) {
541     pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
542     memset(pCkSmpl->LoadChunkData(), 0, 60);
543     }
544 schoenebeck 809 // update 'smpl' chunk
545     uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
546 persson 918 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
547 persson 1179 store32(&pData[0], Manufacturer);
548     store32(&pData[4], Product);
549     store32(&pData[8], SamplePeriod);
550     store32(&pData[12], MIDIUnityNote);
551     store32(&pData[16], FineTune);
552     store32(&pData[20], SMPTEFormat);
553     store32(&pData[24], SMPTEOffset);
554     store32(&pData[28], Loops);
555 schoenebeck 809
556     // we skip 'manufByt' for now (4 bytes)
557    
558 persson 1179 store32(&pData[36], LoopID);
559     store32(&pData[40], LoopType);
560     store32(&pData[44], LoopStart);
561     store32(&pData[48], LoopEnd);
562     store32(&pData[52], LoopFraction);
563     store32(&pData[56], LoopPlayCount);
564 schoenebeck 809
565     // make sure '3gix' chunk exists
566     pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
567     if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
568 schoenebeck 929 // determine appropriate sample group index (to be stored in chunk)
569 schoenebeck 930 uint16_t iSampleGroup = 0; // 0 refers to default sample group
570 schoenebeck 929 File* pFile = static_cast<File*>(pParent);
571     if (pFile->pGroups) {
572     std::list<Group*>::iterator iter = pFile->pGroups->begin();
573     std::list<Group*>::iterator end = pFile->pGroups->end();
574 schoenebeck 930 for (int i = 0; iter != end; i++, iter++) {
575 schoenebeck 929 if (*iter == pGroup) {
576     iSampleGroup = i;
577     break; // found
578     }
579     }
580     }
581 schoenebeck 809 // update '3gix' chunk
582     pData = (uint8_t*) pCk3gix->LoadChunkData();
583 persson 1179 store16(&pData[0], iSampleGroup);
584 schoenebeck 2484
585     // if the library user toggled the "Compressed" attribute from true to
586     // false, then the EWAV chunk associated with compressed samples needs
587     // to be deleted
588     RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
589     if (ewav && !Compressed) {
590     pWaveList->DeleteSubChunk(ewav);
591     }
592 schoenebeck 809 }
593    
594 schoenebeck 2 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
595     void Sample::ScanCompressedSample() {
596     //TODO: we have to add some more scans here (e.g. determine compression rate)
597     this->SamplesTotal = 0;
598     std::list<unsigned long> frameOffsets;
599    
600 persson 365 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
601 schoenebeck 384 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
602 persson 365
603 schoenebeck 2 // Scanning
604     pCkData->SetPos(0);
605 persson 365 if (Channels == 2) { // Stereo
606     for (int i = 0 ; ; i++) {
607     // for 24 bit samples every 8:th frame offset is
608     // stored, to save some memory
609     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
610    
611     const int mode_l = pCkData->ReadUint8();
612     const int mode_r = pCkData->ReadUint8();
613     if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
614     const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
615    
616     if (pCkData->RemainingBytes() <= frameSize) {
617     SamplesInLastFrame =
618     ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
619     (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
620     SamplesTotal += SamplesInLastFrame;
621 schoenebeck 2 break;
622 persson 365 }
623     SamplesTotal += SamplesPerFrame;
624     pCkData->SetPos(frameSize, RIFF::stream_curpos);
625     }
626     }
627     else { // Mono
628     for (int i = 0 ; ; i++) {
629     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
630    
631     const int mode = pCkData->ReadUint8();
632     if (mode > 5) throw gig::Exception("Unknown compression mode");
633     const unsigned long frameSize = bytesPerFrame[mode];
634    
635     if (pCkData->RemainingBytes() <= frameSize) {
636     SamplesInLastFrame =
637     ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
638     SamplesTotal += SamplesInLastFrame;
639 schoenebeck 2 break;
640 persson 365 }
641     SamplesTotal += SamplesPerFrame;
642     pCkData->SetPos(frameSize, RIFF::stream_curpos);
643 schoenebeck 2 }
644     }
645     pCkData->SetPos(0);
646    
647     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
648     if (FrameTable) delete[] FrameTable;
649     FrameTable = new unsigned long[frameOffsets.size()];
650     std::list<unsigned long>::iterator end = frameOffsets.end();
651     std::list<unsigned long>::iterator iter = frameOffsets.begin();
652     for (int i = 0; iter != end; i++, iter++) {
653     FrameTable[i] = *iter;
654     }
655     }
656    
657     /**
658     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
659     * ReleaseSampleData() to free the memory if you don't need the cached
660     * sample data anymore.
661     *
662     * @returns buffer_t structure with start address and size of the buffer
663     * in bytes
664     * @see ReleaseSampleData(), Read(), SetPos()
665     */
666     buffer_t Sample::LoadSampleData() {
667     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
668     }
669    
670     /**
671     * Reads (uncompresses if needed) and caches the first \a SampleCount
672     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
673     * memory space if you don't need the cached samples anymore. There is no
674     * guarantee that exactly \a SampleCount samples will be cached; this is
675     * not an error. The size will be eventually truncated e.g. to the
676     * beginning of a frame of a compressed sample. This is done for
677     * efficiency reasons while streaming the wave by your sampler engine
678     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
679     * that will be returned to determine the actual cached samples, but note
680     * that the size is given in bytes! You get the number of actually cached
681     * samples by dividing it by the frame size of the sample:
682 schoenebeck 384 * @code
683 schoenebeck 2 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
684     * long cachedsamples = buf.Size / pSample->FrameSize;
685 schoenebeck 384 * @endcode
686 schoenebeck 2 *
687     * @param SampleCount - number of sample points to load into RAM
688     * @returns buffer_t structure with start address and size of
689     * the cached sample data in bytes
690     * @see ReleaseSampleData(), Read(), SetPos()
691     */
692     buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
693     return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
694     }
695    
696     /**
697     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
698     * ReleaseSampleData() to free the memory if you don't need the cached
699     * sample data anymore.
700     * The method will add \a NullSamplesCount silence samples past the
701     * official buffer end (this won't affect the 'Size' member of the
702     * buffer_t structure, that means 'Size' always reflects the size of the
703     * actual sample data, the buffer might be bigger though). Silence
704     * samples past the official buffer are needed for differential
705     * algorithms that always have to take subsequent samples into account
706     * (resampling/interpolation would be an important example) and avoids
707     * memory access faults in such cases.
708     *
709     * @param NullSamplesCount - number of silence samples the buffer should
710     * be extended past it's data end
711     * @returns buffer_t structure with start address and
712     * size of the buffer in bytes
713     * @see ReleaseSampleData(), Read(), SetPos()
714     */
715     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
716     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
717     }
718    
719     /**
720     * Reads (uncompresses if needed) and caches the first \a SampleCount
721     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
722     * memory space if you don't need the cached samples anymore. There is no
723     * guarantee that exactly \a SampleCount samples will be cached; this is
724     * not an error. The size will be eventually truncated e.g. to the
725     * beginning of a frame of a compressed sample. This is done for
726     * efficiency reasons while streaming the wave by your sampler engine
727     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
728     * that will be returned to determine the actual cached samples, but note
729     * that the size is given in bytes! You get the number of actually cached
730     * samples by dividing it by the frame size of the sample:
731 schoenebeck 384 * @code
732 schoenebeck 2 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
733     * long cachedsamples = buf.Size / pSample->FrameSize;
734 schoenebeck 384 * @endcode
735 schoenebeck 2 * The method will add \a NullSamplesCount silence samples past the
736     * official buffer end (this won't affect the 'Size' member of the
737     * buffer_t structure, that means 'Size' always reflects the size of the
738     * actual sample data, the buffer might be bigger though). Silence
739     * samples past the official buffer are needed for differential
740     * algorithms that always have to take subsequent samples into account
741     * (resampling/interpolation would be an important example) and avoids
742     * memory access faults in such cases.
743     *
744     * @param SampleCount - number of sample points to load into RAM
745     * @param NullSamplesCount - number of silence samples the buffer should
746     * be extended past it's data end
747     * @returns buffer_t structure with start address and
748     * size of the cached sample data in bytes
749     * @see ReleaseSampleData(), Read(), SetPos()
750     */
751     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
752     if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
753     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
754     unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
755 schoenebeck 1851 SetPos(0); // reset read position to begin of sample
756 schoenebeck 2 RAMCache.pStart = new int8_t[allocationsize];
757     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
758     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
759     // fill the remaining buffer space with silence samples
760     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
761     return GetCache();
762     }
763    
764     /**
765     * Returns current cached sample points. A buffer_t structure will be
766     * returned which contains address pointer to the begin of the cache and
767     * the size of the cached sample data in bytes. Use
768     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
769     * RAM.
770     *
771     * @returns buffer_t structure with current cached sample points
772     * @see LoadSampleData();
773     */
774     buffer_t Sample::GetCache() {
775     // return a copy of the buffer_t structure
776     buffer_t result;
777     result.Size = this->RAMCache.Size;
778     result.pStart = this->RAMCache.pStart;
779     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
780     return result;
781     }
782    
783     /**
784     * Frees the cached sample from RAM if loaded with
785     * <i>LoadSampleData()</i> previously.
786     *
787     * @see LoadSampleData();
788     */
789     void Sample::ReleaseSampleData() {
790     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
791     RAMCache.pStart = NULL;
792     RAMCache.Size = 0;
793 schoenebeck 1851 RAMCache.NullExtensionSize = 0;
794 schoenebeck 2 }
795    
796 schoenebeck 809 /** @brief Resize sample.
797     *
798     * Resizes the sample's wave form data, that is the actual size of
799     * sample wave data possible to be written for this sample. This call
800     * will return immediately and just schedule the resize operation. You
801     * should call File::Save() to actually perform the resize operation(s)
802     * "physically" to the file. As this can take a while on large files, it
803     * is recommended to call Resize() first on all samples which have to be
804     * resized and finally to call File::Save() to perform all those resize
805     * operations in one rush.
806     *
807     * The actual size (in bytes) is dependant to the current FrameSize
808     * value. You may want to set FrameSize before calling Resize().
809     *
810     * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
811     * enlarged samples before calling File::Save() as this might exceed the
812     * current sample's boundary!
813     *
814 schoenebeck 1050 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
815     * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
816 schoenebeck 809 * other formats will fail!
817     *
818     * @param iNewSize - new sample wave data size in sample points (must be
819     * greater than zero)
820 schoenebeck 1050 * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
821 schoenebeck 809 * or if \a iNewSize is less than 1
822     * @throws gig::Exception if existing sample is compressed
823     * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
824     * DLS::Sample::FormatTag, File::Save()
825     */
826     void Sample::Resize(int iNewSize) {
827     if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
828     DLS::Sample::Resize(iNewSize);
829     }
830    
831 schoenebeck 2 /**
832     * Sets the position within the sample (in sample points, not in
833     * bytes). Use this method and <i>Read()</i> if you don't want to load
834     * the sample into RAM, thus for disk streaming.
835     *
836     * Although the original Gigasampler engine doesn't allow positioning
837     * within compressed samples, I decided to implement it. Even though
838     * the Gigasampler format doesn't allow to define loops for compressed
839     * samples at the moment, positioning within compressed samples might be
840     * interesting for some sampler engines though. The only drawback about
841     * my decision is that it takes longer to load compressed gig Files on
842     * startup, because it's neccessary to scan the samples for some
843     * mandatory informations. But I think as it doesn't affect the runtime
844     * efficiency, nobody will have a problem with that.
845     *
846     * @param SampleCount number of sample points to jump
847     * @param Whence optional: to which relation \a SampleCount refers
848     * to, if omited <i>RIFF::stream_start</i> is assumed
849     * @returns the new sample position
850     * @see Read()
851     */
852     unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
853     if (Compressed) {
854     switch (Whence) {
855     case RIFF::stream_curpos:
856     this->SamplePos += SampleCount;
857     break;
858     case RIFF::stream_end:
859     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
860     break;
861     case RIFF::stream_backward:
862     this->SamplePos -= SampleCount;
863     break;
864     case RIFF::stream_start: default:
865     this->SamplePos = SampleCount;
866     break;
867     }
868     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
869    
870     unsigned long frame = this->SamplePos / 2048; // to which frame to jump
871     this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
872     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
873     return this->SamplePos;
874     }
875     else { // not compressed
876     unsigned long orderedBytes = SampleCount * this->FrameSize;
877     unsigned long result = pCkData->SetPos(orderedBytes, Whence);
878     return (result == orderedBytes) ? SampleCount
879     : result / this->FrameSize;
880     }
881     }
882    
883     /**
884     * Returns the current position in the sample (in sample points).
885     */
886 schoenebeck 2482 unsigned long Sample::GetPos() const {
887 schoenebeck 2 if (Compressed) return SamplePos;
888     else return pCkData->GetPos() / FrameSize;
889     }
890    
891     /**
892 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
893     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
894     * the position within the sample respectively, this method honors the
895     * looping informations of the sample (if any). The sample wave stream
896     * will be decompressed on the fly if using a compressed sample. Use this
897     * method if you don't want to load the sample into RAM, thus for disk
898     * streaming. All this methods needs to know to proceed with streaming
899     * for the next time you call this method is stored in \a pPlaybackState.
900     * You have to allocate and initialize the playback_state_t structure by
901     * yourself before you use it to stream a sample:
902 schoenebeck 384 * @code
903     * gig::playback_state_t playbackstate;
904     * playbackstate.position = 0;
905     * playbackstate.reverse = false;
906     * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
907     * @endcode
908 schoenebeck 24 * You don't have to take care of things like if there is actually a loop
909     * defined or if the current read position is located within a loop area.
910     * The method already handles such cases by itself.
911     *
912 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
913     * have to use an external decompression buffer for <b>EACH</b>
914     * streaming thread to avoid race conditions and crashes!
915     *
916 schoenebeck 24 * @param pBuffer destination buffer
917     * @param SampleCount number of sample points to read
918     * @param pPlaybackState will be used to store and reload the playback
919     * state for the next ReadAndLoop() call
920 persson 864 * @param pDimRgn dimension region with looping information
921 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
922 schoenebeck 24 * @returns number of successfully read sample points
923 schoenebeck 384 * @see CreateDecompressionBuffer()
924 schoenebeck 24 */
925 persson 864 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
926     DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
927 schoenebeck 24 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
928     uint8_t* pDst = (uint8_t*) pBuffer;
929    
930     SetPos(pPlaybackState->position); // recover position from the last time
931    
932 persson 864 if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
933 schoenebeck 24
934 persson 864 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
935     const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
936 schoenebeck 24
937 persson 864 if (GetPos() <= loopEnd) {
938     switch (loop.LoopType) {
939 schoenebeck 24
940 persson 864 case loop_type_bidirectional: { //TODO: not tested yet!
941     do {
942     // if not endless loop check if max. number of loop cycles have been passed
943     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
944 schoenebeck 24
945 persson 864 if (!pPlaybackState->reverse) { // forward playback
946     do {
947     samplestoloopend = loopEnd - GetPos();
948     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
949     samplestoread -= readsamples;
950     totalreadsamples += readsamples;
951     if (readsamples == samplestoloopend) {
952     pPlaybackState->reverse = true;
953     break;
954     }
955     } while (samplestoread && readsamples);
956     }
957     else { // backward playback
958 schoenebeck 24
959 persson 864 // as we can only read forward from disk, we have to
960     // determine the end position within the loop first,
961     // read forward from that 'end' and finally after
962     // reading, swap all sample frames so it reflects
963     // backward playback
964 schoenebeck 24
965 persson 864 unsigned long swapareastart = totalreadsamples;
966     unsigned long loopoffset = GetPos() - loop.LoopStart;
967     unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
968     unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
969 schoenebeck 24
970 persson 864 SetPos(reverseplaybackend);
971 schoenebeck 24
972 persson 864 // read samples for backward playback
973     do {
974     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
975     samplestoreadinloop -= readsamples;
976     samplestoread -= readsamples;
977     totalreadsamples += readsamples;
978     } while (samplestoreadinloop && readsamples);
979 schoenebeck 24
980 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
981    
982     if (reverseplaybackend == loop.LoopStart) {
983     pPlaybackState->loop_cycles_left--;
984     pPlaybackState->reverse = false;
985     }
986    
987     // reverse the sample frames for backward playback
988 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!
989     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
990 schoenebeck 24 }
991 persson 864 } while (samplestoread && readsamples);
992     break;
993     }
994 schoenebeck 24
995 persson 864 case loop_type_backward: { // TODO: not tested yet!
996     // forward playback (not entered the loop yet)
997     if (!pPlaybackState->reverse) do {
998     samplestoloopend = loopEnd - GetPos();
999     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1000     samplestoread -= readsamples;
1001     totalreadsamples += readsamples;
1002     if (readsamples == samplestoloopend) {
1003     pPlaybackState->reverse = true;
1004     break;
1005     }
1006     } while (samplestoread && readsamples);
1007 schoenebeck 24
1008 persson 864 if (!samplestoread) break;
1009 schoenebeck 24
1010 persson 864 // as we can only read forward from disk, we have to
1011     // determine the end position within the loop first,
1012     // read forward from that 'end' and finally after
1013     // reading, swap all sample frames so it reflects
1014     // backward playback
1015 schoenebeck 24
1016 persson 864 unsigned long swapareastart = totalreadsamples;
1017     unsigned long loopoffset = GetPos() - loop.LoopStart;
1018     unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1019     : samplestoread;
1020     unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1021 schoenebeck 24
1022 persson 864 SetPos(reverseplaybackend);
1023 schoenebeck 24
1024 persson 864 // read samples for backward playback
1025     do {
1026     // if not endless loop check if max. number of loop cycles have been passed
1027     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1028     samplestoloopend = loopEnd - GetPos();
1029     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1030     samplestoreadinloop -= readsamples;
1031     samplestoread -= readsamples;
1032     totalreadsamples += readsamples;
1033     if (readsamples == samplestoloopend) {
1034     pPlaybackState->loop_cycles_left--;
1035     SetPos(loop.LoopStart);
1036     }
1037     } while (samplestoreadinloop && readsamples);
1038 schoenebeck 24
1039 persson 864 SetPos(reverseplaybackend); // pretend we really read backwards
1040 schoenebeck 24
1041 persson 864 // reverse the sample frames for backward playback
1042     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1043     break;
1044     }
1045 schoenebeck 24
1046 persson 864 default: case loop_type_normal: {
1047     do {
1048     // if not endless loop check if max. number of loop cycles have been passed
1049     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1050     samplestoloopend = loopEnd - GetPos();
1051     readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1052     samplestoread -= readsamples;
1053     totalreadsamples += readsamples;
1054     if (readsamples == samplestoloopend) {
1055     pPlaybackState->loop_cycles_left--;
1056     SetPos(loop.LoopStart);
1057     }
1058     } while (samplestoread && readsamples);
1059     break;
1060     }
1061 schoenebeck 24 }
1062     }
1063     }
1064    
1065     // read on without looping
1066     if (samplestoread) do {
1067 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1068 schoenebeck 24 samplestoread -= readsamples;
1069     totalreadsamples += readsamples;
1070     } while (readsamples && samplestoread);
1071    
1072     // store current position
1073     pPlaybackState->position = GetPos();
1074    
1075     return totalreadsamples;
1076     }
1077    
1078     /**
1079 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
1080     * position into the buffer pointed by \a pBuffer and increments the
1081     * position within the sample. The sample wave stream will be
1082     * decompressed on the fly if using a compressed sample. Use this method
1083     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
1084     * thus for disk streaming.
1085     *
1086 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
1087     * have to use an external decompression buffer for <b>EACH</b>
1088     * streaming thread to avoid race conditions and crashes!
1089     *
1090 persson 902 * For 16 bit samples, the data in the buffer will be int16_t
1091     * (using native endianness). For 24 bit, the buffer will
1092     * contain three bytes per sample, little-endian.
1093     *
1094 schoenebeck 2 * @param pBuffer destination buffer
1095     * @param SampleCount number of sample points to read
1096 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
1097 schoenebeck 2 * @returns number of successfully read sample points
1098 schoenebeck 384 * @see SetPos(), CreateDecompressionBuffer()
1099 schoenebeck 2 */
1100 schoenebeck 384 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1101 schoenebeck 21 if (SampleCount == 0) return 0;
1102 schoenebeck 317 if (!Compressed) {
1103     if (BitDepth == 24) {
1104 persson 902 return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1105 schoenebeck 317 }
1106 persson 365 else { // 16 bit
1107     // (pCkData->Read does endian correction)
1108     return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1109     : pCkData->Read(pBuffer, SampleCount, 2);
1110     }
1111 schoenebeck 317 }
1112 persson 365 else {
1113 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
1114 persson 365 //TODO: efficiency: maybe we should test for an average compression rate
1115     unsigned long assumedsize = GuessSize(SampleCount),
1116 schoenebeck 2 remainingbytes = 0, // remaining bytes in the local buffer
1117     remainingsamples = SampleCount,
1118 persson 365 copysamples, skipsamples,
1119     currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1120 schoenebeck 2 this->FrameOffset = 0;
1121    
1122 schoenebeck 384 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1123    
1124     // if decompression buffer too small, then reduce amount of samples to read
1125     if (pDecompressionBuffer->Size < assumedsize) {
1126     std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1127     SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1128     remainingsamples = SampleCount;
1129     assumedsize = GuessSize(SampleCount);
1130 schoenebeck 2 }
1131    
1132 schoenebeck 384 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1133 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
1134 persson 902 uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1135 schoenebeck 2 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1136    
1137 persson 365 while (remainingsamples && remainingbytes) {
1138     unsigned long framesamples = SamplesPerFrame;
1139     unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1140 schoenebeck 2
1141 persson 365 int mode_l = *pSrc++, mode_r = 0;
1142    
1143     if (Channels == 2) {
1144     mode_r = *pSrc++;
1145     framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1146     rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1147     nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1148     if (remainingbytes < framebytes) { // last frame in sample
1149     framesamples = SamplesInLastFrame;
1150     if (mode_l == 4 && (framesamples & 1)) {
1151     rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1152     }
1153     else {
1154     rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1155     }
1156 schoenebeck 2 }
1157     }
1158 persson 365 else {
1159     framebytes = bytesPerFrame[mode_l] + 1;
1160     nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1161     if (remainingbytes < framebytes) {
1162     framesamples = SamplesInLastFrame;
1163     }
1164     }
1165 schoenebeck 2
1166     // determine how many samples in this frame to skip and read
1167 persson 365 if (currentframeoffset + remainingsamples >= framesamples) {
1168     if (currentframeoffset <= framesamples) {
1169     copysamples = framesamples - currentframeoffset;
1170     skipsamples = currentframeoffset;
1171     }
1172     else {
1173     copysamples = 0;
1174     skipsamples = framesamples;
1175     }
1176 schoenebeck 2 }
1177     else {
1178 persson 365 // This frame has enough data for pBuffer, but not
1179     // all of the frame is needed. Set file position
1180     // to start of this frame for next call to Read.
1181 schoenebeck 2 copysamples = remainingsamples;
1182 persson 365 skipsamples = currentframeoffset;
1183     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1184     this->FrameOffset = currentframeoffset + copysamples;
1185     }
1186     remainingsamples -= copysamples;
1187    
1188     if (remainingbytes > framebytes) {
1189     remainingbytes -= framebytes;
1190     if (remainingsamples == 0 &&
1191     currentframeoffset + copysamples == framesamples) {
1192     // This frame has enough data for pBuffer, and
1193     // all of the frame is needed. Set file
1194     // position to start of next frame for next
1195     // call to Read. FrameOffset is 0.
1196 schoenebeck 2 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1197     }
1198     }
1199 persson 365 else remainingbytes = 0;
1200 schoenebeck 2
1201 persson 365 currentframeoffset -= skipsamples;
1202 schoenebeck 2
1203 persson 365 if (copysamples == 0) {
1204     // skip this frame
1205     pSrc += framebytes - Channels;
1206     }
1207     else {
1208     const unsigned char* const param_l = pSrc;
1209     if (BitDepth == 24) {
1210     if (mode_l != 2) pSrc += 12;
1211 schoenebeck 2
1212 persson 365 if (Channels == 2) { // Stereo
1213     const unsigned char* const param_r = pSrc;
1214     if (mode_r != 2) pSrc += 12;
1215    
1216 persson 902 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1217 persson 437 skipsamples, copysamples, TruncatedBits);
1218 persson 902 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1219 persson 437 skipsamples, copysamples, TruncatedBits);
1220 persson 902 pDst24 += copysamples * 6;
1221 schoenebeck 2 }
1222 persson 365 else { // Mono
1223 persson 902 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1224 persson 437 skipsamples, copysamples, TruncatedBits);
1225 persson 902 pDst24 += copysamples * 3;
1226 schoenebeck 2 }
1227 persson 365 }
1228     else { // 16 bit
1229     if (mode_l) pSrc += 4;
1230 schoenebeck 2
1231 persson 365 int step;
1232     if (Channels == 2) { // Stereo
1233     const unsigned char* const param_r = pSrc;
1234     if (mode_r) pSrc += 4;
1235    
1236     step = (2 - mode_l) + (2 - mode_r);
1237 persson 372 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1238     Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1239 persson 365 skipsamples, copysamples);
1240     pDst += copysamples << 1;
1241 schoenebeck 2 }
1242 persson 365 else { // Mono
1243     step = 2 - mode_l;
1244 persson 372 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1245 persson 365 pDst += copysamples;
1246 schoenebeck 2 }
1247 persson 365 }
1248     pSrc += nextFrameOffset;
1249     }
1250 schoenebeck 2
1251 persson 365 // reload from disk to local buffer if needed
1252     if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1253     assumedsize = GuessSize(remainingsamples);
1254     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1255     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1256 schoenebeck 384 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1257     pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1258 schoenebeck 2 }
1259 persson 365 } // while
1260    
1261 schoenebeck 2 this->SamplePos += (SampleCount - remainingsamples);
1262 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1263 schoenebeck 2 return (SampleCount - remainingsamples);
1264     }
1265     }
1266    
1267 schoenebeck 809 /** @brief Write sample wave data.
1268     *
1269     * Writes \a SampleCount number of sample points from the buffer pointed
1270     * by \a pBuffer and increments the position within the sample. Use this
1271     * method to directly write the sample data to disk, i.e. if you don't
1272     * want or cannot load the whole sample data into RAM.
1273     *
1274     * You have to Resize() the sample to the desired size and call
1275     * File::Save() <b>before</b> using Write().
1276     *
1277     * Note: there is currently no support for writing compressed samples.
1278     *
1279 persson 1264 * For 16 bit samples, the data in the source buffer should be
1280     * int16_t (using native endianness). For 24 bit, the buffer
1281     * should contain three bytes per sample, little-endian.
1282     *
1283 schoenebeck 809 * @param pBuffer - source buffer
1284     * @param SampleCount - number of sample points to write
1285     * @throws DLS::Exception if current sample size is too small
1286     * @throws gig::Exception if sample is compressed
1287     * @see DLS::LoadSampleData()
1288     */
1289     unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1290     if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1291 persson 1207
1292     // if this is the first write in this sample, reset the
1293     // checksum calculator
1294 persson 1199 if (pCkData->GetPos() == 0) {
1295 schoenebeck 1381 __resetCRC(crc);
1296 persson 1199 }
1297 persson 1264 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1298     unsigned long res;
1299     if (BitDepth == 24) {
1300     res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1301     } else { // 16 bit
1302     res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1303     : pCkData->Write(pBuffer, SampleCount, 2);
1304     }
1305 schoenebeck 1381 __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1306 persson 1199
1307 persson 1207 // if this is the last write, update the checksum chunk in the
1308     // file
1309 persson 1199 if (pCkData->GetPos() == pCkData->GetSize()) {
1310     File* pFile = static_cast<File*>(GetParent());
1311 schoenebeck 1381 pFile->SetSampleChecksum(this, __encodeCRC(crc));
1312 persson 1199 }
1313     return res;
1314 schoenebeck 809 }
1315    
1316 schoenebeck 384 /**
1317     * Allocates a decompression buffer for streaming (compressed) samples
1318     * with Sample::Read(). If you are using more than one streaming thread
1319     * in your application you <b>HAVE</b> to create a decompression buffer
1320     * for <b>EACH</b> of your streaming threads and provide it with the
1321     * Sample::Read() call in order to avoid race conditions and crashes.
1322     *
1323     * You should free the memory occupied by the allocated buffer(s) once
1324     * you don't need one of your streaming threads anymore by calling
1325     * DestroyDecompressionBuffer().
1326     *
1327     * @param MaxReadSize - the maximum size (in sample points) you ever
1328     * expect to read with one Read() call
1329     * @returns allocated decompression buffer
1330     * @see DestroyDecompressionBuffer()
1331     */
1332     buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1333     buffer_t result;
1334     const double worstCaseHeaderOverhead =
1335     (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1336     result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1337     result.pStart = new int8_t[result.Size];
1338     result.NullExtensionSize = 0;
1339     return result;
1340     }
1341    
1342     /**
1343     * Free decompression buffer, previously created with
1344     * CreateDecompressionBuffer().
1345     *
1346     * @param DecompressionBuffer - previously allocated decompression
1347     * buffer to free
1348     */
1349     void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1350     if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1351     delete[] (int8_t*) DecompressionBuffer.pStart;
1352     DecompressionBuffer.pStart = NULL;
1353     DecompressionBuffer.Size = 0;
1354     DecompressionBuffer.NullExtensionSize = 0;
1355     }
1356     }
1357    
1358 schoenebeck 930 /**
1359     * Returns pointer to the Group this Sample belongs to. In the .gig
1360     * format a sample always belongs to one group. If it wasn't explicitly
1361     * assigned to a certain group, it will be automatically assigned to a
1362     * default group.
1363     *
1364     * @returns Sample's Group (never NULL)
1365     */
1366     Group* Sample::GetGroup() const {
1367     return pGroup;
1368     }
1369    
1370 schoenebeck 2 Sample::~Sample() {
1371     Instances--;
1372 schoenebeck 384 if (!Instances && InternalDecompressionBuffer.Size) {
1373     delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1374     InternalDecompressionBuffer.pStart = NULL;
1375     InternalDecompressionBuffer.Size = 0;
1376 schoenebeck 355 }
1377 schoenebeck 2 if (FrameTable) delete[] FrameTable;
1378     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1379     }
1380    
1381    
1382    
1383     // *************** DimensionRegion ***************
1384     // *
1385    
1386 schoenebeck 16 uint DimensionRegion::Instances = 0;
1387     DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1388    
1389 schoenebeck 1316 DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1390 schoenebeck 16 Instances++;
1391    
1392 schoenebeck 823 pSample = NULL;
1393 schoenebeck 1316 pRegion = pParent;
1394 schoenebeck 823
1395 persson 1247 if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1396     else memset(&Crossfade, 0, 4);
1397    
1398 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1399 schoenebeck 2
1400     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1401 schoenebeck 809 if (_3ewa) { // if '3ewa' chunk exists
1402 persson 918 _3ewa->ReadInt32(); // unknown, always == chunk size ?
1403 schoenebeck 809 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1404     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1405     _3ewa->ReadInt16(); // unknown
1406     LFO1InternalDepth = _3ewa->ReadUint16();
1407     _3ewa->ReadInt16(); // unknown
1408     LFO3InternalDepth = _3ewa->ReadInt16();
1409     _3ewa->ReadInt16(); // unknown
1410     LFO1ControlDepth = _3ewa->ReadUint16();
1411     _3ewa->ReadInt16(); // unknown
1412     LFO3ControlDepth = _3ewa->ReadInt16();
1413     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1414     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1415     _3ewa->ReadInt16(); // unknown
1416     EG1Sustain = _3ewa->ReadUint16();
1417     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1418     EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1419     uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1420     EG1ControllerInvert = eg1ctrloptions & 0x01;
1421     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1422     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1423     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1424     EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1425     uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1426     EG2ControllerInvert = eg2ctrloptions & 0x01;
1427     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1428     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1429     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1430     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1431     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1432     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1433     _3ewa->ReadInt16(); // unknown
1434     EG2Sustain = _3ewa->ReadUint16();
1435     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1436     _3ewa->ReadInt16(); // unknown
1437     LFO2ControlDepth = _3ewa->ReadUint16();
1438     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1439     _3ewa->ReadInt16(); // unknown
1440     LFO2InternalDepth = _3ewa->ReadUint16();
1441     int32_t eg1decay2 = _3ewa->ReadInt32();
1442     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1443     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1444     _3ewa->ReadInt16(); // unknown
1445     EG1PreAttack = _3ewa->ReadUint16();
1446     int32_t eg2decay2 = _3ewa->ReadInt32();
1447     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1448     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1449     _3ewa->ReadInt16(); // unknown
1450     EG2PreAttack = _3ewa->ReadUint16();
1451     uint8_t velocityresponse = _3ewa->ReadUint8();
1452     if (velocityresponse < 5) {
1453     VelocityResponseCurve = curve_type_nonlinear;
1454     VelocityResponseDepth = velocityresponse;
1455     } else if (velocityresponse < 10) {
1456     VelocityResponseCurve = curve_type_linear;
1457     VelocityResponseDepth = velocityresponse - 5;
1458     } else if (velocityresponse < 15) {
1459     VelocityResponseCurve = curve_type_special;
1460     VelocityResponseDepth = velocityresponse - 10;
1461     } else {
1462     VelocityResponseCurve = curve_type_unknown;
1463     VelocityResponseDepth = 0;
1464     }
1465     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1466     if (releasevelocityresponse < 5) {
1467     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1468     ReleaseVelocityResponseDepth = releasevelocityresponse;
1469     } else if (releasevelocityresponse < 10) {
1470     ReleaseVelocityResponseCurve = curve_type_linear;
1471     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1472     } else if (releasevelocityresponse < 15) {
1473     ReleaseVelocityResponseCurve = curve_type_special;
1474     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1475     } else {
1476     ReleaseVelocityResponseCurve = curve_type_unknown;
1477     ReleaseVelocityResponseDepth = 0;
1478     }
1479     VelocityResponseCurveScaling = _3ewa->ReadUint8();
1480     AttenuationControllerThreshold = _3ewa->ReadInt8();
1481     _3ewa->ReadInt32(); // unknown
1482     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1483     _3ewa->ReadInt16(); // unknown
1484     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1485     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1486     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1487     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1488     else DimensionBypass = dim_bypass_ctrl_none;
1489     uint8_t pan = _3ewa->ReadUint8();
1490     Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1491     SelfMask = _3ewa->ReadInt8() & 0x01;
1492     _3ewa->ReadInt8(); // unknown
1493     uint8_t lfo3ctrl = _3ewa->ReadUint8();
1494     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1495     LFO3Sync = lfo3ctrl & 0x20; // bit 5
1496     InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1497     AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1498     uint8_t lfo2ctrl = _3ewa->ReadUint8();
1499     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1500     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1501     LFO2Sync = lfo2ctrl & 0x20; // bit 5
1502     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1503     uint8_t lfo1ctrl = _3ewa->ReadUint8();
1504     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1505     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1506     LFO1Sync = lfo1ctrl & 0x40; // bit 6
1507     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1508     : vcf_res_ctrl_none;
1509     uint16_t eg3depth = _3ewa->ReadUint16();
1510     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1511 persson 2402 : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1512 schoenebeck 809 _3ewa->ReadInt16(); // unknown
1513     ChannelOffset = _3ewa->ReadUint8() / 4;
1514     uint8_t regoptions = _3ewa->ReadUint8();
1515     MSDecode = regoptions & 0x01; // bit 0
1516     SustainDefeat = regoptions & 0x02; // bit 1
1517     _3ewa->ReadInt16(); // unknown
1518     VelocityUpperLimit = _3ewa->ReadInt8();
1519     _3ewa->ReadInt8(); // unknown
1520     _3ewa->ReadInt16(); // unknown
1521     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1522     _3ewa->ReadInt8(); // unknown
1523     _3ewa->ReadInt8(); // unknown
1524     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1525     uint8_t vcfcutoff = _3ewa->ReadUint8();
1526     VCFEnabled = vcfcutoff & 0x80; // bit 7
1527     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1528     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1529     uint8_t vcfvelscale = _3ewa->ReadUint8();
1530     VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1531     VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1532     _3ewa->ReadInt8(); // unknown
1533     uint8_t vcfresonance = _3ewa->ReadUint8();
1534     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1535     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1536     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1537     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1538     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1539     uint8_t vcfvelocity = _3ewa->ReadUint8();
1540     VCFVelocityDynamicRange = vcfvelocity % 5;
1541     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1542     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1543     if (VCFType == vcf_type_lowpass) {
1544     if (lfo3ctrl & 0x40) // bit 6
1545     VCFType = vcf_type_lowpassturbo;
1546     }
1547 persson 1070 if (_3ewa->RemainingBytes() >= 8) {
1548     _3ewa->Read(DimensionUpperLimits, 1, 8);
1549     } else {
1550     memset(DimensionUpperLimits, 0, 8);
1551     }
1552 schoenebeck 809 } else { // '3ewa' chunk does not exist yet
1553     // use default values
1554     LFO3Frequency = 1.0;
1555     EG3Attack = 0.0;
1556     LFO1InternalDepth = 0;
1557     LFO3InternalDepth = 0;
1558     LFO1ControlDepth = 0;
1559     LFO3ControlDepth = 0;
1560     EG1Attack = 0.0;
1561 persson 1218 EG1Decay1 = 0.005;
1562     EG1Sustain = 1000;
1563     EG1Release = 0.3;
1564 schoenebeck 809 EG1Controller.type = eg1_ctrl_t::type_none;
1565     EG1Controller.controller_number = 0;
1566     EG1ControllerInvert = false;
1567     EG1ControllerAttackInfluence = 0;
1568     EG1ControllerDecayInfluence = 0;
1569     EG1ControllerReleaseInfluence = 0;
1570     EG2Controller.type = eg2_ctrl_t::type_none;
1571     EG2Controller.controller_number = 0;
1572     EG2ControllerInvert = false;
1573     EG2ControllerAttackInfluence = 0;
1574     EG2ControllerDecayInfluence = 0;
1575     EG2ControllerReleaseInfluence = 0;
1576     LFO1Frequency = 1.0;
1577     EG2Attack = 0.0;
1578 persson 1218 EG2Decay1 = 0.005;
1579     EG2Sustain = 1000;
1580     EG2Release = 0.3;
1581 schoenebeck 809 LFO2ControlDepth = 0;
1582     LFO2Frequency = 1.0;
1583     LFO2InternalDepth = 0;
1584     EG1Decay2 = 0.0;
1585 persson 1218 EG1InfiniteSustain = true;
1586     EG1PreAttack = 0;
1587 schoenebeck 809 EG2Decay2 = 0.0;
1588 persson 1218 EG2InfiniteSustain = true;
1589     EG2PreAttack = 0;
1590 schoenebeck 809 VelocityResponseCurve = curve_type_nonlinear;
1591     VelocityResponseDepth = 3;
1592     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1593     ReleaseVelocityResponseDepth = 3;
1594     VelocityResponseCurveScaling = 32;
1595     AttenuationControllerThreshold = 0;
1596     SampleStartOffset = 0;
1597     PitchTrack = true;
1598     DimensionBypass = dim_bypass_ctrl_none;
1599     Pan = 0;
1600     SelfMask = true;
1601     LFO3Controller = lfo3_ctrl_modwheel;
1602     LFO3Sync = false;
1603     InvertAttenuationController = false;
1604     AttenuationController.type = attenuation_ctrl_t::type_none;
1605     AttenuationController.controller_number = 0;
1606     LFO2Controller = lfo2_ctrl_internal;
1607     LFO2FlipPhase = false;
1608     LFO2Sync = false;
1609     LFO1Controller = lfo1_ctrl_internal;
1610     LFO1FlipPhase = false;
1611     LFO1Sync = false;
1612     VCFResonanceController = vcf_res_ctrl_none;
1613     EG3Depth = 0;
1614     ChannelOffset = 0;
1615     MSDecode = false;
1616     SustainDefeat = false;
1617     VelocityUpperLimit = 0;
1618     ReleaseTriggerDecay = 0;
1619     EG1Hold = false;
1620     VCFEnabled = false;
1621     VCFCutoff = 0;
1622     VCFCutoffController = vcf_cutoff_ctrl_none;
1623     VCFCutoffControllerInvert = false;
1624     VCFVelocityScale = 0;
1625     VCFResonance = 0;
1626     VCFResonanceDynamic = false;
1627     VCFKeyboardTracking = false;
1628     VCFKeyboardTrackingBreakpoint = 0;
1629     VCFVelocityDynamicRange = 0x04;
1630     VCFVelocityCurve = curve_type_linear;
1631     VCFType = vcf_type_lowpass;
1632 persson 1247 memset(DimensionUpperLimits, 127, 8);
1633 schoenebeck 2 }
1634 schoenebeck 16
1635 persson 613 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1636     VelocityResponseDepth,
1637     VelocityResponseCurveScaling);
1638    
1639 schoenebeck 1358 pVelocityReleaseTable = GetReleaseVelocityTable(
1640     ReleaseVelocityResponseCurve,
1641     ReleaseVelocityResponseDepth
1642     );
1643 persson 613
1644 schoenebeck 1358 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1645     VCFVelocityDynamicRange,
1646     VCFVelocityScale,
1647     VCFCutoffController);
1648 persson 613
1649     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1650 persson 858 VelocityTable = 0;
1651 persson 613 }
1652    
1653 persson 1301 /*
1654     * Constructs a DimensionRegion by copying all parameters from
1655     * another DimensionRegion
1656     */
1657     DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1658     Instances++;
1659 schoenebeck 2394 //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1660 persson 1301 *this = src; // default memberwise shallow copy of all parameters
1661     pParentList = _3ewl; // restore the chunk pointer
1662    
1663     // deep copy of owned structures
1664     if (src.VelocityTable) {
1665     VelocityTable = new uint8_t[128];
1666     for (int k = 0 ; k < 128 ; k++)
1667     VelocityTable[k] = src.VelocityTable[k];
1668     }
1669     if (src.pSampleLoops) {
1670     pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1671     for (int k = 0 ; k < src.SampleLoops ; k++)
1672     pSampleLoops[k] = src.pSampleLoops[k];
1673     }
1674     }
1675 schoenebeck 2394
1676     /**
1677     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1678     * and assign it to this object.
1679     *
1680     * Note that all sample pointers referenced by @a orig are simply copied as
1681     * memory address. Thus the respective samples are shared, not duplicated!
1682     *
1683     * @param orig - original DimensionRegion object to be copied from
1684     */
1685     void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1686 schoenebeck 2482 CopyAssign(orig, NULL);
1687     }
1688    
1689     /**
1690     * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1691     * and assign it to this object.
1692     *
1693     * @param orig - original DimensionRegion object to be copied from
1694     * @param mSamples - crosslink map between the foreign file's samples and
1695     * this file's samples
1696     */
1697     void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1698 schoenebeck 2394 // delete all allocated data first
1699     if (VelocityTable) delete [] VelocityTable;
1700     if (pSampleLoops) delete [] pSampleLoops;
1701    
1702     // backup parent list pointer
1703     RIFF::List* p = pParentList;
1704    
1705 schoenebeck 2482 gig::Sample* pOriginalSample = pSample;
1706     gig::Region* pOriginalRegion = pRegion;
1707    
1708 schoenebeck 2394 //NOTE: copy code copied from assignment constructor above, see comment there as well
1709    
1710     *this = *orig; // default memberwise shallow copy of all parameters
1711     pParentList = p; // restore the chunk pointer
1712 schoenebeck 2482
1713     // only take the raw sample reference & parent region reference if the
1714     // two DimensionRegion objects are part of the same file
1715     if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1716     pRegion = pOriginalRegion;
1717     pSample = pOriginalSample;
1718     }
1719    
1720     if (mSamples && mSamples->count(orig->pSample)) {
1721     pSample = mSamples->find(orig->pSample)->second;
1722     }
1723 persson 1301
1724 schoenebeck 2394 // deep copy of owned structures
1725     if (orig->VelocityTable) {
1726     VelocityTable = new uint8_t[128];
1727     for (int k = 0 ; k < 128 ; k++)
1728     VelocityTable[k] = orig->VelocityTable[k];
1729     }
1730     if (orig->pSampleLoops) {
1731     pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1732     for (int k = 0 ; k < orig->SampleLoops ; k++)
1733     pSampleLoops[k] = orig->pSampleLoops[k];
1734     }
1735     }
1736    
1737 schoenebeck 809 /**
1738 schoenebeck 1358 * Updates the respective member variable and updates @c SampleAttenuation
1739     * which depends on this value.
1740     */
1741     void DimensionRegion::SetGain(int32_t gain) {
1742     DLS::Sampler::SetGain(gain);
1743     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1744     }
1745    
1746     /**
1747 schoenebeck 809 * Apply dimension region settings to the respective RIFF chunks. You
1748     * have to call File::Save() to make changes persistent.
1749     *
1750     * Usually there is absolutely no need to call this method explicitly.
1751     * It will be called automatically when File::Save() was called.
1752     */
1753     void DimensionRegion::UpdateChunks() {
1754     // first update base class's chunk
1755     DLS::Sampler::UpdateChunks();
1756    
1757 persson 1247 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1758     uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1759     pData[12] = Crossfade.in_start;
1760     pData[13] = Crossfade.in_end;
1761     pData[14] = Crossfade.out_start;
1762     pData[15] = Crossfade.out_end;
1763    
1764 schoenebeck 809 // make sure '3ewa' chunk exists
1765     RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1766 persson 1317 if (!_3ewa) {
1767     File* pFile = (File*) GetParent()->GetParent()->GetParent();
1768     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1769     _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1770 persson 1264 }
1771 persson 1247 pData = (uint8_t*) _3ewa->LoadChunkData();
1772 schoenebeck 809
1773     // update '3ewa' chunk with DimensionRegion's current settings
1774    
1775 persson 1182 const uint32_t chunksize = _3ewa->GetNewSize();
1776 persson 1179 store32(&pData[0], chunksize); // unknown, always chunk size?
1777 schoenebeck 809
1778     const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1779 persson 1179 store32(&pData[4], lfo3freq);
1780 schoenebeck 809
1781     const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1782 persson 1179 store32(&pData[8], eg3attack);
1783 schoenebeck 809
1784     // next 2 bytes unknown
1785    
1786 persson 1179 store16(&pData[14], LFO1InternalDepth);
1787 schoenebeck 809
1788     // next 2 bytes unknown
1789    
1790 persson 1179 store16(&pData[18], LFO3InternalDepth);
1791 schoenebeck 809
1792     // next 2 bytes unknown
1793    
1794 persson 1179 store16(&pData[22], LFO1ControlDepth);
1795 schoenebeck 809
1796     // next 2 bytes unknown
1797    
1798 persson 1179 store16(&pData[26], LFO3ControlDepth);
1799 schoenebeck 809
1800     const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1801 persson 1179 store32(&pData[28], eg1attack);
1802 schoenebeck 809
1803     const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1804 persson 1179 store32(&pData[32], eg1decay1);
1805 schoenebeck 809
1806     // next 2 bytes unknown
1807    
1808 persson 1179 store16(&pData[38], EG1Sustain);
1809 schoenebeck 809
1810     const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1811 persson 1179 store32(&pData[40], eg1release);
1812 schoenebeck 809
1813     const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1814 persson 1179 pData[44] = eg1ctl;
1815 schoenebeck 809
1816     const uint8_t eg1ctrloptions =
1817 persson 1266 (EG1ControllerInvert ? 0x01 : 0x00) |
1818 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1819     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1820     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1821 persson 1179 pData[45] = eg1ctrloptions;
1822 schoenebeck 809
1823     const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1824 persson 1179 pData[46] = eg2ctl;
1825 schoenebeck 809
1826     const uint8_t eg2ctrloptions =
1827 persson 1266 (EG2ControllerInvert ? 0x01 : 0x00) |
1828 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1829     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1830     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1831 persson 1179 pData[47] = eg2ctrloptions;
1832 schoenebeck 809
1833     const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1834 persson 1179 store32(&pData[48], lfo1freq);
1835 schoenebeck 809
1836     const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1837 persson 1179 store32(&pData[52], eg2attack);
1838 schoenebeck 809
1839     const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1840 persson 1179 store32(&pData[56], eg2decay1);
1841 schoenebeck 809
1842     // next 2 bytes unknown
1843    
1844 persson 1179 store16(&pData[62], EG2Sustain);
1845 schoenebeck 809
1846     const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1847 persson 1179 store32(&pData[64], eg2release);
1848 schoenebeck 809
1849     // next 2 bytes unknown
1850    
1851 persson 1179 store16(&pData[70], LFO2ControlDepth);
1852 schoenebeck 809
1853     const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1854 persson 1179 store32(&pData[72], lfo2freq);
1855 schoenebeck 809
1856     // next 2 bytes unknown
1857    
1858 persson 1179 store16(&pData[78], LFO2InternalDepth);
1859 schoenebeck 809
1860     const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1861 persson 1179 store32(&pData[80], eg1decay2);
1862 schoenebeck 809
1863     // next 2 bytes unknown
1864    
1865 persson 1179 store16(&pData[86], EG1PreAttack);
1866 schoenebeck 809
1867     const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1868 persson 1179 store32(&pData[88], eg2decay2);
1869 schoenebeck 809
1870     // next 2 bytes unknown
1871    
1872 persson 1179 store16(&pData[94], EG2PreAttack);
1873 schoenebeck 809
1874     {
1875     if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1876     uint8_t velocityresponse = VelocityResponseDepth;
1877     switch (VelocityResponseCurve) {
1878     case curve_type_nonlinear:
1879     break;
1880     case curve_type_linear:
1881     velocityresponse += 5;
1882     break;
1883     case curve_type_special:
1884     velocityresponse += 10;
1885     break;
1886     case curve_type_unknown:
1887     default:
1888     throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1889     }
1890 persson 1179 pData[96] = velocityresponse;
1891 schoenebeck 809 }
1892    
1893     {
1894     if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1895     uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1896     switch (ReleaseVelocityResponseCurve) {
1897     case curve_type_nonlinear:
1898     break;
1899     case curve_type_linear:
1900     releasevelocityresponse += 5;
1901     break;
1902     case curve_type_special:
1903     releasevelocityresponse += 10;
1904     break;
1905     case curve_type_unknown:
1906     default:
1907     throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1908     }
1909 persson 1179 pData[97] = releasevelocityresponse;
1910 schoenebeck 809 }
1911    
1912 persson 1179 pData[98] = VelocityResponseCurveScaling;
1913 schoenebeck 809
1914 persson 1179 pData[99] = AttenuationControllerThreshold;
1915 schoenebeck 809
1916     // next 4 bytes unknown
1917    
1918 persson 1179 store16(&pData[104], SampleStartOffset);
1919 schoenebeck 809
1920     // next 2 bytes unknown
1921    
1922     {
1923     uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1924     switch (DimensionBypass) {
1925     case dim_bypass_ctrl_94:
1926     pitchTrackDimensionBypass |= 0x10;
1927     break;
1928     case dim_bypass_ctrl_95:
1929     pitchTrackDimensionBypass |= 0x20;
1930     break;
1931     case dim_bypass_ctrl_none:
1932     //FIXME: should we set anything here?
1933     break;
1934     default:
1935     throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1936     }
1937 persson 1179 pData[108] = pitchTrackDimensionBypass;
1938 schoenebeck 809 }
1939    
1940     const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1941 persson 1179 pData[109] = pan;
1942 schoenebeck 809
1943     const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1944 persson 1179 pData[110] = selfmask;
1945 schoenebeck 809
1946     // next byte unknown
1947    
1948     {
1949     uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1950     if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1951     if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1952     if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1953 persson 1179 pData[112] = lfo3ctrl;
1954 schoenebeck 809 }
1955    
1956     const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1957 persson 1179 pData[113] = attenctl;
1958 schoenebeck 809
1959     {
1960     uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1961     if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1962     if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1963     if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1964 persson 1179 pData[114] = lfo2ctrl;
1965 schoenebeck 809 }
1966    
1967     {
1968     uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1969     if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1970     if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1971     if (VCFResonanceController != vcf_res_ctrl_none)
1972     lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1973 persson 1179 pData[115] = lfo1ctrl;
1974 schoenebeck 809 }
1975    
1976     const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1977 persson 2402 : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1978 persson 1869 store16(&pData[116], eg3depth);
1979 schoenebeck 809
1980     // next 2 bytes unknown
1981    
1982     const uint8_t channeloffset = ChannelOffset * 4;
1983 persson 1179 pData[120] = channeloffset;
1984 schoenebeck 809
1985     {
1986     uint8_t regoptions = 0;
1987     if (MSDecode) regoptions |= 0x01; // bit 0
1988     if (SustainDefeat) regoptions |= 0x02; // bit 1
1989 persson 1179 pData[121] = regoptions;
1990 schoenebeck 809 }
1991    
1992     // next 2 bytes unknown
1993    
1994 persson 1179 pData[124] = VelocityUpperLimit;
1995 schoenebeck 809
1996     // next 3 bytes unknown
1997    
1998 persson 1179 pData[128] = ReleaseTriggerDecay;
1999 schoenebeck 809
2000     // next 2 bytes unknown
2001    
2002     const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2003 persson 1179 pData[131] = eg1hold;
2004 schoenebeck 809
2005 persson 1266 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2006 persson 918 (VCFCutoff & 0x7f); /* lower 7 bits */
2007 persson 1179 pData[132] = vcfcutoff;
2008 schoenebeck 809
2009 persson 1179 pData[133] = VCFCutoffController;
2010 schoenebeck 809
2011 persson 1266 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2012 persson 918 (VCFVelocityScale & 0x7f); /* lower 7 bits */
2013 persson 1179 pData[134] = vcfvelscale;
2014 schoenebeck 809
2015     // next byte unknown
2016    
2017 persson 1266 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2018 persson 918 (VCFResonance & 0x7f); /* lower 7 bits */
2019 persson 1179 pData[136] = vcfresonance;
2020 schoenebeck 809
2021 persson 1266 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2022 persson 918 (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2023 persson 1179 pData[137] = vcfbreakpoint;
2024 schoenebeck 809
2025 persson 2152 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2026 schoenebeck 809 VCFVelocityCurve * 5;
2027 persson 1179 pData[138] = vcfvelocity;
2028 schoenebeck 809
2029     const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2030 persson 1179 pData[139] = vcftype;
2031 persson 1070
2032     if (chunksize >= 148) {
2033     memcpy(&pData[140], DimensionUpperLimits, 8);
2034     }
2035 schoenebeck 809 }
2036    
2037 schoenebeck 1358 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2038     curve_type_t curveType = releaseVelocityResponseCurve;
2039     uint8_t depth = releaseVelocityResponseDepth;
2040     // this models a strange behaviour or bug in GSt: two of the
2041     // velocity response curves for release time are not used even
2042     // if specified, instead another curve is chosen.
2043     if ((curveType == curve_type_nonlinear && depth == 0) ||
2044     (curveType == curve_type_special && depth == 4)) {
2045     curveType = curve_type_nonlinear;
2046     depth = 3;
2047     }
2048     return GetVelocityTable(curveType, depth, 0);
2049     }
2050    
2051     double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2052     uint8_t vcfVelocityDynamicRange,
2053     uint8_t vcfVelocityScale,
2054     vcf_cutoff_ctrl_t vcfCutoffController)
2055     {
2056     curve_type_t curveType = vcfVelocityCurve;
2057     uint8_t depth = vcfVelocityDynamicRange;
2058     // even stranger GSt: two of the velocity response curves for
2059     // filter cutoff are not used, instead another special curve
2060     // is chosen. This curve is not used anywhere else.
2061     if ((curveType == curve_type_nonlinear && depth == 0) ||
2062     (curveType == curve_type_special && depth == 4)) {
2063     curveType = curve_type_special;
2064     depth = 5;
2065     }
2066     return GetVelocityTable(curveType, depth,
2067     (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2068     ? vcfVelocityScale : 0);
2069     }
2070    
2071 persson 613 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2072     double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2073     {
2074     double* table;
2075     uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2076 schoenebeck 16 if (pVelocityTables->count(tableKey)) { // if key exists
2077 persson 613 table = (*pVelocityTables)[tableKey];
2078 schoenebeck 16 }
2079     else {
2080 persson 613 table = CreateVelocityTable(curveType, depth, scaling);
2081     (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2082 schoenebeck 16 }
2083 persson 613 return table;
2084 schoenebeck 2 }
2085 schoenebeck 55
2086 schoenebeck 1316 Region* DimensionRegion::GetParent() const {
2087     return pRegion;
2088     }
2089    
2090 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2091     leverage_ctrl_t decodedcontroller;
2092     switch (EncodedController) {
2093     // special controller
2094     case _lev_ctrl_none:
2095     decodedcontroller.type = leverage_ctrl_t::type_none;
2096     decodedcontroller.controller_number = 0;
2097     break;
2098     case _lev_ctrl_velocity:
2099     decodedcontroller.type = leverage_ctrl_t::type_velocity;
2100     decodedcontroller.controller_number = 0;
2101     break;
2102     case _lev_ctrl_channelaftertouch:
2103     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2104     decodedcontroller.controller_number = 0;
2105     break;
2106 schoenebeck 55
2107 schoenebeck 36 // ordinary MIDI control change controller
2108     case _lev_ctrl_modwheel:
2109     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2110     decodedcontroller.controller_number = 1;
2111     break;
2112     case _lev_ctrl_breath:
2113     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2114     decodedcontroller.controller_number = 2;
2115     break;
2116     case _lev_ctrl_foot:
2117     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2118     decodedcontroller.controller_number = 4;
2119     break;
2120     case _lev_ctrl_effect1:
2121     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2122     decodedcontroller.controller_number = 12;
2123     break;
2124     case _lev_ctrl_effect2:
2125     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2126     decodedcontroller.controller_number = 13;
2127     break;
2128     case _lev_ctrl_genpurpose1:
2129     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2130     decodedcontroller.controller_number = 16;
2131     break;
2132     case _lev_ctrl_genpurpose2:
2133     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2134     decodedcontroller.controller_number = 17;
2135     break;
2136     case _lev_ctrl_genpurpose3:
2137     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2138     decodedcontroller.controller_number = 18;
2139     break;
2140     case _lev_ctrl_genpurpose4:
2141     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2142     decodedcontroller.controller_number = 19;
2143     break;
2144     case _lev_ctrl_portamentotime:
2145     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2146     decodedcontroller.controller_number = 5;
2147     break;
2148     case _lev_ctrl_sustainpedal:
2149     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2150     decodedcontroller.controller_number = 64;
2151     break;
2152     case _lev_ctrl_portamento:
2153     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2154     decodedcontroller.controller_number = 65;
2155     break;
2156     case _lev_ctrl_sostenutopedal:
2157     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2158     decodedcontroller.controller_number = 66;
2159     break;
2160     case _lev_ctrl_softpedal:
2161     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2162     decodedcontroller.controller_number = 67;
2163     break;
2164     case _lev_ctrl_genpurpose5:
2165     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2166     decodedcontroller.controller_number = 80;
2167     break;
2168     case _lev_ctrl_genpurpose6:
2169     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2170     decodedcontroller.controller_number = 81;
2171     break;
2172     case _lev_ctrl_genpurpose7:
2173     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2174     decodedcontroller.controller_number = 82;
2175     break;
2176     case _lev_ctrl_genpurpose8:
2177     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178     decodedcontroller.controller_number = 83;
2179     break;
2180     case _lev_ctrl_effect1depth:
2181     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2182     decodedcontroller.controller_number = 91;
2183     break;
2184     case _lev_ctrl_effect2depth:
2185     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186     decodedcontroller.controller_number = 92;
2187     break;
2188     case _lev_ctrl_effect3depth:
2189     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190     decodedcontroller.controller_number = 93;
2191     break;
2192     case _lev_ctrl_effect4depth:
2193     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194     decodedcontroller.controller_number = 94;
2195     break;
2196     case _lev_ctrl_effect5depth:
2197     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198     decodedcontroller.controller_number = 95;
2199     break;
2200 schoenebeck 55
2201 schoenebeck 36 // unknown controller type
2202     default:
2203     throw gig::Exception("Unknown leverage controller type.");
2204     }
2205     return decodedcontroller;
2206     }
2207 schoenebeck 2
2208 schoenebeck 809 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2209     _lev_ctrl_t encodedcontroller;
2210     switch (DecodedController.type) {
2211     // special controller
2212     case leverage_ctrl_t::type_none:
2213     encodedcontroller = _lev_ctrl_none;
2214     break;
2215     case leverage_ctrl_t::type_velocity:
2216     encodedcontroller = _lev_ctrl_velocity;
2217     break;
2218     case leverage_ctrl_t::type_channelaftertouch:
2219     encodedcontroller = _lev_ctrl_channelaftertouch;
2220     break;
2221    
2222     // ordinary MIDI control change controller
2223     case leverage_ctrl_t::type_controlchange:
2224     switch (DecodedController.controller_number) {
2225     case 1:
2226     encodedcontroller = _lev_ctrl_modwheel;
2227     break;
2228     case 2:
2229     encodedcontroller = _lev_ctrl_breath;
2230     break;
2231     case 4:
2232     encodedcontroller = _lev_ctrl_foot;
2233     break;
2234     case 12:
2235     encodedcontroller = _lev_ctrl_effect1;
2236     break;
2237     case 13:
2238     encodedcontroller = _lev_ctrl_effect2;
2239     break;
2240     case 16:
2241     encodedcontroller = _lev_ctrl_genpurpose1;
2242     break;
2243     case 17:
2244     encodedcontroller = _lev_ctrl_genpurpose2;
2245     break;
2246     case 18:
2247     encodedcontroller = _lev_ctrl_genpurpose3;
2248     break;
2249     case 19:
2250     encodedcontroller = _lev_ctrl_genpurpose4;
2251     break;
2252     case 5:
2253     encodedcontroller = _lev_ctrl_portamentotime;
2254     break;
2255     case 64:
2256     encodedcontroller = _lev_ctrl_sustainpedal;
2257     break;
2258     case 65:
2259     encodedcontroller = _lev_ctrl_portamento;
2260     break;
2261     case 66:
2262     encodedcontroller = _lev_ctrl_sostenutopedal;
2263     break;
2264     case 67:
2265     encodedcontroller = _lev_ctrl_softpedal;
2266     break;
2267     case 80:
2268     encodedcontroller = _lev_ctrl_genpurpose5;
2269     break;
2270     case 81:
2271     encodedcontroller = _lev_ctrl_genpurpose6;
2272     break;
2273     case 82:
2274     encodedcontroller = _lev_ctrl_genpurpose7;
2275     break;
2276     case 83:
2277     encodedcontroller = _lev_ctrl_genpurpose8;
2278     break;
2279     case 91:
2280     encodedcontroller = _lev_ctrl_effect1depth;
2281     break;
2282     case 92:
2283     encodedcontroller = _lev_ctrl_effect2depth;
2284     break;
2285     case 93:
2286     encodedcontroller = _lev_ctrl_effect3depth;
2287     break;
2288     case 94:
2289     encodedcontroller = _lev_ctrl_effect4depth;
2290     break;
2291     case 95:
2292     encodedcontroller = _lev_ctrl_effect5depth;
2293     break;
2294     default:
2295     throw gig::Exception("leverage controller number is not supported by the gig format");
2296     }
2297 persson 1182 break;
2298 schoenebeck 809 default:
2299     throw gig::Exception("Unknown leverage controller type.");
2300     }
2301     return encodedcontroller;
2302     }
2303    
2304 schoenebeck 16 DimensionRegion::~DimensionRegion() {
2305     Instances--;
2306     if (!Instances) {
2307     // delete the velocity->volume tables
2308     VelocityTableMap::iterator iter;
2309     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2310     double* pTable = iter->second;
2311     if (pTable) delete[] pTable;
2312     }
2313     pVelocityTables->clear();
2314     delete pVelocityTables;
2315     pVelocityTables = NULL;
2316     }
2317 persson 858 if (VelocityTable) delete[] VelocityTable;
2318 schoenebeck 16 }
2319 schoenebeck 2
2320 schoenebeck 16 /**
2321     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
2322     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
2323     * and VelocityResponseCurveScaling) involved are taken into account to
2324     * calculate the amplitude factor. Use this method when a key was
2325     * triggered to get the volume with which the sample should be played
2326     * back.
2327     *
2328 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
2329     * @returns amplitude factor (between 0.0 and 1.0)
2330 schoenebeck 16 */
2331     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2332     return pVelocityAttenuationTable[MIDIKeyVelocity];
2333     }
2334 schoenebeck 2
2335 persson 613 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2336     return pVelocityReleaseTable[MIDIKeyVelocity];
2337     }
2338    
2339 persson 728 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2340     return pVelocityCutoffTable[MIDIKeyVelocity];
2341     }
2342    
2343 schoenebeck 1358 /**
2344     * Updates the respective member variable and the lookup table / cache
2345     * that depends on this value.
2346     */
2347     void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2348     pVelocityAttenuationTable =
2349     GetVelocityTable(
2350     curve, VelocityResponseDepth, VelocityResponseCurveScaling
2351     );
2352     VelocityResponseCurve = curve;
2353     }
2354    
2355     /**
2356     * Updates the respective member variable and the lookup table / cache
2357     * that depends on this value.
2358     */
2359     void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2360     pVelocityAttenuationTable =
2361     GetVelocityTable(
2362     VelocityResponseCurve, depth, VelocityResponseCurveScaling
2363     );
2364     VelocityResponseDepth = depth;
2365     }
2366    
2367     /**
2368     * Updates the respective member variable and the lookup table / cache
2369     * that depends on this value.
2370     */
2371     void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2372     pVelocityAttenuationTable =
2373     GetVelocityTable(
2374     VelocityResponseCurve, VelocityResponseDepth, scaling
2375     );
2376     VelocityResponseCurveScaling = scaling;
2377     }
2378    
2379     /**
2380     * Updates the respective member variable and the lookup table / cache
2381     * that depends on this value.
2382     */
2383     void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2384     pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2385     ReleaseVelocityResponseCurve = curve;
2386     }
2387    
2388     /**
2389     * Updates the respective member variable and the lookup table / cache
2390     * that depends on this value.
2391     */
2392     void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2393     pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2394     ReleaseVelocityResponseDepth = depth;
2395     }
2396    
2397     /**
2398     * Updates the respective member variable and the lookup table / cache
2399     * that depends on this value.
2400     */
2401     void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2402     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2403     VCFCutoffController = controller;
2404     }
2405    
2406     /**
2407     * Updates the respective member variable and the lookup table / cache
2408     * that depends on this value.
2409     */
2410     void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2411     pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2412     VCFVelocityCurve = curve;
2413     }
2414    
2415     /**
2416     * Updates the respective member variable and the lookup table / cache
2417     * that depends on this value.
2418     */
2419     void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2420     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2421     VCFVelocityDynamicRange = range;
2422     }
2423    
2424     /**
2425     * Updates the respective member variable and the lookup table / cache
2426     * that depends on this value.
2427     */
2428     void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2429     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2430     VCFVelocityScale = scaling;
2431     }
2432    
2433 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2434 schoenebeck 317
2435 schoenebeck 308 // line-segment approximations of the 15 velocity curves
2436 schoenebeck 16
2437 schoenebeck 308 // linear
2438     const int lin0[] = { 1, 1, 127, 127 };
2439     const int lin1[] = { 1, 21, 127, 127 };
2440     const int lin2[] = { 1, 45, 127, 127 };
2441     const int lin3[] = { 1, 74, 127, 127 };
2442     const int lin4[] = { 1, 127, 127, 127 };
2443 schoenebeck 16
2444 schoenebeck 308 // non-linear
2445     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2446 schoenebeck 317 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2447 schoenebeck 308 127, 127 };
2448     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2449     127, 127 };
2450     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2451     127, 127 };
2452     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2453 schoenebeck 317
2454 schoenebeck 308 // special
2455 schoenebeck 317 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2456 schoenebeck 308 113, 127, 127, 127 };
2457     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2458     118, 127, 127, 127 };
2459 schoenebeck 317 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2460 schoenebeck 308 85, 90, 91, 127, 127, 127 };
2461 schoenebeck 317 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2462 schoenebeck 308 117, 127, 127, 127 };
2463 schoenebeck 317 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2464 schoenebeck 308 127, 127 };
2465 schoenebeck 317
2466 persson 728 // this is only used by the VCF velocity curve
2467     const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2468     91, 127, 127, 127 };
2469    
2470 schoenebeck 308 const int* const curves[] = { non0, non1, non2, non3, non4,
2471 schoenebeck 317 lin0, lin1, lin2, lin3, lin4,
2472 persson 728 spe0, spe1, spe2, spe3, spe4, spe5 };
2473 schoenebeck 317
2474 schoenebeck 308 double* const table = new double[128];
2475    
2476     const int* curve = curves[curveType * 5 + depth];
2477     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2478 schoenebeck 317
2479 schoenebeck 308 table[0] = 0;
2480     for (int x = 1 ; x < 128 ; x++) {
2481    
2482     if (x > curve[2]) curve += 2;
2483 schoenebeck 317 double y = curve[1] + (x - curve[0]) *
2484 schoenebeck 308 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2485     y = y / 127;
2486    
2487     // Scale up for s > 20, down for s < 20. When
2488     // down-scaling, the curve still ends at 1.0.
2489     if (s < 20 && y >= 0.5)
2490     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2491     else
2492     y = y * (s / 20.0);
2493     if (y > 1) y = 1;
2494    
2495     table[x] = y;
2496     }
2497     return table;
2498     }
2499    
2500    
2501 schoenebeck 2 // *************** Region ***************
2502     // *
2503    
2504     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2505     // Initialization
2506     Dimensions = 0;
2507 schoenebeck 347 for (int i = 0; i < 256; i++) {
2508 schoenebeck 2 pDimensionRegions[i] = NULL;
2509     }
2510 schoenebeck 282 Layers = 1;
2511 schoenebeck 347 File* file = (File*) GetParent()->GetParent();
2512     int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2513 schoenebeck 2
2514     // Actual Loading
2515    
2516 schoenebeck 1524 if (!file->GetAutoLoad()) return;
2517    
2518 schoenebeck 2 LoadDimensionRegions(rgnList);
2519    
2520     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2521     if (_3lnk) {
2522     DimensionRegions = _3lnk->ReadUint32();
2523 schoenebeck 347 for (int i = 0; i < dimensionBits; i++) {
2524 schoenebeck 2 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2525     uint8_t bits = _3lnk->ReadUint8();
2526 persson 1199 _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2527     _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2528 persson 774 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2529 schoenebeck 2 if (dimension == dimension_none) { // inactive dimension
2530     pDimensionDefinitions[i].dimension = dimension_none;
2531     pDimensionDefinitions[i].bits = 0;
2532     pDimensionDefinitions[i].zones = 0;
2533     pDimensionDefinitions[i].split_type = split_type_bit;
2534     pDimensionDefinitions[i].zone_size = 0;
2535     }
2536     else { // active dimension
2537     pDimensionDefinitions[i].dimension = dimension;
2538     pDimensionDefinitions[i].bits = bits;
2539 persson 774 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2540 schoenebeck 1113 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2541     pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
2542 schoenebeck 2 Dimensions++;
2543 schoenebeck 282
2544     // if this is a layer dimension, remember the amount of layers
2545     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2546 schoenebeck 2 }
2547 persson 774 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2548 schoenebeck 2 }
2549 persson 834 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2550 schoenebeck 2
2551 persson 858 // if there's a velocity dimension and custom velocity zone splits are used,
2552     // update the VelocityTables in the dimension regions
2553     UpdateVelocityTable();
2554 schoenebeck 2
2555 schoenebeck 317 // jump to start of the wave pool indices (if not already there)
2556     if (file->pVersion && file->pVersion->major == 3)
2557     _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2558     else
2559     _3lnk->SetPos(44);
2560    
2561 schoenebeck 1524 // load sample references (if auto loading is enabled)
2562     if (file->GetAutoLoad()) {
2563     for (uint i = 0; i < DimensionRegions; i++) {
2564     uint32_t wavepoolindex = _3lnk->ReadUint32();
2565     if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2566     }
2567     GetSample(); // load global region sample reference
2568 schoenebeck 2 }
2569 persson 1102 } else {
2570     DimensionRegions = 0;
2571 persson 1182 for (int i = 0 ; i < 8 ; i++) {
2572     pDimensionDefinitions[i].dimension = dimension_none;
2573     pDimensionDefinitions[i].bits = 0;
2574     pDimensionDefinitions[i].zones = 0;
2575     }
2576 schoenebeck 2 }
2577 schoenebeck 823
2578     // make sure there is at least one dimension region
2579     if (!DimensionRegions) {
2580     RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2581     if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2582     RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2583 schoenebeck 1316 pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2584 schoenebeck 823 DimensionRegions = 1;
2585     }
2586 schoenebeck 2 }
2587    
2588 schoenebeck 809 /**
2589     * Apply Region settings and all its DimensionRegions to the respective
2590     * RIFF chunks. You have to call File::Save() to make changes persistent.
2591     *
2592     * Usually there is absolutely no need to call this method explicitly.
2593     * It will be called automatically when File::Save() was called.
2594     *
2595     * @throws gig::Exception if samples cannot be dereferenced
2596     */
2597     void Region::UpdateChunks() {
2598 schoenebeck 1106 // in the gig format we don't care about the Region's sample reference
2599     // but we still have to provide some existing one to not corrupt the
2600     // file, so to avoid the latter we simply always assign the sample of
2601     // the first dimension region of this region
2602     pSample = pDimensionRegions[0]->pSample;
2603    
2604 schoenebeck 809 // first update base class's chunks
2605     DLS::Region::UpdateChunks();
2606    
2607     // update dimension region's chunks
2608 schoenebeck 823 for (int i = 0; i < DimensionRegions; i++) {
2609 persson 1317 pDimensionRegions[i]->UpdateChunks();
2610 schoenebeck 823 }
2611 schoenebeck 809
2612 persson 1317 File* pFile = (File*) GetParent()->GetParent();
2613     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2614 persson 1247 const int iMaxDimensions = version3 ? 8 : 5;
2615     const int iMaxDimensionRegions = version3 ? 256 : 32;
2616 schoenebeck 809
2617     // make sure '3lnk' chunk exists
2618     RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2619     if (!_3lnk) {
2620 persson 1247 const int _3lnkChunkSize = version3 ? 1092 : 172;
2621 schoenebeck 809 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2622 persson 1182 memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2623 persson 1192
2624     // move 3prg to last position
2625     pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2626 schoenebeck 809 }
2627    
2628     // update dimension definitions in '3lnk' chunk
2629     uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2630 persson 1179 store32(&pData[0], DimensionRegions);
2631 persson 1199 int shift = 0;
2632 schoenebeck 809 for (int i = 0; i < iMaxDimensions; i++) {
2633 persson 918 pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2634     pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2635 persson 1266 pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2636 persson 1199 pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2637 persson 918 pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2638 persson 1199 // next 3 bytes unknown, always zero?
2639    
2640     shift += pDimensionDefinitions[i].bits;
2641 schoenebeck 809 }
2642    
2643     // update wave pool table in '3lnk' chunk
2644 persson 1247 const int iWavePoolOffset = version3 ? 68 : 44;
2645 schoenebeck 809 for (uint i = 0; i < iMaxDimensionRegions; i++) {
2646     int iWaveIndex = -1;
2647     if (i < DimensionRegions) {
2648 schoenebeck 823 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2649     File::SampleList::iterator iter = pFile->pSamples->begin();
2650     File::SampleList::iterator end = pFile->pSamples->end();
2651 schoenebeck 809 for (int index = 0; iter != end; ++iter, ++index) {
2652 schoenebeck 823 if (*iter == pDimensionRegions[i]->pSample) {
2653     iWaveIndex = index;
2654     break;
2655     }
2656 schoenebeck 809 }
2657     }
2658 persson 1179 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2659 schoenebeck 809 }
2660     }
2661    
2662 schoenebeck 2 void Region::LoadDimensionRegions(RIFF::List* rgn) {
2663     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
2664     if (_3prg) {
2665     int dimensionRegionNr = 0;
2666     RIFF::List* _3ewl = _3prg->GetFirstSubList();
2667     while (_3ewl) {
2668     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2669 schoenebeck 1316 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2670 schoenebeck 2 dimensionRegionNr++;
2671     }
2672     _3ewl = _3prg->GetNextSubList();
2673     }
2674     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
2675     }
2676     }
2677    
2678 schoenebeck 1335 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2679     // update KeyRange struct and make sure regions are in correct order
2680     DLS::Region::SetKeyRange(Low, High);
2681     // update Region key table for fast lookup
2682     ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2683     }
2684    
2685 persson 858 void Region::UpdateVelocityTable() {
2686     // get velocity dimension's index
2687     int veldim = -1;
2688     for (int i = 0 ; i < Dimensions ; i++) {
2689     if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2690     veldim = i;
2691 schoenebeck 809 break;
2692     }
2693     }
2694 persson 858 if (veldim == -1) return;
2695 schoenebeck 809
2696 persson 858 int step = 1;
2697     for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2698     int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2699     int end = step * pDimensionDefinitions[veldim].zones;
2700 schoenebeck 809
2701 persson 858 // loop through all dimension regions for all dimensions except the velocity dimension
2702     int dim[8] = { 0 };
2703     for (int i = 0 ; i < DimensionRegions ; i++) {
2704    
2705 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2706     pDimensionRegions[i]->VelocityUpperLimit) {
2707 persson 858 // create the velocity table
2708     uint8_t* table = pDimensionRegions[i]->VelocityTable;
2709     if (!table) {
2710     table = new uint8_t[128];
2711     pDimensionRegions[i]->VelocityTable = table;
2712     }
2713     int tableidx = 0;
2714     int velocityZone = 0;
2715 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2716     for (int k = i ; k < end ; k += step) {
2717     DimensionRegion *d = pDimensionRegions[k];
2718     for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2719     velocityZone++;
2720     }
2721     } else { // gig2
2722     for (int k = i ; k < end ; k += step) {
2723     DimensionRegion *d = pDimensionRegions[k];
2724     for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2725     velocityZone++;
2726     }
2727 persson 858 }
2728     } else {
2729     if (pDimensionRegions[i]->VelocityTable) {
2730     delete[] pDimensionRegions[i]->VelocityTable;
2731     pDimensionRegions[i]->VelocityTable = 0;
2732     }
2733 schoenebeck 809 }
2734 persson 858
2735     int j;
2736     int shift = 0;
2737     for (j = 0 ; j < Dimensions ; j++) {
2738     if (j == veldim) i += skipveldim; // skip velocity dimension
2739     else {
2740     dim[j]++;
2741     if (dim[j] < pDimensionDefinitions[j].zones) break;
2742     else {
2743     // skip unused dimension regions
2744     dim[j] = 0;
2745     i += ((1 << pDimensionDefinitions[j].bits) -
2746     pDimensionDefinitions[j].zones) << shift;
2747     }
2748     }
2749     shift += pDimensionDefinitions[j].bits;
2750     }
2751     if (j == Dimensions) break;
2752 schoenebeck 809 }
2753     }
2754    
2755     /** @brief Einstein would have dreamed of it - create a new dimension.
2756     *
2757     * Creates a new dimension with the dimension definition given by
2758     * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2759     * There is a hard limit of dimensions and total amount of "bits" all
2760     * dimensions can have. This limit is dependant to what gig file format
2761     * version this file refers to. The gig v2 (and lower) format has a
2762     * dimension limit and total amount of bits limit of 5, whereas the gig v3
2763     * format has a limit of 8.
2764     *
2765     * @param pDimDef - defintion of the new dimension
2766     * @throws gig::Exception if dimension of the same type exists already
2767     * @throws gig::Exception if amount of dimensions or total amount of
2768     * dimension bits limit is violated
2769     */
2770     void Region::AddDimension(dimension_def_t* pDimDef) {
2771     // check if max. amount of dimensions reached
2772     File* file = (File*) GetParent()->GetParent();
2773     const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2774     if (Dimensions >= iMaxDimensions)
2775     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2776     // check if max. amount of dimension bits reached
2777     int iCurrentBits = 0;
2778     for (int i = 0; i < Dimensions; i++)
2779     iCurrentBits += pDimensionDefinitions[i].bits;
2780     if (iCurrentBits >= iMaxDimensions)
2781     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2782     const int iNewBits = iCurrentBits + pDimDef->bits;
2783     if (iNewBits > iMaxDimensions)
2784     throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2785     // check if there's already a dimensions of the same type
2786     for (int i = 0; i < Dimensions; i++)
2787     if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2788     throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2789    
2790 persson 1301 // pos is where the new dimension should be placed, normally
2791     // last in list, except for the samplechannel dimension which
2792     // has to be first in list
2793     int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2794     int bitpos = 0;
2795     for (int i = 0 ; i < pos ; i++)
2796     bitpos += pDimensionDefinitions[i].bits;
2797    
2798     // make room for the new dimension
2799     for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2800     for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2801     for (int j = Dimensions ; j > pos ; j--) {
2802     pDimensionRegions[i]->DimensionUpperLimits[j] =
2803     pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2804     }
2805     }
2806    
2807 schoenebeck 809 // assign definition of new dimension
2808 persson 1301 pDimensionDefinitions[pos] = *pDimDef;
2809 schoenebeck 809
2810 schoenebeck 1113 // auto correct certain dimension definition fields (where possible)
2811 persson 1301 pDimensionDefinitions[pos].split_type =
2812     __resolveSplitType(pDimensionDefinitions[pos].dimension);
2813     pDimensionDefinitions[pos].zone_size =
2814     __resolveZoneSize(pDimensionDefinitions[pos]);
2815 schoenebeck 1113
2816 persson 1301 // create new dimension region(s) for this new dimension, and make
2817     // sure that the dimension regions are placed correctly in both the
2818     // RIFF list and the pDimensionRegions array
2819     RIFF::Chunk* moveTo = NULL;
2820     RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2821     for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2822     for (int k = 0 ; k < (1 << bitpos) ; k++) {
2823     pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2824     }
2825     for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2826     for (int k = 0 ; k < (1 << bitpos) ; k++) {
2827     RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2828     if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2829     // create a new dimension region and copy all parameter values from
2830     // an existing dimension region
2831     pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2832     new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2833 persson 1247
2834 persson 1301 DimensionRegions++;
2835     }
2836     }
2837     moveTo = pDimensionRegions[i]->pParentList;
2838 schoenebeck 809 }
2839    
2840 persson 1247 // initialize the upper limits for this dimension
2841 persson 1301 int mask = (1 << bitpos) - 1;
2842     for (int z = 0 ; z < pDimDef->zones ; z++) {
2843 persson 1264 uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2844 persson 1247 for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2845 persson 1301 pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2846     (z << bitpos) |
2847     (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2848 persson 1247 }
2849     }
2850    
2851 schoenebeck 809 Dimensions++;
2852    
2853     // if this is a layer dimension, update 'Layers' attribute
2854     if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2855    
2856 persson 858 UpdateVelocityTable();
2857 schoenebeck 809 }
2858    
2859     /** @brief Delete an existing dimension.
2860     *
2861     * Deletes the dimension given by \a pDimDef and deletes all respective
2862     * dimension regions, that is all dimension regions where the dimension's
2863     * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2864     * for example this would delete all dimension regions for the case(s)
2865     * where the sustain pedal is pressed down.
2866     *
2867     * @param pDimDef - dimension to delete
2868     * @throws gig::Exception if given dimension cannot be found
2869     */
2870     void Region::DeleteDimension(dimension_def_t* pDimDef) {
2871     // get dimension's index
2872     int iDimensionNr = -1;
2873     for (int i = 0; i < Dimensions; i++) {
2874     if (&pDimensionDefinitions[i] == pDimDef) {
2875     iDimensionNr = i;
2876     break;
2877     }
2878     }
2879     if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2880    
2881     // get amount of bits below the dimension to delete
2882     int iLowerBits = 0;
2883     for (int i = 0; i < iDimensionNr; i++)
2884     iLowerBits += pDimensionDefinitions[i].bits;
2885    
2886     // get amount ot bits above the dimension to delete
2887     int iUpperBits = 0;
2888     for (int i = iDimensionNr + 1; i < Dimensions; i++)
2889     iUpperBits += pDimensionDefinitions[i].bits;
2890    
2891 persson 1247 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2892    
2893 schoenebeck 809 // delete dimension regions which belong to the given dimension
2894     // (that is where the dimension's bit > 0)
2895     for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2896     for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2897     for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2898     int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2899     iObsoleteBit << iLowerBits |
2900     iLowerBit;
2901 persson 1247
2902     _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2903 schoenebeck 809 delete pDimensionRegions[iToDelete];
2904     pDimensionRegions[iToDelete] = NULL;
2905     DimensionRegions--;
2906     }
2907     }
2908     }
2909    
2910     // defrag pDimensionRegions array
2911     // (that is remove the NULL spaces within the pDimensionRegions array)
2912     for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2913     if (!pDimensionRegions[iTo]) {
2914     if (iFrom <= iTo) iFrom = iTo + 1;
2915     while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2916     if (iFrom < 256 && pDimensionRegions[iFrom]) {
2917     pDimensionRegions[iTo] = pDimensionRegions[iFrom];
2918     pDimensionRegions[iFrom] = NULL;
2919     }
2920     }
2921     }
2922    
2923 persson 1247 // remove the this dimension from the upper limits arrays
2924     for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2925     DimensionRegion* d = pDimensionRegions[j];
2926     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2927     d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2928     }
2929     d->DimensionUpperLimits[Dimensions - 1] = 127;
2930     }
2931    
2932 schoenebeck 809 // 'remove' dimension definition
2933     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2934     pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2935     }
2936     pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2937     pDimensionDefinitions[Dimensions - 1].bits = 0;
2938     pDimensionDefinitions[Dimensions - 1].zones = 0;
2939    
2940     Dimensions--;
2941    
2942     // if this was a layer dimension, update 'Layers' attribute
2943     if (pDimDef->dimension == dimension_layer) Layers = 1;
2944     }
2945    
2946 schoenebeck 2 Region::~Region() {
2947 schoenebeck 350 for (int i = 0; i < 256; i++) {
2948 schoenebeck 2 if (pDimensionRegions[i]) delete pDimensionRegions[i];
2949     }
2950     }
2951    
2952     /**
2953     * Use this method in your audio engine to get the appropriate dimension
2954     * region with it's articulation data for the current situation. Just
2955     * call the method with the current MIDI controller values and you'll get
2956     * the DimensionRegion with the appropriate articulation data for the
2957     * current situation (for this Region of course only). To do that you'll
2958     * first have to look which dimensions with which controllers and in
2959     * which order are defined for this Region when you load the .gig file.
2960     * Special cases are e.g. layer or channel dimensions where you just put
2961     * in the index numbers instead of a MIDI controller value (means 0 for
2962     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
2963     * etc.).
2964     *
2965 schoenebeck 347 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
2966 schoenebeck 2 * @returns adress to the DimensionRegion for the given situation
2967     * @see pDimensionDefinitions
2968     * @see Dimensions
2969     */
2970 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2971 persson 858 uint8_t bits;
2972     int veldim = -1;
2973     int velbitpos;
2974     int bitpos = 0;
2975     int dimregidx = 0;
2976 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
2977 persson 858 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2978     // the velocity dimension must be handled after the other dimensions
2979     veldim = i;
2980     velbitpos = bitpos;
2981     } else {
2982     switch (pDimensionDefinitions[i].split_type) {
2983     case split_type_normal:
2984 persson 1070 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2985     // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2986     for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2987     if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2988     }
2989     } else {
2990     // gig2: evenly sized zones
2991     bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2992     }
2993 persson 858 break;
2994     case split_type_bit: // the value is already the sought dimension bit number
2995     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2996     bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2997     break;
2998     }
2999     dimregidx |= bits << bitpos;
3000 schoenebeck 2 }
3001 persson 858 bitpos += pDimensionDefinitions[i].bits;
3002 schoenebeck 2 }
3003 persson 858 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3004     if (veldim != -1) {
3005     // (dimreg is now the dimension region for the lowest velocity)
3006 persson 1070 if (dimreg->VelocityTable) // custom defined zone ranges
3007 persson 858 bits = dimreg->VelocityTable[DimValues[veldim]];
3008     else // normal split type
3009     bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
3010    
3011     dimregidx |= bits << velbitpos;
3012     dimreg = pDimensionRegions[dimregidx];
3013     }
3014     return dimreg;
3015 schoenebeck 2 }
3016    
3017     /**
3018     * Returns the appropriate DimensionRegion for the given dimension bit
3019     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
3020     * instead of calling this method directly!
3021     *
3022 schoenebeck 347 * @param DimBits Bit numbers for dimension 0 to 7
3023 schoenebeck 2 * @returns adress to the DimensionRegion for the given dimension
3024     * bit numbers
3025     * @see GetDimensionRegionByValue()
3026     */
3027 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
3028     return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3029     << pDimensionDefinitions[5].bits | DimBits[5])
3030     << pDimensionDefinitions[4].bits | DimBits[4])
3031     << pDimensionDefinitions[3].bits | DimBits[3])
3032     << pDimensionDefinitions[2].bits | DimBits[2])
3033     << pDimensionDefinitions[1].bits | DimBits[1])
3034     << pDimensionDefinitions[0].bits | DimBits[0]];
3035 schoenebeck 2 }
3036    
3037     /**
3038     * Returns pointer address to the Sample referenced with this region.
3039     * This is the global Sample for the entire Region (not sure if this is
3040     * actually used by the Gigasampler engine - I would only use the Sample
3041     * referenced by the appropriate DimensionRegion instead of this sample).
3042     *
3043     * @returns address to Sample or NULL if there is no reference to a
3044     * sample saved in the .gig file
3045     */
3046     Sample* Region::GetSample() {
3047     if (pSample) return static_cast<gig::Sample*>(pSample);
3048     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3049     }
3050    
3051 schoenebeck 515 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3052 schoenebeck 352 if ((int32_t)WavePoolTableIndex == -1) return NULL;
3053 schoenebeck 2 File* file = (File*) GetParent()->GetParent();
3054 persson 902 if (!file->pWavePoolTable) return NULL;
3055 schoenebeck 2 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3056 persson 666 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3057 schoenebeck 515 Sample* sample = file->GetFirstSample(pProgress);
3058 schoenebeck 2 while (sample) {
3059 persson 666 if (sample->ulWavePoolOffset == soughtoffset &&
3060 persson 918 sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3061 schoenebeck 2 sample = file->GetNextSample();
3062     }
3063     return NULL;
3064     }
3065 schoenebeck 2394
3066     /**
3067     * Make a (semi) deep copy of the Region object given by @a orig
3068     * and assign it to this object.
3069     *
3070     * Note that all sample pointers referenced by @a orig are simply copied as
3071     * memory address. Thus the respective samples are shared, not duplicated!
3072     *
3073     * @param orig - original Region object to be copied from
3074     */
3075     void Region::CopyAssign(const Region* orig) {
3076 schoenebeck 2482 CopyAssign(orig, NULL);
3077     }
3078    
3079     /**
3080     * Make a (semi) deep copy of the Region object given by @a orig and
3081     * assign it to this object
3082     *
3083     * @param mSamples - crosslink map between the foreign file's samples and
3084     * this file's samples
3085     */
3086     void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3087 schoenebeck 2394 // handle base classes
3088     DLS::Region::CopyAssign(orig);
3089    
3090 schoenebeck 2482 if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3091     pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3092     }
3093    
3094 schoenebeck 2394 // handle own member variables
3095     for (int i = Dimensions - 1; i >= 0; --i) {
3096     DeleteDimension(&pDimensionDefinitions[i]);
3097     }
3098     Layers = 0; // just to be sure
3099     for (int i = 0; i < orig->Dimensions; i++) {
3100     // we need to copy the dim definition here, to avoid the compiler
3101     // complaining about const-ness issue
3102     dimension_def_t def = orig->pDimensionDefinitions[i];
3103     AddDimension(&def);
3104     }
3105     for (int i = 0; i < 256; i++) {
3106     if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3107     pDimensionRegions[i]->CopyAssign(
3108 schoenebeck 2482 orig->pDimensionRegions[i],
3109     mSamples
3110 schoenebeck 2394 );
3111     }
3112     }
3113     Layers = orig->Layers;
3114     }
3115 schoenebeck 2
3116    
3117 persson 1627 // *************** MidiRule ***************
3118     // *
3119 schoenebeck 2
3120 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3121     _3ewg->SetPos(36);
3122     Triggers = _3ewg->ReadUint8();
3123     _3ewg->SetPos(40);
3124     ControllerNumber = _3ewg->ReadUint8();
3125     _3ewg->SetPos(46);
3126     for (int i = 0 ; i < Triggers ; i++) {
3127     pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3128     pTriggers[i].Descending = _3ewg->ReadUint8();
3129     pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3130     pTriggers[i].Key = _3ewg->ReadUint8();
3131     pTriggers[i].NoteOff = _3ewg->ReadUint8();
3132     pTriggers[i].Velocity = _3ewg->ReadUint8();
3133     pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3134     _3ewg->ReadUint8();
3135     }
3136 persson 1627 }
3137    
3138 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3139     ControllerNumber(0),
3140     Triggers(0) {
3141     }
3142 persson 1627
3143 persson 2450 void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3144     pData[32] = 4;
3145     pData[33] = 16;
3146     pData[36] = Triggers;
3147     pData[40] = ControllerNumber;
3148     for (int i = 0 ; i < Triggers ; i++) {
3149     pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3150     pData[47 + i * 8] = pTriggers[i].Descending;
3151     pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3152     pData[49 + i * 8] = pTriggers[i].Key;
3153     pData[50 + i * 8] = pTriggers[i].NoteOff;
3154     pData[51 + i * 8] = pTriggers[i].Velocity;
3155     pData[52 + i * 8] = pTriggers[i].OverridePedal;
3156     }
3157     }
3158    
3159     MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3160     _3ewg->SetPos(36);
3161     LegatoSamples = _3ewg->ReadUint8(); // always 12
3162     _3ewg->SetPos(40);
3163     BypassUseController = _3ewg->ReadUint8();
3164     BypassKey = _3ewg->ReadUint8();
3165     BypassController = _3ewg->ReadUint8();
3166     ThresholdTime = _3ewg->ReadUint16();
3167     _3ewg->ReadInt16();
3168     ReleaseTime = _3ewg->ReadUint16();
3169     _3ewg->ReadInt16();
3170     KeyRange.low = _3ewg->ReadUint8();
3171     KeyRange.high = _3ewg->ReadUint8();
3172     _3ewg->SetPos(64);
3173     ReleaseTriggerKey = _3ewg->ReadUint8();
3174     AltSustain1Key = _3ewg->ReadUint8();
3175     AltSustain2Key = _3ewg->ReadUint8();
3176     }
3177    
3178     MidiRuleLegato::MidiRuleLegato() :
3179     LegatoSamples(12),
3180     BypassUseController(false),
3181     BypassKey(0),
3182     BypassController(1),
3183     ThresholdTime(20),
3184     ReleaseTime(20),
3185     ReleaseTriggerKey(0),
3186     AltSustain1Key(0),
3187     AltSustain2Key(0)
3188     {
3189     KeyRange.low = KeyRange.high = 0;
3190     }
3191    
3192     void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3193     pData[32] = 0;
3194     pData[33] = 16;
3195     pData[36] = LegatoSamples;
3196     pData[40] = BypassUseController;
3197     pData[41] = BypassKey;
3198     pData[42] = BypassController;
3199     store16(&pData[43], ThresholdTime);
3200     store16(&pData[47], ReleaseTime);
3201     pData[51] = KeyRange.low;
3202     pData[52] = KeyRange.high;
3203     pData[64] = ReleaseTriggerKey;
3204     pData[65] = AltSustain1Key;
3205     pData[66] = AltSustain2Key;
3206     }
3207    
3208     MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3209     _3ewg->SetPos(36);
3210     Articulations = _3ewg->ReadUint8();
3211     int flags = _3ewg->ReadUint8();
3212     Polyphonic = flags & 8;
3213     Chained = flags & 4;
3214     Selector = (flags & 2) ? selector_controller :
3215     (flags & 1) ? selector_key_switch : selector_none;
3216     Patterns = _3ewg->ReadUint8();
3217     _3ewg->ReadUint8(); // chosen row
3218     _3ewg->ReadUint8(); // unknown
3219     _3ewg->ReadUint8(); // unknown
3220     _3ewg->ReadUint8(); // unknown
3221     KeySwitchRange.low = _3ewg->ReadUint8();
3222     KeySwitchRange.high = _3ewg->ReadUint8();
3223     Controller = _3ewg->ReadUint8();
3224     PlayRange.low = _3ewg->ReadUint8();
3225     PlayRange.high = _3ewg->ReadUint8();
3226    
3227     int n = std::min(int(Articulations), 32);
3228     for (int i = 0 ; i < n ; i++) {
3229     _3ewg->ReadString(pArticulations[i], 32);
3230     }
3231     _3ewg->SetPos(1072);
3232     n = std::min(int(Patterns), 32);
3233     for (int i = 0 ; i < n ; i++) {
3234     _3ewg->ReadString(pPatterns[i].Name, 16);
3235     pPatterns[i].Size = _3ewg->ReadUint8();
3236     _3ewg->Read(&pPatterns[i][0], 1, 32);
3237     }
3238     }
3239    
3240     MidiRuleAlternator::MidiRuleAlternator() :
3241     Articulations(0),
3242     Patterns(0),
3243     Selector(selector_none),
3244     Controller(0),
3245     Polyphonic(false),
3246     Chained(false)
3247     {
3248     PlayRange.low = PlayRange.high = 0;
3249     KeySwitchRange.low = KeySwitchRange.high = 0;
3250     }
3251    
3252     void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3253     pData[32] = 3;
3254     pData[33] = 16;
3255     pData[36] = Articulations;
3256     pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3257     (Selector == selector_controller ? 2 :
3258     (Selector == selector_key_switch ? 1 : 0));
3259     pData[38] = Patterns;
3260    
3261     pData[43] = KeySwitchRange.low;
3262     pData[44] = KeySwitchRange.high;
3263     pData[45] = Controller;
3264     pData[46] = PlayRange.low;
3265     pData[47] = PlayRange.high;
3266    
3267     char* str = reinterpret_cast<char*>(pData);
3268     int pos = 48;
3269     int n = std::min(int(Articulations), 32);
3270     for (int i = 0 ; i < n ; i++, pos += 32) {
3271     strncpy(&str[pos], pArticulations[i].c_str(), 32);
3272     }
3273    
3274     pos = 1072;
3275     n = std::min(int(Patterns), 32);
3276     for (int i = 0 ; i < n ; i++, pos += 49) {
3277     strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3278     pData[pos + 16] = pPatterns[i].Size;
3279     memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3280     }
3281     }
3282    
3283 schoenebeck 2 // *************** Instrument ***************
3284     // *
3285    
3286 schoenebeck 515 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
3287 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
3288 persson 1180 { CHUNK_ID_INAM, 64 },
3289     { CHUNK_ID_ISFT, 12 },
3290     { 0, 0 }
3291     };
3292 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
3293 persson 918
3294 schoenebeck 2 // Initialization
3295     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3296 persson 1182 EffectSend = 0;
3297     Attenuation = 0;
3298     FineTune = 0;
3299     PitchbendRange = 0;
3300     PianoReleaseMode = false;
3301     DimensionKeyRange.low = 0;
3302     DimensionKeyRange.high = 0;
3303 persson 1678 pMidiRules = new MidiRule*[3];
3304     pMidiRules[0] = NULL;
3305 schoenebeck 2
3306     // Loading
3307     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
3308     if (lart) {
3309     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3310     if (_3ewg) {
3311     EffectSend = _3ewg->ReadUint16();
3312     Attenuation = _3ewg->ReadInt32();
3313     FineTune = _3ewg->ReadInt16();
3314     PitchbendRange = _3ewg->ReadInt16();
3315     uint8_t dimkeystart = _3ewg->ReadUint8();
3316     PianoReleaseMode = dimkeystart & 0x01;
3317     DimensionKeyRange.low = dimkeystart >> 1;
3318     DimensionKeyRange.high = _3ewg->ReadUint8();
3319 persson 1627
3320     if (_3ewg->GetSize() > 32) {
3321     // read MIDI rules
3322 persson 1678 int i = 0;
3323 persson 1627 _3ewg->SetPos(32);
3324     uint8_t id1 = _3ewg->ReadUint8();
3325     uint8_t id2 = _3ewg->ReadUint8();
3326    
3327 persson 2450 if (id2 == 16) {
3328     if (id1 == 4) {
3329     pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3330     } else if (id1 == 0) {
3331     pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3332     } else if (id1 == 3) {
3333     pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3334     } else {
3335     pMidiRules[i++] = new MidiRuleUnknown;
3336     }
3337 persson 1627 }
3338 persson 2450 else if (id1 != 0 || id2 != 0) {
3339     pMidiRules[i++] = new MidiRuleUnknown;
3340     }
3341 persson 1627 //TODO: all the other types of rules
3342 persson 1678
3343     pMidiRules[i] = NULL;
3344 persson 1627 }
3345 schoenebeck 2 }
3346     }
3347    
3348 schoenebeck 1524 if (pFile->GetAutoLoad()) {
3349     if (!pRegions) pRegions = new RegionList;
3350     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3351     if (lrgn) {
3352     RIFF::List* rgn = lrgn->GetFirstSubList();
3353     while (rgn) {
3354     if (rgn->GetListType() == LIST_TYPE_RGN) {
3355     __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3356     pRegions->push_back(new Region(this, rgn));
3357     }
3358     rgn = lrgn->GetNextSubList();
3359 schoenebeck 809 }
3360 schoenebeck 1524 // Creating Region Key Table for fast lookup
3361     UpdateRegionKeyTable();
3362 schoenebeck 2 }
3363     }
3364    
3365 schoenebeck 809 __notify_progress(pProgress, 1.0f); // notify done
3366     }
3367    
3368     void Instrument::UpdateRegionKeyTable() {
3369 schoenebeck 1335 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3370 schoenebeck 823 RegionList::iterator iter = pRegions->begin();
3371     RegionList::iterator end = pRegions->end();
3372     for (; iter != end; ++iter) {
3373     gig::Region* pRegion = static_cast<gig::Region*>(*iter);
3374     for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
3375     RegionKeyTable[iKey] = pRegion;
3376 schoenebeck 2 }
3377     }
3378     }
3379    
3380     Instrument::~Instrument() {
3381 persson 1950 for (int i = 0 ; pMidiRules[i] ; i++) {
3382     delete pMidiRules[i];
3383     }
3384 persson 1678 delete[] pMidiRules;
3385 schoenebeck 2 }
3386    
3387     /**
3388 schoenebeck 809 * Apply Instrument with all its Regions to the respective RIFF chunks.
3389     * You have to call File::Save() to make changes persistent.
3390     *
3391     * Usually there is absolutely no need to call this method explicitly.
3392     * It will be called automatically when File::Save() was called.
3393     *
3394     * @throws gig::Exception if samples cannot be dereferenced
3395     */
3396     void Instrument::UpdateChunks() {
3397     // first update base classes' chunks
3398     DLS::Instrument::UpdateChunks();
3399    
3400     // update Regions' chunks
3401 schoenebeck 823 {
3402     RegionList::iterator iter = pRegions->begin();
3403     RegionList::iterator end = pRegions->end();
3404     for (; iter != end; ++iter)
3405     (*iter)->UpdateChunks();
3406     }
3407 schoenebeck 809
3408     // make sure 'lart' RIFF list chunk exists
3409     RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
3410     if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3411     // make sure '3ewg' RIFF chunk exists
3412     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3413 persson 1264 if (!_3ewg) {
3414     File* pFile = (File*) GetParent();
3415    
3416     // 3ewg is bigger in gig3, as it includes the iMIDI rules
3417     int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3418     _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3419     memset(_3ewg->LoadChunkData(), 0, size);
3420     }
3421 schoenebeck 809 // update '3ewg' RIFF chunk
3422     uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3423 persson 1179 store16(&pData[0], EffectSend);
3424     store32(&pData[2], Attenuation);
3425     store16(&pData[6], FineTune);
3426     store16(&pData[8], PitchbendRange);
3427 persson 1266 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3428 schoenebeck 809 DimensionKeyRange.low << 1;
3429 persson 1179 pData[10] = dimkeystart;
3430     pData[11] = DimensionKeyRange.high;
3431 persson 2450
3432     if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3433     pData[32] = 0;
3434     pData[33] = 0;
3435     } else {
3436     for (int i = 0 ; pMidiRules[i] ; i++) {
3437     pMidiRules[i]->UpdateChunks(pData);
3438     }
3439     }
3440 schoenebeck 809 }
3441    
3442     /**
3443 schoenebeck 2 * Returns the appropriate Region for a triggered note.
3444     *
3445     * @param Key MIDI Key number of triggered note / key (0 - 127)
3446     * @returns pointer adress to the appropriate Region or NULL if there
3447     * there is no Region defined for the given \a Key
3448     */
3449     Region* Instrument::GetRegion(unsigned int Key) {
3450 schoenebeck 1335 if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3451 schoenebeck 2 return RegionKeyTable[Key];
3452 schoenebeck 823
3453 schoenebeck 2 /*for (int i = 0; i < Regions; i++) {
3454     if (Key <= pRegions[i]->KeyRange.high &&
3455     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
3456     }
3457     return NULL;*/
3458     }
3459    
3460     /**
3461     * Returns the first Region of the instrument. You have to call this
3462     * method once before you use GetNextRegion().
3463     *
3464     * @returns pointer address to first region or NULL if there is none
3465     * @see GetNextRegion()
3466     */
3467     Region* Instrument::GetFirstRegion() {
3468 schoenebeck 823 if (!pRegions) return NULL;
3469     RegionsIterator = pRegions->begin();
3470     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3471 schoenebeck 2 }
3472    
3473     /**
3474     * Returns the next Region of the instrument. You have to call
3475     * GetFirstRegion() once before you can use this method. By calling this
3476     * method multiple times it iterates through the available Regions.
3477     *
3478     * @returns pointer address to the next region or NULL if end reached
3479     * @see GetFirstRegion()
3480     */
3481     Region* Instrument::GetNextRegion() {
3482 schoenebeck 823 if (!pRegions) return NULL;
3483     RegionsIterator++;
3484     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3485 schoenebeck 2 }
3486    
3487 schoenebeck 809 Region* Instrument::AddRegion() {
3488     // create new Region object (and its RIFF chunks)
3489     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3490     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3491     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3492     Region* pNewRegion = new Region(this, rgn);
3493 schoenebeck 823 pRegions->push_back(pNewRegion);
3494     Regions = pRegions->size();
3495 schoenebeck 809 // update Region key table for fast lookup
3496     UpdateRegionKeyTable();
3497     // done
3498     return pNewRegion;
3499     }
3500 schoenebeck 2
3501 schoenebeck 809 void Instrument::DeleteRegion(Region* pRegion) {
3502     if (!pRegions) return;
3503 schoenebeck 823 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
3504 schoenebeck 809 // update Region key table for fast lookup
3505     UpdateRegionKeyTable();
3506     }
3507 schoenebeck 2
3508 persson 1627 /**
3509 persson 1678 * Returns a MIDI rule of the instrument.
3510 persson 1627 *
3511     * The list of MIDI rules, at least in gig v3, always contains at
3512     * most two rules. The second rule can only be the DEF filter
3513     * (which currently isn't supported by libgig).
3514     *
3515 persson 1678 * @param i - MIDI rule number
3516     * @returns pointer address to MIDI rule number i or NULL if there is none
3517 persson 1627 */
3518 persson 1678 MidiRule* Instrument::GetMidiRule(int i) {
3519     return pMidiRules[i];
3520 persson 1627 }
3521 persson 2450
3522 schoenebeck 2394 /**
3523 persson 2450 * Adds the "controller trigger" MIDI rule to the instrument.
3524     *
3525     * @returns the new MIDI rule
3526     */
3527     MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3528     delete pMidiRules[0];
3529     MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3530     pMidiRules[0] = r;
3531     pMidiRules[1] = 0;
3532     return r;
3533     }
3534    
3535     /**
3536     * Adds the legato MIDI rule to the instrument.
3537     *
3538     * @returns the new MIDI rule
3539     */
3540     MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3541     delete pMidiRules[0];
3542     MidiRuleLegato* r = new MidiRuleLegato;
3543     pMidiRules[0] = r;
3544     pMidiRules[1] = 0;
3545     return r;
3546     }
3547    
3548     /**
3549     * Adds the alternator MIDI rule to the instrument.
3550     *
3551     * @returns the new MIDI rule
3552     */
3553     MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3554     delete pMidiRules[0];
3555     MidiRuleAlternator* r = new MidiRuleAlternator;
3556     pMidiRules[0] = r;
3557     pMidiRules[1] = 0;
3558     return r;
3559     }
3560    
3561     /**
3562     * Deletes a MIDI rule from the instrument.
3563     *
3564     * @param i - MIDI rule number
3565     */
3566     void Instrument::DeleteMidiRule(int i) {
3567     delete pMidiRules[i];
3568     pMidiRules[i] = 0;
3569     }
3570    
3571     /**
3572 schoenebeck 2394 * Make a (semi) deep copy of the Instrument object given by @a orig
3573     * and assign it to this object.
3574     *
3575     * Note that all sample pointers referenced by @a orig are simply copied as
3576     * memory address. Thus the respective samples are shared, not duplicated!
3577     *
3578     * @param orig - original Instrument object to be copied from
3579     */
3580     void Instrument::CopyAssign(const Instrument* orig) {
3581 schoenebeck 2482 CopyAssign(orig, NULL);
3582     }
3583    
3584     /**
3585     * Make a (semi) deep copy of the Instrument object given by @a orig
3586     * and assign it to this object.
3587     *
3588     * @param orig - original Instrument object to be copied from
3589     * @param mSamples - crosslink map between the foreign file's samples and
3590     * this file's samples
3591     */
3592     void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3593 schoenebeck 2394 // handle base class
3594     // (without copying DLS region stuff)
3595     DLS::Instrument::CopyAssignCore(orig);
3596    
3597     // handle own member variables
3598     Attenuation = orig->Attenuation;
3599     EffectSend = orig->EffectSend;
3600     FineTune = orig->FineTune;
3601     PitchbendRange = orig->PitchbendRange;
3602     PianoReleaseMode = orig->PianoReleaseMode;
3603     DimensionKeyRange = orig->DimensionKeyRange;
3604    
3605     // free old midi rules
3606     for (int i = 0 ; pMidiRules[i] ; i++) {
3607     delete pMidiRules[i];
3608     }
3609     //TODO: MIDI rule copying
3610     pMidiRules[0] = NULL;
3611    
3612     // delete all old regions
3613     while (Regions) DeleteRegion(GetFirstRegion());
3614     // create new regions and copy them from original
3615     {
3616     RegionList::const_iterator it = orig->pRegions->begin();
3617     for (int i = 0; i < orig->Regions; ++i, ++it) {
3618     Region* dstRgn = AddRegion();
3619     //NOTE: Region does semi-deep copy !
3620     dstRgn->CopyAssign(
3621 schoenebeck 2482 static_cast<gig::Region*>(*it),
3622     mSamples
3623 schoenebeck 2394 );
3624     }
3625     }
3626 schoenebeck 809
3627 schoenebeck 2394 UpdateRegionKeyTable();
3628     }
3629 schoenebeck 809
3630 schoenebeck 2394
3631 schoenebeck 929 // *************** Group ***************
3632     // *
3633    
3634     /** @brief Constructor.
3635     *
3636 schoenebeck 930 * @param file - pointer to the gig::File object
3637     * @param ck3gnm - pointer to 3gnm chunk associated with this group or
3638     * NULL if this is a new Group
3639 schoenebeck 929 */
3640 schoenebeck 930 Group::Group(File* file, RIFF::Chunk* ck3gnm) {
3641 schoenebeck 929 pFile = file;
3642     pNameChunk = ck3gnm;
3643     ::LoadString(pNameChunk, Name);
3644     }
3645    
3646     Group::~Group() {
3647 schoenebeck 1099 // remove the chunk associated with this group (if any)
3648     if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3649 schoenebeck 929 }
3650    
3651     /** @brief Update chunks with current group settings.
3652     *
3653 schoenebeck 1098 * Apply current Group field values to the respective chunks. You have
3654     * to call File::Save() to make changes persistent.
3655     *
3656     * Usually there is absolutely no need to call this method explicitly.
3657     * It will be called automatically when File::Save() was called.
3658 schoenebeck 929 */
3659     void Group::UpdateChunks() {
3660     // make sure <3gri> and <3gnl> list chunks exist
3661 schoenebeck 930 RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3662 persson 1192 if (!_3gri) {
3663     _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3664     pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3665     }
3666 schoenebeck 929 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3667 persson 1182 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3668 persson 1266
3669     if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3670     // v3 has a fixed list of 128 strings, find a free one
3671     for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3672     if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3673     pNameChunk = ck;
3674     break;
3675     }
3676     }
3677     }
3678    
3679 schoenebeck 929 // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3680     ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3681     }
3682    
3683 schoenebeck 930 /**
3684     * Returns the first Sample of this Group. You have to call this method
3685     * once before you use GetNextSample().
3686     *
3687     * <b>Notice:</b> this method might block for a long time, in case the
3688     * samples of this .gig file were not scanned yet
3689     *
3690     * @returns pointer address to first Sample or NULL if there is none
3691     * applied to this Group
3692     * @see GetNextSample()
3693     */
3694     Sample* Group::GetFirstSample() {
3695     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3696     for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
3697     if (pSample->GetGroup() == this) return pSample;
3698     }
3699     return NULL;
3700     }
3701 schoenebeck 929
3702 schoenebeck 930 /**
3703     * Returns the next Sample of the Group. You have to call
3704     * GetFirstSample() once before you can use this method. By calling this
3705     * method multiple times it iterates through the Samples assigned to
3706     * this Group.
3707     *
3708     * @returns pointer address to the next Sample of this Group or NULL if
3709     * end reached
3710     * @see GetFirstSample()
3711     */
3712     Sample* Group::GetNextSample() {
3713     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3714     for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
3715     if (pSample->GetGroup() == this) return pSample;
3716     }
3717     return NULL;
3718     }
3719 schoenebeck 929
3720 schoenebeck 930 /**
3721     * Move Sample given by \a pSample from another Group to this Group.
3722     */
3723     void Group::AddSample(Sample* pSample) {
3724     pSample->pGroup = this;
3725     }
3726    
3727     /**
3728     * Move all members of this group to another group (preferably the 1st
3729     * one except this). This method is called explicitly by
3730     * File::DeleteGroup() thus when a Group was deleted. This code was
3731     * intentionally not placed in the destructor!
3732     */
3733     void Group::MoveAll() {
3734     // get "that" other group first
3735     Group* pOtherGroup = NULL;
3736     for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
3737     if (pOtherGroup != this) break;
3738     }
3739     if (!pOtherGroup) throw Exception(
3740     "Could not move samples to another group, since there is no "
3741     "other Group. This is a bug, report it!"
3742     );
3743     // now move all samples of this group to the other group
3744     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3745     pOtherGroup->AddSample(pSample);
3746     }
3747     }
3748    
3749    
3750    
3751 schoenebeck 2 // *************** File ***************
3752     // *
3753    
3754 schoenebeck 1384 /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3755 persson 1199 const DLS::version_t File::VERSION_2 = {
3756     0, 2, 19980628 & 0xffff, 19980628 >> 16
3757     };
3758    
3759 schoenebeck 1384 /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3760 persson 1199 const DLS::version_t File::VERSION_3 = {
3761     0, 3, 20030331 & 0xffff, 20030331 >> 16
3762     };
3763    
3764 schoenebeck 1416 static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3765 persson 1180 { CHUNK_ID_IARL, 256 },
3766     { CHUNK_ID_IART, 128 },
3767     { CHUNK_ID_ICMS, 128 },
3768     { CHUNK_ID_ICMT, 1024 },
3769     { CHUNK_ID_ICOP, 128 },
3770     { CHUNK_ID_ICRD, 128 },
3771     { CHUNK_ID_IENG, 128 },
3772     { CHUNK_ID_IGNR, 128 },
3773     { CHUNK_ID_IKEY, 128 },
3774     { CHUNK_ID_IMED, 128 },
3775     { CHUNK_ID_INAM, 128 },
3776     { CHUNK_ID_IPRD, 128 },
3777     { CHUNK_ID_ISBJ, 128 },
3778     { CHUNK_ID_ISFT, 128 },
3779     { CHUNK_ID_ISRC, 128 },
3780     { CHUNK_ID_ISRF, 128 },
3781     { CHUNK_ID_ITCH, 128 },
3782     { 0, 0 }
3783     };
3784    
3785 schoenebeck 809 File::File() : DLS::File() {
3786 schoenebeck 1524 bAutoLoad = true;
3787 persson 1264 *pVersion = VERSION_3;
3788 schoenebeck 929 pGroups = NULL;
3789 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3790 persson 1182 pInfo->ArchivalLocation = String(256, ' ');
3791 persson 1192
3792     // add some mandatory chunks to get the file chunks in right
3793     // order (INFO chunk will be moved to first position later)
3794     pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3795     pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3796 persson 1209 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3797    
3798     GenerateDLSID();
3799 schoenebeck 809 }
3800    
3801 schoenebeck 2 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3802 schoenebeck 1524 bAutoLoad = true;
3803 schoenebeck 929 pGroups = NULL;
3804 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3805 schoenebeck 2 }
3806    
3807 schoenebeck 929 File::~File() {
3808     if (pGroups) {
3809     std::list<Group*>::iterator iter = pGroups->begin();
3810     std::list<Group*>::iterator end = pGroups->end();
3811     while (iter != end) {
3812     delete *iter;
3813     ++iter;
3814     }
3815     delete pGroups;
3816     }
3817     }
3818    
3819 schoenebeck 515 Sample* File::GetFirstSample(progress_t* pProgress) {
3820     if (!pSamples) LoadSamples(pProgress);
3821 schoenebeck 2 if (!pSamples) return NULL;
3822     SamplesIterator = pSamples->begin();
3823     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3824     }
3825    
3826     Sample* File::GetNextSample() {
3827     if (!pSamples) return NULL;
3828     SamplesIterator++;
3829     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3830     }
3831 schoenebeck 2482
3832     /**
3833     * Returns Sample object of @a index.
3834     *
3835     * @returns sample object or NULL if index is out of bounds
3836     */
3837     Sample* File::GetSample(uint index) {
3838     if (!pSamples) LoadSamples();
3839     if (!pSamples) return NULL;
3840     DLS::File::SampleList::iterator it = pSamples->begin();
3841     for (int i = 0; i < index; ++i) {
3842     ++it;
3843     if (it == pSamples->end()) return NULL;
3844     }
3845     if (it == pSamples->end()) return NULL;
3846     return static_cast<gig::Sample*>( *it );
3847     }
3848 schoenebeck 2
3849 schoenebeck 809 /** @brief Add a new sample.
3850     *
3851     * This will create a new Sample object for the gig file. You have to
3852     * call Save() to make this persistent to the file.
3853     *
3854     * @returns pointer to new Sample object
3855     */
3856     Sample* File::AddSample() {
3857     if (!pSamples) LoadSamples();
3858     __ensureMandatoryChunksExist();
3859     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
3860     // create new Sample object and its respective 'wave' list chunk
3861     RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3862     Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
3863 persson 1192
3864     // add mandatory chunks to get the chunks in right order
3865     wave->AddSubChunk(CHUNK_ID_FMT, 16);
3866     wave->AddSubList(LIST_TYPE_INFO);
3867    
3868 schoenebeck 809 pSamples->push_back(pSample);
3869     return pSample;
3870     }
3871    
3872     /** @brief Delete a sample.
3873     *
3874 schoenebeck 1292 * This will delete the given Sample object from the gig file. Any
3875     * references to this sample from Regions and DimensionRegions will be
3876     * removed. You have to call Save() to make this persistent to the file.
3877 schoenebeck 809 *
3878     * @param pSample - sample to delete
3879     * @throws gig::Exception if given sample could not be found
3880     */
3881     void File::DeleteSample(Sample* pSample) {
3882 schoenebeck 823 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
3883     SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
3884 schoenebeck 809 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
3885 schoenebeck 1083 if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3886 schoenebeck 809 pSamples->erase(iter);
3887     delete pSample;
3888 persson 1266
3889 persson 1678 SampleList::iterator tmp = SamplesIterator;
3890 persson 1266 // remove all references to the sample
3891     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3892     instrument = GetNextInstrument()) {
3893     for (Region* region = instrument->GetFirstRegion() ; region ;
3894     region = instrument->GetNextRegion()) {
3895    
3896     if (region->GetSample() == pSample) region->SetSample(NULL);
3897    
3898     for (int i = 0 ; i < region->DimensionRegions ; i++) {
3899     gig::DimensionRegion *d = region->pDimensionRegions[i];
3900     if (d->pSample == pSample) d->pSample = NULL;
3901     }
3902     }
3903     }
3904 persson 1678 SamplesIterator = tmp; // restore iterator
3905 schoenebeck 809 }
3906    
3907 schoenebeck 823 void File::LoadSamples() {
3908     LoadSamples(NULL);
3909     }
3910    
3911 schoenebeck 515 void File::LoadSamples(progress_t* pProgress) {
3912 schoenebeck 930 // Groups must be loaded before samples, because samples will try
3913     // to resolve the group they belong to
3914 schoenebeck 1158 if (!pGroups) LoadGroups();
3915 schoenebeck 930
3916 schoenebeck 823 if (!pSamples) pSamples = new SampleList;
3917    
3918 persson 666 RIFF::File* file = pRIFF;
3919 schoenebeck 515
3920 persson 666 // just for progress calculation
3921     int iSampleIndex = 0;
3922     int iTotalSamples = WavePoolCount;
3923 schoenebeck 515
3924 persson 666 // check if samples should be loaded from extension files
3925     int lastFileNo = 0;
3926     for (int i = 0 ; i < WavePoolCount ; i++) {
3927     if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
3928     }
3929 schoenebeck 780 String name(pRIFF->GetFileName());
3930     int nameLen = name.length();
3931 persson 666 char suffix[6];
3932 schoenebeck 780 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
3933 schoenebeck 515
3934 persson 666 for (int fileNo = 0 ; ; ) {
3935     RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
3936     if (wvpl) {
3937     unsigned long wvplFileOffset = wvpl->GetFilePos();
3938     RIFF::List* wave = wvpl->GetFirstSubList();
3939     while (wave) {
3940     if (wave->GetListType() == LIST_TYPE_WAVE) {
3941     // notify current progress
3942     const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
3943     __notify_progress(pProgress, subprogress);
3944    
3945     unsigned long waveFileOffset = wave->GetFilePos();
3946     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
3947    
3948     iSampleIndex++;
3949     }
3950     wave = wvpl->GetNextSubList();
3951 schoenebeck 2 }
3952 persson 666
3953     if (fileNo == lastFileNo) break;
3954    
3955     // open extension file (*.gx01, *.gx02, ...)
3956     fileNo++;
3957     sprintf(suffix, ".gx%02d", fileNo);
3958     name.replace(nameLen, 5, suffix);
3959     file = new RIFF::File(name);
3960     ExtensionFiles.push_back(file);
3961 schoenebeck 823 } else break;
3962 schoenebeck 2 }
3963 persson 666
3964     __notify_progress(pProgress, 1.0); // notify done
3965 schoenebeck 2 }
3966    
3967     Instrument* File::GetFirstInstrument() {
3968     if (!pInstruments) LoadInstruments();
3969     if (!pInstruments) return NULL;
3970     InstrumentsIterator = pInstruments->begin();
3971 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3972 schoenebeck 2 }
3973    
3974     Instrument* File::GetNextInstrument() {
3975     if (!pInstruments) return NULL;
3976     InstrumentsIterator++;
3977 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3978 schoenebeck 2 }
3979    
3980 schoenebeck 21 /**
3981     * Returns the instrument with the given index.
3982     *
3983 schoenebeck 515 * @param index - number of the sought instrument (0..n)
3984     * @param pProgress - optional: callback function for progress notification
3985 schoenebeck 21 * @returns sought instrument or NULL if there's no such instrument
3986     */
3987 schoenebeck 515 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
3988     if (!pInstruments) {
3989     // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
3990    
3991     // sample loading subtask
3992     progress_t subprogress;
3993     __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
3994     __notify_progress(&subprogress, 0.0f);
3995 schoenebeck 1524 if (GetAutoLoad())
3996     GetFirstSample(&subprogress); // now force all samples to be loaded
3997 schoenebeck 515 __notify_progress(&subprogress, 1.0f);
3998    
3999     // instrument loading subtask
4000     if (pProgress && pProgress->callback) {
4001     subprogress.__range_min = subprogress.__range_max;
4002     subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
4003     }
4004     __notify_progress(&subprogress, 0.0f);
4005     LoadInstruments(&subprogress);
4006     __notify_progress(&subprogress, 1.0f);
4007     }
4008 schoenebeck 21 if (!pInstruments) return NULL;
4009     InstrumentsIterator = pInstruments->begin();
4010     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
4011 schoenebeck 823 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
4012 schoenebeck 21 InstrumentsIterator++;
4013     }
4014     return NULL;
4015     }
4016    
4017 schoenebeck 809 /** @brief Add a new instrument definition.
4018     *
4019     * This will create a new Instrument object for the gig file. You have
4020     * to call Save() to make this persistent to the file.
4021     *
4022     * @returns pointer to new Instrument object
4023     */
4024     Instrument* File::AddInstrument() {
4025     if (!pInstruments) LoadInstruments();
4026     __ensureMandatoryChunksExist();
4027     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4028     RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4029 persson 1192
4030     // add mandatory chunks to get the chunks in right order
4031     lstInstr->AddSubList(LIST_TYPE_INFO);
4032 persson 1209 lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4033 persson 1192
4034 schoenebeck 809 Instrument* pInstrument = new Instrument(this, lstInstr);
4035 persson 1209 pInstrument->GenerateDLSID();
4036 persson 1182
4037 persson 1192 lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4038    
4039 persson 1182 // this string is needed for the gig to be loadable in GSt:
4040     pInstrument->pInfo->Software = "Endless Wave";
4041    
4042 schoenebeck 809 pInstruments->push_back(pInstrument);
4043     return pInstrument;
4044     }
4045 schoenebeck 2394
4046     /** @brief Add a duplicate of an existing instrument.
4047     *
4048     * Duplicates the instrument definition given by @a orig and adds it
4049     * to this file. This allows in an instrument editor application to
4050     * easily create variations of an instrument, which will be stored in
4051     * the same .gig file, sharing i.e. the same samples.
4052     *
4053     * Note that all sample pointers referenced by @a orig are simply copied as
4054     * memory address. Thus the respective samples are shared, not duplicated!
4055     *
4056     * You have to call Save() to make this persistent to the file.
4057     *
4058     * @param orig - original instrument to be copied
4059     * @returns duplicated copy of the given instrument
4060     */
4061     Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4062     Instrument* instr = AddInstrument();
4063     instr->CopyAssign(orig);
4064     return instr;
4065     }
4066 schoenebeck 2482
4067     /** @brief Add content of another existing file.
4068     *
4069     * Duplicates the samples, groups and instruments of the original file
4070     * given by @a pFile and adds them to @c this File. In case @c this File is
4071     * a new one that you haven't saved before, then you have to call
4072     * SetFileName() before calling AddContentOf(), because this method will
4073     * automatically save this file during operation, which is required for
4074     * writing the sample waveform data by disk streaming.
4075     *
4076     * @param pFile - original file whose's content shall be copied from
4077     */
4078     void File::AddContentOf(File* pFile) {
4079     static int iCallCount = -1;
4080     iCallCount++;
4081     std::map<Group*,Group*> mGroups;
4082     std::map<Sample*,Sample*> mSamples;
4083    
4084     // clone sample groups
4085     for (int i = 0; pFile->GetGroup(i); ++i) {
4086     Group* g = AddGroup();
4087     g->Name =
4088     "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4089     mGroups[pFile->GetGroup(i)] = g;
4090     }
4091    
4092     // clone samples (not waveform data here yet)
4093     for (int i = 0; pFile->GetSample(i); ++i) {
4094     Sample* s = AddSample();
4095     s->CopyAssignMeta(pFile->GetSample(i));
4096     mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4097     mSamples[pFile->GetSample(i)] = s;
4098     }
4099    
4100     //BUG: For some reason this method only works with this additional
4101     // Save() call in between here.
4102     //
4103     // Important: The correct one of the 2 Save() methods has to be called
4104     // here, depending on whether the file is completely new or has been
4105     // saved to disk already, otherwise it will result in data corruption.
4106     if (pRIFF->IsNew())
4107     Save(GetFileName());
4108     else
4109     Save();
4110    
4111     // clone instruments
4112     // (passing the crosslink table here for the cloned samples)
4113     for (int i = 0; pFile->GetInstrument(i); ++i) {
4114     Instrument* instr = AddInstrument();
4115     instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4116     }
4117    
4118     // Mandatory: file needs to be saved to disk at this point, so this
4119     // file has the correct size and data layout for writing the samples'
4120     // waveform data to disk.
4121     Save();
4122    
4123     // clone samples' waveform data
4124     // (using direct read & write disk streaming)
4125     for (int i = 0; pFile->GetSample(i); ++i) {
4126     mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4127     }
4128     }
4129 schoenebeck 809
4130     /** @brief Delete an instrument.
4131     *
4132     * This will delete the given Instrument object from the gig file. You
4133     * have to call Save() to make this persistent to the file.
4134     *
4135     * @param pInstrument - instrument to delete
4136 schoenebeck 1081 * @throws gig::Exception if given instrument could not be found
4137 schoenebeck 809 */
4138     void File::DeleteInstrument(Instrument* pInstrument) {
4139     if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
4140 schoenebeck 823 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
4141 schoenebeck 809 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
4142     pInstruments->erase(iter);
4143     delete pInstrument;
4144     }
4145    
4146 schoenebeck 823 void File::LoadInstruments() {
4147     LoadInstruments(NULL);
4148     }
4149    
4150 schoenebeck 515 void File::LoadInstruments(progress_t* pProgress) {
4151 schoenebeck 823 if (!pInstruments) pInstruments = new InstrumentList;
4152 schoenebeck 2 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4153     if (lstInstruments) {
4154 schoenebeck 515 int iInstrumentIndex = 0;
4155 schoenebeck 2 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
4156     while (lstInstr) {
4157     if (lstInstr->GetListType() == LIST_TYPE_INS) {
4158 schoenebeck 515 // notify current progress
4159     const float localProgress = (float) iInstrumentIndex / (float) Instruments;
4160     __notify_progress(pProgress, localProgress);
4161    
4162     // divide local progress into subprogress for loading current Instrument
4163     progress_t subprogress;
4164     __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
4165    
4166     pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
4167    
4168     iInstrumentIndex++;
4169 schoenebeck 2 }
4170     lstInstr = lstInstruments->GetNextSubList();
4171     }
4172 schoenebeck 515 __notify_progress(pProgress, 1.0); // notify done
4173 schoenebeck 2 }
4174     }
4175    
4176 persson 1207 /// Updates the 3crc chunk with the checksum of a sample. The
4177     /// update is done directly to disk, as this method is called
4178     /// after File::Save()
4179 persson 1199 void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4180     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4181     if (!_3crc) return;
4182 persson 1207
4183     // get the index of the sample
4184 persson 1199 int iWaveIndex = -1;
4185     File::SampleList::iterator iter = pSamples->begin();
4186     File::SampleList::iterator end = pSamples->end();
4187     for (int index = 0; iter != end; ++iter, ++index) {
4188     if (*iter == pSample) {
4189     iWaveIndex = index;
4190     break;
4191     }
4192     }
4193     if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4194    
4195 persson 1207 // write the CRC-32 checksum to disk
4196 persson 1199 _3crc->SetPos(iWaveIndex * 8);
4197     uint32_t tmp = 1;
4198     _3crc->WriteUint32(&tmp); // unknown, always 1?
4199     _3crc->WriteUint32(&crc);
4200     }
4201    
4202 schoenebeck 929 Group* File::GetFirstGroup() {
4203     if (!pGroups) LoadGroups();
4204 schoenebeck 930 // there must always be at least one group
4205 schoenebeck 929 GroupsIterator = pGroups->begin();
4206 schoenebeck 930 return *GroupsIterator;
4207 schoenebeck 929 }
4208 schoenebeck 2
4209 schoenebeck 929 Group* File::GetNextGroup() {
4210     if (!pGroups) return NULL;
4211     ++GroupsIterator;
4212     return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
4213     }
4214 schoenebeck 2
4215 schoenebeck 929 /**
4216     * Returns the group with the given index.
4217     *
4218     * @param index - number of the sought group (0..n)
4219     * @returns sought group or NULL if there's no such group
4220     */
4221     Group* File::GetGroup(uint index) {
4222     if (!pGroups) LoadGroups();
4223     GroupsIterator = pGroups->begin();
4224     for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4225     if (i == index) return *GroupsIterator;
4226     ++GroupsIterator;
4227     }
4228     return NULL;
4229     }
4230    
4231     Group* File::AddGroup() {
4232     if (!pGroups) LoadGroups();
4233 schoenebeck 930 // there must always be at least one group
4234 schoenebeck 929 __ensureMandatoryChunksExist();
4235 schoenebeck 930 Group* pGroup = new Group(this, NULL);
4236 schoenebeck 929 pGroups->push_back(pGroup);
4237     return pGroup;
4238     }
4239    
4240 schoenebeck 1081 /** @brief Delete a group and its samples.
4241     *
4242     * This will delete the given Group object and all the samples that
4243     * belong to this group from the gig file. You have to call Save() to
4244     * make this persistent to the file.
4245     *
4246     * @param pGroup - group to delete
4247     * @throws gig::Exception if given group could not be found
4248     */
4249 schoenebeck 929 void File::DeleteGroup(Group* pGroup) {
4250 schoenebeck 930 if (!pGroups) LoadGroups();
4251 schoenebeck 929 std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4252     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4253 schoenebeck 930 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4254 schoenebeck 1081 // delete all members of this group
4255     for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
4256     DeleteSample(pSample);
4257     }
4258     // now delete this group object
4259     pGroups->erase(iter);
4260     delete pGroup;
4261     }
4262    
4263     /** @brief Delete a group.
4264     *
4265     * This will delete the given Group object from the gig file. All the
4266     * samples that belong to this group will not be deleted, but instead
4267     * be moved to another group. You have to call Save() to make this
4268     * persistent to the file.
4269     *
4270     * @param pGroup - group to delete
4271     * @throws gig::Exception if given group could not be found
4272     */
4273     void File::DeleteGroupOnly(Group* pGroup) {
4274     if (!pGroups) LoadGroups();
4275     std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4276     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4277     if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4278 schoenebeck 930 // move all members of this group to another group
4279     pGroup->MoveAll();
4280 schoenebeck 929 pGroups->erase(iter);
4281     delete pGroup;
4282     }
4283    
4284     void File::LoadGroups() {
4285     if (!pGroups) pGroups = new std::list<Group*>;
4286 schoenebeck 930 // try to read defined groups from file
4287 schoenebeck 929 RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4288 schoenebeck 930 if (lst3gri) {
4289     RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
4290     if (lst3gnl) {
4291     RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4292     while (ck) {
4293     if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4294 persson 1266 if (pVersion && pVersion->major == 3 &&
4295     strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4296    
4297 schoenebeck 930 pGroups->push_back(new Group(this, ck));
4298     }
4299     ck = lst3gnl->GetNextSubChunk();
4300 schoenebeck 929 }
4301     }
4302     }
4303 schoenebeck 930 // if there were no group(s), create at least the mandatory default group
4304     if (!pGroups->size()) {
4305     Group* pGroup = new Group(this, NULL);
4306     pGroup->Name = "Default Group";
4307     pGroups->push_back(pGroup);
4308     }
4309 schoenebeck 929 }
4310    
4311 schoenebeck 1098 /**
4312     * Apply all the gig file's current instruments, samples, groups and settings
4313     * to the respective RIFF chunks. You have to call Save() to make changes
4314     * persistent.
4315     *
4316     * Usually there is absolutely no need to call this method explicitly.
4317     * It will be called automatically when File::Save() was called.
4318     *
4319     * @throws Exception - on errors
4320     */
4321     void File::UpdateChunks() {
4322 persson 1199 bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4323 persson 1192
4324 persson 1247 b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4325    
4326 schoenebeck 1098 // first update base class's chunks
4327     DLS::File::UpdateChunks();
4328 schoenebeck 929
4329 persson 1199 if (newFile) {
4330 persson 1192 // INFO was added by Resource::UpdateChunks - make sure it
4331     // is placed first in file
4332 persson 1199 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4333 persson 1192 RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4334     if (first != info) {
4335     pRIFF->MoveSubChunk(info, first);
4336     }
4337     }
4338    
4339 schoenebeck 1098 // update group's chunks
4340     if (pGroups) {
4341 schoenebeck 2467 // make sure '3gri' and '3gnl' list chunks exist
4342     // (before updating the Group chunks)
4343     RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4344     if (!_3gri) {
4345     _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4346     pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4347 schoenebeck 1098 }
4348 schoenebeck 2467 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4349     if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4350 persson 1266
4351     // v3: make sure the file has 128 3gnm chunks
4352 schoenebeck 2467 // (before updating the Group chunks)
4353 persson 1266 if (pVersion && pVersion->major == 3) {
4354     RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4355     for (int i = 0 ; i < 128 ; i++) {
4356     if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4357     if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4358     }
4359     }
4360 schoenebeck 2467
4361     std::list<Group*>::iterator iter = pGroups->begin();
4362     std::list<Group*>::iterator end = pGroups->end();
4363     for (; iter != end; ++iter) {
4364     (*iter)->UpdateChunks();
4365     }
4366 schoenebeck 1098 }
4367 persson 1199
4368     // update einf chunk
4369    
4370     // The einf chunk contains statistics about the gig file, such
4371     // as the number of regions and samples used by each
4372     // instrument. It is divided in equally sized parts, where the
4373     // first part contains information about the whole gig file,
4374     // and the rest of the parts map to each instrument in the
4375     // file.
4376     //
4377     // At the end of each part there is a bit map of each sample
4378     // in the file, where a set bit means that the sample is used
4379     // by the file/instrument.
4380     //
4381     // Note that there are several fields with unknown use. These
4382     // are set to zero.
4383    
4384     int sublen = pSamples->size() / 8 + 49;
4385     int einfSize = (Instruments + 1) * sublen;
4386    
4387     RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4388     if (einf) {
4389     if (einf->GetSize() != einfSize) {
4390     einf->Resize(einfSize);
4391     memset(einf->LoadChunkData(), 0, einfSize);
4392     }
4393     } else if (newFile) {
4394     einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4395     }
4396     if (einf) {
4397     uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4398    
4399     std::map<gig::Sample*,int> sampleMap;
4400     int sampleIdx = 0;
4401     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4402     sampleMap[pSample] = sampleIdx++;
4403     }
4404    
4405     int totnbusedsamples = 0;
4406     int totnbusedchannels = 0;
4407     int totnbregions = 0;
4408     int totnbdimregions = 0;
4409 persson 1264 int totnbloops = 0;
4410 persson 1199 int instrumentIdx = 0;
4411    
4412     memset(&pData[48], 0, sublen - 48);
4413    
4414     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4415     instrument = GetNextInstrument()) {
4416     int nbusedsamples = 0;
4417     int nbusedchannels = 0;
4418     int nbdimregions = 0;
4419 persson 1264 int nbloops = 0;
4420 persson 1199
4421     memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4422    
4423     for (Region* region = instrument->GetFirstRegion() ; region ;
4424     region = instrument->GetNextRegion()) {
4425     for (int i = 0 ; i < region->DimensionRegions ; i++) {
4426     gig::DimensionRegion *d = region->pDimensionRegions[i];
4427     if (d->pSample) {
4428     int sampleIdx = sampleMap[d->pSample];
4429     int byte = 48 + sampleIdx / 8;
4430     int bit = 1 << (sampleIdx & 7);
4431     if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4432     pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4433     nbusedsamples++;
4434     nbusedchannels += d->pSample->Channels;
4435    
4436     if ((pData[byte] & bit) == 0) {
4437     pData[byte] |= bit;
4438     totnbusedsamples++;
4439     totnbusedchannels += d->pSample->Channels;
4440     }
4441     }
4442     }
4443 persson 1264 if (d->SampleLoops) nbloops++;
4444 persson 1199 }
4445     nbdimregions += region->DimensionRegions;
4446     }
4447     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4448     // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4449     store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4450     store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4451     store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4452     store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4453     store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4454 persson 1264 store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4455     // next 8 bytes unknown
4456 persson 1199 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4457     store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4458     // next 4 bytes unknown
4459    
4460     totnbregions += instrument->Regions;
4461     totnbdimregions += nbdimregions;
4462 persson 1264 totnbloops += nbloops;
4463 persson 1199 instrumentIdx++;
4464     }
4465     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4466     // store32(&pData[0], sublen);
4467     store32(&pData[4], totnbusedchannels);
4468     store32(&pData[8], totnbusedsamples);
4469     store32(&pData[12], Instruments);
4470     store32(&pData[16], totnbregions);
4471     store32(&pData[20], totnbdimregions);
4472 persson 1264 store32(&pData[24], totnbloops);
4473     // next 8 bytes unknown
4474     // next 4 bytes unknown, not always 0
4475 persson 1199 store32(&pData[40], pSamples->size());
4476     // next 4 bytes unknown
4477     }
4478    
4479     // update 3crc chunk
4480    
4481     // The 3crc chunk contains CRC-32 checksums for the
4482     // samples. The actual checksum values will be filled in
4483     // later, by Sample::Write.
4484    
4485     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4486     if (_3crc) {
4487     _3crc->Resize(pSamples->size() * 8);
4488     } else if (newFile) {
4489     _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4490     _3crc->LoadChunkData();
4491 persson 1264
4492     // the order of einf and 3crc is not the same in v2 and v3
4493     if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4494 persson 1199 }
4495 schoenebeck 1098 }
4496 schoenebeck 929
4497 schoenebeck 1524 /**
4498     * Enable / disable automatic loading. By default this properyt is
4499     * enabled and all informations are loaded automatically. However
4500     * loading all Regions, DimensionRegions and especially samples might
4501     * take a long time for large .gig files, and sometimes one might only
4502     * be interested in retrieving very superficial informations like the
4503     * amount of instruments and their names. In this case one might disable
4504     * automatic loading to avoid very slow response times.
4505     *
4506     * @e CAUTION: by disabling this property many pointers (i.e. sample
4507     * references) and informations will have invalid or even undefined
4508     * data! This feature is currently only intended for retrieving very
4509     * superficial informations in a very fast way. Don't use it to retrieve
4510     * details like synthesis informations or even to modify .gig files!
4511     */
4512     void File::SetAutoLoad(bool b) {
4513     bAutoLoad = b;
4514     }
4515 schoenebeck 1098
4516 schoenebeck 1524 /**
4517     * Returns whether automatic loading is enabled.
4518     * @see SetAutoLoad()
4519     */
4520     bool File::GetAutoLoad() {
4521     return bAutoLoad;
4522     }
4523 schoenebeck 1098
4524 schoenebeck 1524
4525    
4526 schoenebeck 2 // *************** Exception ***************
4527     // *
4528    
4529     Exception::Exception(String Message) : DLS::Exception(Message) {
4530     }
4531    
4532     void Exception::PrintMessage() {
4533     std::cout << "gig::Exception: " << Message << std::endl;
4534     }
4535    
4536 schoenebeck 518
4537     // *************** functions ***************
4538     // *
4539    
4540     /**
4541     * Returns the name of this C++ library. This is usually "libgig" of
4542     * course. This call is equivalent to RIFF::libraryName() and
4543     * DLS::libraryName().
4544     */
4545     String libraryName() {
4546     return PACKAGE;
4547     }
4548    
4549     /**
4550     * Returns version of this C++ library. This call is equivalent to
4551     * RIFF::libraryVersion() and DLS::libraryVersion().
4552     */
4553     String libraryVersion() {
4554     return VERSION;
4555     }
4556    
4557 schoenebeck 2 } // namespace gig

  ViewVC Help
Powered by ViewVC