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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2547 - (hide annotations) (download)
Tue May 13 11:17:24 2014 UTC (9 years, 10 months ago) by schoenebeck
File size: 218005 byte(s)
* Fix: don't alter region pointer in gig::DimensionRegion::CopyAssign()
  (caused crash with the new "combine instruments" feature in gigedit).
* Added new method gig::Region::GetDimensionDefinition(dimension_t type).
* Added some more sanity checks in gig::Region::AddDimension().
* Added inline helper methods overlaps() for struct DLS::range_t.
* Added more API doc comments.
* Bumped version (3.3.0.svn10).


1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2540 * Copyright (C) 2003-2014 by Christian Schoenebeck *
6 schoenebeck 384 * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8     * This library is free software; you can redistribute it and/or modify *
9     * it under the terms of the GNU General Public License as published by *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This library is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this library; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include "gig.h"
25    
26 schoenebeck 809 #include "helper.h"
27    
28 persson 1713 #include <algorithm>
29 schoenebeck 809 #include <math.h>
30 schoenebeck 384 #include <iostream>
31    
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 schoenebeck 2547
1712     // restore members that shall not be altered
1713 schoenebeck 2394 pParentList = p; // restore the chunk pointer
1714 schoenebeck 2547 pRegion = pOriginalRegion;
1715 schoenebeck 2482
1716 schoenebeck 2547 // only take the raw sample reference reference if the
1717 schoenebeck 2482 // two DimensionRegion objects are part of the same file
1718     if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1719     pSample = pOriginalSample;
1720     }
1721    
1722     if (mSamples && mSamples->count(orig->pSample)) {
1723     pSample = mSamples->find(orig->pSample)->second;
1724     }
1725 persson 1301
1726 schoenebeck 2394 // deep copy of owned structures
1727     if (orig->VelocityTable) {
1728     VelocityTable = new uint8_t[128];
1729     for (int k = 0 ; k < 128 ; k++)
1730     VelocityTable[k] = orig->VelocityTable[k];
1731     }
1732     if (orig->pSampleLoops) {
1733     pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1734     for (int k = 0 ; k < orig->SampleLoops ; k++)
1735     pSampleLoops[k] = orig->pSampleLoops[k];
1736     }
1737     }
1738    
1739 schoenebeck 809 /**
1740 schoenebeck 1358 * Updates the respective member variable and updates @c SampleAttenuation
1741     * which depends on this value.
1742     */
1743     void DimensionRegion::SetGain(int32_t gain) {
1744     DLS::Sampler::SetGain(gain);
1745     SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1746     }
1747    
1748     /**
1749 schoenebeck 809 * Apply dimension region settings to the respective RIFF chunks. You
1750     * have to call File::Save() to make changes persistent.
1751     *
1752     * Usually there is absolutely no need to call this method explicitly.
1753     * It will be called automatically when File::Save() was called.
1754     */
1755     void DimensionRegion::UpdateChunks() {
1756     // first update base class's chunk
1757     DLS::Sampler::UpdateChunks();
1758    
1759 persson 1247 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1760     uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1761     pData[12] = Crossfade.in_start;
1762     pData[13] = Crossfade.in_end;
1763     pData[14] = Crossfade.out_start;
1764     pData[15] = Crossfade.out_end;
1765    
1766 schoenebeck 809 // make sure '3ewa' chunk exists
1767     RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1768 persson 1317 if (!_3ewa) {
1769     File* pFile = (File*) GetParent()->GetParent()->GetParent();
1770     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1771     _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1772 persson 1264 }
1773 persson 1247 pData = (uint8_t*) _3ewa->LoadChunkData();
1774 schoenebeck 809
1775     // update '3ewa' chunk with DimensionRegion's current settings
1776    
1777 persson 1182 const uint32_t chunksize = _3ewa->GetNewSize();
1778 persson 1179 store32(&pData[0], chunksize); // unknown, always chunk size?
1779 schoenebeck 809
1780     const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1781 persson 1179 store32(&pData[4], lfo3freq);
1782 schoenebeck 809
1783     const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1784 persson 1179 store32(&pData[8], eg3attack);
1785 schoenebeck 809
1786     // next 2 bytes unknown
1787    
1788 persson 1179 store16(&pData[14], LFO1InternalDepth);
1789 schoenebeck 809
1790     // next 2 bytes unknown
1791    
1792 persson 1179 store16(&pData[18], LFO3InternalDepth);
1793 schoenebeck 809
1794     // next 2 bytes unknown
1795    
1796 persson 1179 store16(&pData[22], LFO1ControlDepth);
1797 schoenebeck 809
1798     // next 2 bytes unknown
1799    
1800 persson 1179 store16(&pData[26], LFO3ControlDepth);
1801 schoenebeck 809
1802     const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1803 persson 1179 store32(&pData[28], eg1attack);
1804 schoenebeck 809
1805     const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1806 persson 1179 store32(&pData[32], eg1decay1);
1807 schoenebeck 809
1808     // next 2 bytes unknown
1809    
1810 persson 1179 store16(&pData[38], EG1Sustain);
1811 schoenebeck 809
1812     const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1813 persson 1179 store32(&pData[40], eg1release);
1814 schoenebeck 809
1815     const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1816 persson 1179 pData[44] = eg1ctl;
1817 schoenebeck 809
1818     const uint8_t eg1ctrloptions =
1819 persson 1266 (EG1ControllerInvert ? 0x01 : 0x00) |
1820 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1821     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1822     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1823 persson 1179 pData[45] = eg1ctrloptions;
1824 schoenebeck 809
1825     const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1826 persson 1179 pData[46] = eg2ctl;
1827 schoenebeck 809
1828     const uint8_t eg2ctrloptions =
1829 persson 1266 (EG2ControllerInvert ? 0x01 : 0x00) |
1830 schoenebeck 809 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1831     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1832     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1833 persson 1179 pData[47] = eg2ctrloptions;
1834 schoenebeck 809
1835     const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1836 persson 1179 store32(&pData[48], lfo1freq);
1837 schoenebeck 809
1838     const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1839 persson 1179 store32(&pData[52], eg2attack);
1840 schoenebeck 809
1841     const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1842 persson 1179 store32(&pData[56], eg2decay1);
1843 schoenebeck 809
1844     // next 2 bytes unknown
1845    
1846 persson 1179 store16(&pData[62], EG2Sustain);
1847 schoenebeck 809
1848     const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1849 persson 1179 store32(&pData[64], eg2release);
1850 schoenebeck 809
1851     // next 2 bytes unknown
1852    
1853 persson 1179 store16(&pData[70], LFO2ControlDepth);
1854 schoenebeck 809
1855     const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1856 persson 1179 store32(&pData[72], lfo2freq);
1857 schoenebeck 809
1858     // next 2 bytes unknown
1859    
1860 persson 1179 store16(&pData[78], LFO2InternalDepth);
1861 schoenebeck 809
1862     const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1863 persson 1179 store32(&pData[80], eg1decay2);
1864 schoenebeck 809
1865     // next 2 bytes unknown
1866    
1867 persson 1179 store16(&pData[86], EG1PreAttack);
1868 schoenebeck 809
1869     const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1870 persson 1179 store32(&pData[88], eg2decay2);
1871 schoenebeck 809
1872     // next 2 bytes unknown
1873    
1874 persson 1179 store16(&pData[94], EG2PreAttack);
1875 schoenebeck 809
1876     {
1877     if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1878     uint8_t velocityresponse = VelocityResponseDepth;
1879     switch (VelocityResponseCurve) {
1880     case curve_type_nonlinear:
1881     break;
1882     case curve_type_linear:
1883     velocityresponse += 5;
1884     break;
1885     case curve_type_special:
1886     velocityresponse += 10;
1887     break;
1888     case curve_type_unknown:
1889     default:
1890     throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1891     }
1892 persson 1179 pData[96] = velocityresponse;
1893 schoenebeck 809 }
1894    
1895     {
1896     if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1897     uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1898     switch (ReleaseVelocityResponseCurve) {
1899     case curve_type_nonlinear:
1900     break;
1901     case curve_type_linear:
1902     releasevelocityresponse += 5;
1903     break;
1904     case curve_type_special:
1905     releasevelocityresponse += 10;
1906     break;
1907     case curve_type_unknown:
1908     default:
1909     throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1910     }
1911 persson 1179 pData[97] = releasevelocityresponse;
1912 schoenebeck 809 }
1913    
1914 persson 1179 pData[98] = VelocityResponseCurveScaling;
1915 schoenebeck 809
1916 persson 1179 pData[99] = AttenuationControllerThreshold;
1917 schoenebeck 809
1918     // next 4 bytes unknown
1919    
1920 persson 1179 store16(&pData[104], SampleStartOffset);
1921 schoenebeck 809
1922     // next 2 bytes unknown
1923    
1924     {
1925     uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1926     switch (DimensionBypass) {
1927     case dim_bypass_ctrl_94:
1928     pitchTrackDimensionBypass |= 0x10;
1929     break;
1930     case dim_bypass_ctrl_95:
1931     pitchTrackDimensionBypass |= 0x20;
1932     break;
1933     case dim_bypass_ctrl_none:
1934     //FIXME: should we set anything here?
1935     break;
1936     default:
1937     throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1938     }
1939 persson 1179 pData[108] = pitchTrackDimensionBypass;
1940 schoenebeck 809 }
1941    
1942     const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1943 persson 1179 pData[109] = pan;
1944 schoenebeck 809
1945     const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1946 persson 1179 pData[110] = selfmask;
1947 schoenebeck 809
1948     // next byte unknown
1949    
1950     {
1951     uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1952     if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1953     if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1954     if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1955 persson 1179 pData[112] = lfo3ctrl;
1956 schoenebeck 809 }
1957    
1958     const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1959 persson 1179 pData[113] = attenctl;
1960 schoenebeck 809
1961     {
1962     uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1963     if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1964     if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1965     if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1966 persson 1179 pData[114] = lfo2ctrl;
1967 schoenebeck 809 }
1968    
1969     {
1970     uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1971     if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1972     if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1973     if (VCFResonanceController != vcf_res_ctrl_none)
1974     lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1975 persson 1179 pData[115] = lfo1ctrl;
1976 schoenebeck 809 }
1977    
1978     const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1979 persson 2402 : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1980 persson 1869 store16(&pData[116], eg3depth);
1981 schoenebeck 809
1982     // next 2 bytes unknown
1983    
1984     const uint8_t channeloffset = ChannelOffset * 4;
1985 persson 1179 pData[120] = channeloffset;
1986 schoenebeck 809
1987     {
1988     uint8_t regoptions = 0;
1989     if (MSDecode) regoptions |= 0x01; // bit 0
1990     if (SustainDefeat) regoptions |= 0x02; // bit 1
1991 persson 1179 pData[121] = regoptions;
1992 schoenebeck 809 }
1993    
1994     // next 2 bytes unknown
1995    
1996 persson 1179 pData[124] = VelocityUpperLimit;
1997 schoenebeck 809
1998     // next 3 bytes unknown
1999    
2000 persson 1179 pData[128] = ReleaseTriggerDecay;
2001 schoenebeck 809
2002     // next 2 bytes unknown
2003    
2004     const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2005 persson 1179 pData[131] = eg1hold;
2006 schoenebeck 809
2007 persson 1266 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2008 persson 918 (VCFCutoff & 0x7f); /* lower 7 bits */
2009 persson 1179 pData[132] = vcfcutoff;
2010 schoenebeck 809
2011 persson 1179 pData[133] = VCFCutoffController;
2012 schoenebeck 809
2013 persson 1266 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2014 persson 918 (VCFVelocityScale & 0x7f); /* lower 7 bits */
2015 persson 1179 pData[134] = vcfvelscale;
2016 schoenebeck 809
2017     // next byte unknown
2018    
2019 persson 1266 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2020 persson 918 (VCFResonance & 0x7f); /* lower 7 bits */
2021 persson 1179 pData[136] = vcfresonance;
2022 schoenebeck 809
2023 persson 1266 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2024 persson 918 (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2025 persson 1179 pData[137] = vcfbreakpoint;
2026 schoenebeck 809
2027 persson 2152 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2028 schoenebeck 809 VCFVelocityCurve * 5;
2029 persson 1179 pData[138] = vcfvelocity;
2030 schoenebeck 809
2031     const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2032 persson 1179 pData[139] = vcftype;
2033 persson 1070
2034     if (chunksize >= 148) {
2035     memcpy(&pData[140], DimensionUpperLimits, 8);
2036     }
2037 schoenebeck 809 }
2038    
2039 schoenebeck 1358 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2040     curve_type_t curveType = releaseVelocityResponseCurve;
2041     uint8_t depth = releaseVelocityResponseDepth;
2042     // this models a strange behaviour or bug in GSt: two of the
2043     // velocity response curves for release time are not used even
2044     // if specified, instead another curve is chosen.
2045     if ((curveType == curve_type_nonlinear && depth == 0) ||
2046     (curveType == curve_type_special && depth == 4)) {
2047     curveType = curve_type_nonlinear;
2048     depth = 3;
2049     }
2050     return GetVelocityTable(curveType, depth, 0);
2051     }
2052    
2053     double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2054     uint8_t vcfVelocityDynamicRange,
2055     uint8_t vcfVelocityScale,
2056     vcf_cutoff_ctrl_t vcfCutoffController)
2057     {
2058     curve_type_t curveType = vcfVelocityCurve;
2059     uint8_t depth = vcfVelocityDynamicRange;
2060     // even stranger GSt: two of the velocity response curves for
2061     // filter cutoff are not used, instead another special curve
2062     // is chosen. This curve is not used anywhere else.
2063     if ((curveType == curve_type_nonlinear && depth == 0) ||
2064     (curveType == curve_type_special && depth == 4)) {
2065     curveType = curve_type_special;
2066     depth = 5;
2067     }
2068     return GetVelocityTable(curveType, depth,
2069     (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2070     ? vcfVelocityScale : 0);
2071     }
2072    
2073 persson 613 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2074     double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2075     {
2076     double* table;
2077     uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2078 schoenebeck 16 if (pVelocityTables->count(tableKey)) { // if key exists
2079 persson 613 table = (*pVelocityTables)[tableKey];
2080 schoenebeck 16 }
2081     else {
2082 persson 613 table = CreateVelocityTable(curveType, depth, scaling);
2083     (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2084 schoenebeck 16 }
2085 persson 613 return table;
2086 schoenebeck 2 }
2087 schoenebeck 55
2088 schoenebeck 1316 Region* DimensionRegion::GetParent() const {
2089     return pRegion;
2090     }
2091    
2092 schoenebeck 2540 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2093     // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2094     // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2095     //#pragma GCC diagnostic push
2096     //#pragma GCC diagnostic error "-Wswitch"
2097    
2098 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2099     leverage_ctrl_t decodedcontroller;
2100     switch (EncodedController) {
2101     // special controller
2102     case _lev_ctrl_none:
2103     decodedcontroller.type = leverage_ctrl_t::type_none;
2104     decodedcontroller.controller_number = 0;
2105     break;
2106     case _lev_ctrl_velocity:
2107     decodedcontroller.type = leverage_ctrl_t::type_velocity;
2108     decodedcontroller.controller_number = 0;
2109     break;
2110     case _lev_ctrl_channelaftertouch:
2111     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2112     decodedcontroller.controller_number = 0;
2113     break;
2114 schoenebeck 55
2115 schoenebeck 36 // ordinary MIDI control change controller
2116     case _lev_ctrl_modwheel:
2117     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2118     decodedcontroller.controller_number = 1;
2119     break;
2120     case _lev_ctrl_breath:
2121     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2122     decodedcontroller.controller_number = 2;
2123     break;
2124     case _lev_ctrl_foot:
2125     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2126     decodedcontroller.controller_number = 4;
2127     break;
2128     case _lev_ctrl_effect1:
2129     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2130     decodedcontroller.controller_number = 12;
2131     break;
2132     case _lev_ctrl_effect2:
2133     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2134     decodedcontroller.controller_number = 13;
2135     break;
2136     case _lev_ctrl_genpurpose1:
2137     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2138     decodedcontroller.controller_number = 16;
2139     break;
2140     case _lev_ctrl_genpurpose2:
2141     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2142     decodedcontroller.controller_number = 17;
2143     break;
2144     case _lev_ctrl_genpurpose3:
2145     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2146     decodedcontroller.controller_number = 18;
2147     break;
2148     case _lev_ctrl_genpurpose4:
2149     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2150     decodedcontroller.controller_number = 19;
2151     break;
2152     case _lev_ctrl_portamentotime:
2153     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2154     decodedcontroller.controller_number = 5;
2155     break;
2156     case _lev_ctrl_sustainpedal:
2157     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2158     decodedcontroller.controller_number = 64;
2159     break;
2160     case _lev_ctrl_portamento:
2161     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2162     decodedcontroller.controller_number = 65;
2163     break;
2164     case _lev_ctrl_sostenutopedal:
2165     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2166     decodedcontroller.controller_number = 66;
2167     break;
2168     case _lev_ctrl_softpedal:
2169     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2170     decodedcontroller.controller_number = 67;
2171     break;
2172     case _lev_ctrl_genpurpose5:
2173     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2174     decodedcontroller.controller_number = 80;
2175     break;
2176     case _lev_ctrl_genpurpose6:
2177     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178     decodedcontroller.controller_number = 81;
2179     break;
2180     case _lev_ctrl_genpurpose7:
2181     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2182     decodedcontroller.controller_number = 82;
2183     break;
2184     case _lev_ctrl_genpurpose8:
2185     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186     decodedcontroller.controller_number = 83;
2187     break;
2188     case _lev_ctrl_effect1depth:
2189     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190     decodedcontroller.controller_number = 91;
2191     break;
2192     case _lev_ctrl_effect2depth:
2193     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194     decodedcontroller.controller_number = 92;
2195     break;
2196     case _lev_ctrl_effect3depth:
2197     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198     decodedcontroller.controller_number = 93;
2199     break;
2200     case _lev_ctrl_effect4depth:
2201     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202     decodedcontroller.controller_number = 94;
2203     break;
2204     case _lev_ctrl_effect5depth:
2205     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206     decodedcontroller.controller_number = 95;
2207     break;
2208 schoenebeck 55
2209 schoenebeck 2540 // format extension (these controllers are so far only supported by
2210     // LinuxSampler & gigedit) they will *NOT* work with
2211     // Gigasampler/GigaStudio !
2212     case _lev_ctrl_CC3_EXT:
2213     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214     decodedcontroller.controller_number = 3;
2215     break;
2216     case _lev_ctrl_CC6_EXT:
2217     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218     decodedcontroller.controller_number = 6;
2219     break;
2220     case _lev_ctrl_CC7_EXT:
2221     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222     decodedcontroller.controller_number = 7;
2223     break;
2224     case _lev_ctrl_CC8_EXT:
2225     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226     decodedcontroller.controller_number = 8;
2227     break;
2228     case _lev_ctrl_CC9_EXT:
2229     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230     decodedcontroller.controller_number = 9;
2231     break;
2232     case _lev_ctrl_CC10_EXT:
2233     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234     decodedcontroller.controller_number = 10;
2235     break;
2236     case _lev_ctrl_CC11_EXT:
2237     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238     decodedcontroller.controller_number = 11;
2239     break;
2240     case _lev_ctrl_CC14_EXT:
2241     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242     decodedcontroller.controller_number = 14;
2243     break;
2244     case _lev_ctrl_CC15_EXT:
2245     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246     decodedcontroller.controller_number = 15;
2247     break;
2248     case _lev_ctrl_CC20_EXT:
2249     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250     decodedcontroller.controller_number = 20;
2251     break;
2252     case _lev_ctrl_CC21_EXT:
2253     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254     decodedcontroller.controller_number = 21;
2255     break;
2256     case _lev_ctrl_CC22_EXT:
2257     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258     decodedcontroller.controller_number = 22;
2259     break;
2260     case _lev_ctrl_CC23_EXT:
2261     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262     decodedcontroller.controller_number = 23;
2263     break;
2264     case _lev_ctrl_CC24_EXT:
2265     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2266     decodedcontroller.controller_number = 24;
2267     break;
2268     case _lev_ctrl_CC25_EXT:
2269     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270     decodedcontroller.controller_number = 25;
2271     break;
2272     case _lev_ctrl_CC26_EXT:
2273     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274     decodedcontroller.controller_number = 26;
2275     break;
2276     case _lev_ctrl_CC27_EXT:
2277     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278     decodedcontroller.controller_number = 27;
2279     break;
2280     case _lev_ctrl_CC28_EXT:
2281     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282     decodedcontroller.controller_number = 28;
2283     break;
2284     case _lev_ctrl_CC29_EXT:
2285     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286     decodedcontroller.controller_number = 29;
2287     break;
2288     case _lev_ctrl_CC30_EXT:
2289     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290     decodedcontroller.controller_number = 30;
2291     break;
2292     case _lev_ctrl_CC31_EXT:
2293     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294     decodedcontroller.controller_number = 31;
2295     break;
2296     case _lev_ctrl_CC68_EXT:
2297     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298     decodedcontroller.controller_number = 68;
2299     break;
2300     case _lev_ctrl_CC69_EXT:
2301     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302     decodedcontroller.controller_number = 69;
2303     break;
2304     case _lev_ctrl_CC70_EXT:
2305     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306     decodedcontroller.controller_number = 70;
2307     break;
2308     case _lev_ctrl_CC71_EXT:
2309     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310     decodedcontroller.controller_number = 71;
2311     break;
2312     case _lev_ctrl_CC72_EXT:
2313     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314     decodedcontroller.controller_number = 72;
2315     break;
2316     case _lev_ctrl_CC73_EXT:
2317     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318     decodedcontroller.controller_number = 73;
2319     break;
2320     case _lev_ctrl_CC74_EXT:
2321     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322     decodedcontroller.controller_number = 74;
2323     break;
2324     case _lev_ctrl_CC75_EXT:
2325     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326     decodedcontroller.controller_number = 75;
2327     break;
2328     case _lev_ctrl_CC76_EXT:
2329     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330     decodedcontroller.controller_number = 76;
2331     break;
2332     case _lev_ctrl_CC77_EXT:
2333     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334     decodedcontroller.controller_number = 77;
2335     break;
2336     case _lev_ctrl_CC78_EXT:
2337     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338     decodedcontroller.controller_number = 78;
2339     break;
2340     case _lev_ctrl_CC79_EXT:
2341     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342     decodedcontroller.controller_number = 79;
2343     break;
2344     case _lev_ctrl_CC84_EXT:
2345     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346     decodedcontroller.controller_number = 84;
2347     break;
2348     case _lev_ctrl_CC85_EXT:
2349     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350     decodedcontroller.controller_number = 85;
2351     break;
2352     case _lev_ctrl_CC86_EXT:
2353     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354     decodedcontroller.controller_number = 86;
2355     break;
2356     case _lev_ctrl_CC87_EXT:
2357     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358     decodedcontroller.controller_number = 87;
2359     break;
2360     case _lev_ctrl_CC89_EXT:
2361     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362     decodedcontroller.controller_number = 89;
2363     break;
2364     case _lev_ctrl_CC90_EXT:
2365     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366     decodedcontroller.controller_number = 90;
2367     break;
2368     case _lev_ctrl_CC96_EXT:
2369     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370     decodedcontroller.controller_number = 96;
2371     break;
2372     case _lev_ctrl_CC97_EXT:
2373     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374     decodedcontroller.controller_number = 97;
2375     break;
2376     case _lev_ctrl_CC102_EXT:
2377     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378     decodedcontroller.controller_number = 102;
2379     break;
2380     case _lev_ctrl_CC103_EXT:
2381     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382     decodedcontroller.controller_number = 103;
2383     break;
2384     case _lev_ctrl_CC104_EXT:
2385     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386     decodedcontroller.controller_number = 104;
2387     break;
2388     case _lev_ctrl_CC105_EXT:
2389     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390     decodedcontroller.controller_number = 105;
2391     break;
2392     case _lev_ctrl_CC106_EXT:
2393     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394     decodedcontroller.controller_number = 106;
2395     break;
2396     case _lev_ctrl_CC107_EXT:
2397     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398     decodedcontroller.controller_number = 107;
2399     break;
2400     case _lev_ctrl_CC108_EXT:
2401     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402     decodedcontroller.controller_number = 108;
2403     break;
2404     case _lev_ctrl_CC109_EXT:
2405     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406     decodedcontroller.controller_number = 109;
2407     break;
2408     case _lev_ctrl_CC110_EXT:
2409     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410     decodedcontroller.controller_number = 110;
2411     break;
2412     case _lev_ctrl_CC111_EXT:
2413     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414     decodedcontroller.controller_number = 111;
2415     break;
2416     case _lev_ctrl_CC112_EXT:
2417     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418     decodedcontroller.controller_number = 112;
2419     break;
2420     case _lev_ctrl_CC113_EXT:
2421     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2422     decodedcontroller.controller_number = 113;
2423     break;
2424     case _lev_ctrl_CC114_EXT:
2425     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2426     decodedcontroller.controller_number = 114;
2427     break;
2428     case _lev_ctrl_CC115_EXT:
2429     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2430     decodedcontroller.controller_number = 115;
2431     break;
2432     case _lev_ctrl_CC116_EXT:
2433     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2434     decodedcontroller.controller_number = 116;
2435     break;
2436     case _lev_ctrl_CC117_EXT:
2437     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2438     decodedcontroller.controller_number = 117;
2439     break;
2440     case _lev_ctrl_CC118_EXT:
2441     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2442     decodedcontroller.controller_number = 118;
2443     break;
2444     case _lev_ctrl_CC119_EXT:
2445     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2446     decodedcontroller.controller_number = 119;
2447     break;
2448    
2449 schoenebeck 36 // unknown controller type
2450     default:
2451     throw gig::Exception("Unknown leverage controller type.");
2452     }
2453     return decodedcontroller;
2454     }
2455 schoenebeck 2540
2456     // see above (diagnostic push not supported prior GCC 4.6)
2457     //#pragma GCC diagnostic pop
2458 schoenebeck 2
2459 schoenebeck 809 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2460     _lev_ctrl_t encodedcontroller;
2461     switch (DecodedController.type) {
2462     // special controller
2463     case leverage_ctrl_t::type_none:
2464     encodedcontroller = _lev_ctrl_none;
2465     break;
2466     case leverage_ctrl_t::type_velocity:
2467     encodedcontroller = _lev_ctrl_velocity;
2468     break;
2469     case leverage_ctrl_t::type_channelaftertouch:
2470     encodedcontroller = _lev_ctrl_channelaftertouch;
2471     break;
2472    
2473     // ordinary MIDI control change controller
2474     case leverage_ctrl_t::type_controlchange:
2475     switch (DecodedController.controller_number) {
2476     case 1:
2477     encodedcontroller = _lev_ctrl_modwheel;
2478     break;
2479     case 2:
2480     encodedcontroller = _lev_ctrl_breath;
2481     break;
2482     case 4:
2483     encodedcontroller = _lev_ctrl_foot;
2484     break;
2485     case 12:
2486     encodedcontroller = _lev_ctrl_effect1;
2487     break;
2488     case 13:
2489     encodedcontroller = _lev_ctrl_effect2;
2490     break;
2491     case 16:
2492     encodedcontroller = _lev_ctrl_genpurpose1;
2493     break;
2494     case 17:
2495     encodedcontroller = _lev_ctrl_genpurpose2;
2496     break;
2497     case 18:
2498     encodedcontroller = _lev_ctrl_genpurpose3;
2499     break;
2500     case 19:
2501     encodedcontroller = _lev_ctrl_genpurpose4;
2502     break;
2503     case 5:
2504     encodedcontroller = _lev_ctrl_portamentotime;
2505     break;
2506     case 64:
2507     encodedcontroller = _lev_ctrl_sustainpedal;
2508     break;
2509     case 65:
2510     encodedcontroller = _lev_ctrl_portamento;
2511     break;
2512     case 66:
2513     encodedcontroller = _lev_ctrl_sostenutopedal;
2514     break;
2515     case 67:
2516     encodedcontroller = _lev_ctrl_softpedal;
2517     break;
2518     case 80:
2519     encodedcontroller = _lev_ctrl_genpurpose5;
2520     break;
2521     case 81:
2522     encodedcontroller = _lev_ctrl_genpurpose6;
2523     break;
2524     case 82:
2525     encodedcontroller = _lev_ctrl_genpurpose7;
2526     break;
2527     case 83:
2528     encodedcontroller = _lev_ctrl_genpurpose8;
2529     break;
2530     case 91:
2531     encodedcontroller = _lev_ctrl_effect1depth;
2532     break;
2533     case 92:
2534     encodedcontroller = _lev_ctrl_effect2depth;
2535     break;
2536     case 93:
2537     encodedcontroller = _lev_ctrl_effect3depth;
2538     break;
2539     case 94:
2540     encodedcontroller = _lev_ctrl_effect4depth;
2541     break;
2542     case 95:
2543     encodedcontroller = _lev_ctrl_effect5depth;
2544     break;
2545 schoenebeck 2540
2546     // format extension (these controllers are so far only
2547     // supported by LinuxSampler & gigedit) they will *NOT*
2548     // work with Gigasampler/GigaStudio !
2549     case 3:
2550     encodedcontroller = _lev_ctrl_CC3_EXT;
2551     break;
2552     case 6:
2553     encodedcontroller = _lev_ctrl_CC6_EXT;
2554     break;
2555     case 7:
2556     encodedcontroller = _lev_ctrl_CC7_EXT;
2557     break;
2558     case 8:
2559     encodedcontroller = _lev_ctrl_CC8_EXT;
2560     break;
2561     case 9:
2562     encodedcontroller = _lev_ctrl_CC9_EXT;
2563     break;
2564     case 10:
2565     encodedcontroller = _lev_ctrl_CC10_EXT;
2566     break;
2567     case 11:
2568     encodedcontroller = _lev_ctrl_CC11_EXT;
2569     break;
2570     case 14:
2571     encodedcontroller = _lev_ctrl_CC14_EXT;
2572     break;
2573     case 15:
2574     encodedcontroller = _lev_ctrl_CC15_EXT;
2575     break;
2576     case 20:
2577     encodedcontroller = _lev_ctrl_CC20_EXT;
2578     break;
2579     case 21:
2580     encodedcontroller = _lev_ctrl_CC21_EXT;
2581     break;
2582     case 22:
2583     encodedcontroller = _lev_ctrl_CC22_EXT;
2584     break;
2585     case 23:
2586     encodedcontroller = _lev_ctrl_CC23_EXT;
2587     break;
2588     case 24:
2589     encodedcontroller = _lev_ctrl_CC24_EXT;
2590     break;
2591     case 25:
2592     encodedcontroller = _lev_ctrl_CC25_EXT;
2593     break;
2594     case 26:
2595     encodedcontroller = _lev_ctrl_CC26_EXT;
2596     break;
2597     case 27:
2598     encodedcontroller = _lev_ctrl_CC27_EXT;
2599     break;
2600     case 28:
2601     encodedcontroller = _lev_ctrl_CC28_EXT;
2602     break;
2603     case 29:
2604     encodedcontroller = _lev_ctrl_CC29_EXT;
2605     break;
2606     case 30:
2607     encodedcontroller = _lev_ctrl_CC30_EXT;
2608     break;
2609     case 31:
2610     encodedcontroller = _lev_ctrl_CC31_EXT;
2611     break;
2612     case 68:
2613     encodedcontroller = _lev_ctrl_CC68_EXT;
2614     break;
2615     case 69:
2616     encodedcontroller = _lev_ctrl_CC69_EXT;
2617     break;
2618     case 70:
2619     encodedcontroller = _lev_ctrl_CC70_EXT;
2620     break;
2621     case 71:
2622     encodedcontroller = _lev_ctrl_CC71_EXT;
2623     break;
2624     case 72:
2625     encodedcontroller = _lev_ctrl_CC72_EXT;
2626     break;
2627     case 73:
2628     encodedcontroller = _lev_ctrl_CC73_EXT;
2629     break;
2630     case 74:
2631     encodedcontroller = _lev_ctrl_CC74_EXT;
2632     break;
2633     case 75:
2634     encodedcontroller = _lev_ctrl_CC75_EXT;
2635     break;
2636     case 76:
2637     encodedcontroller = _lev_ctrl_CC76_EXT;
2638     break;
2639     case 77:
2640     encodedcontroller = _lev_ctrl_CC77_EXT;
2641     break;
2642     case 78:
2643     encodedcontroller = _lev_ctrl_CC78_EXT;
2644     break;
2645     case 79:
2646     encodedcontroller = _lev_ctrl_CC79_EXT;
2647     break;
2648     case 84:
2649     encodedcontroller = _lev_ctrl_CC84_EXT;
2650     break;
2651     case 85:
2652     encodedcontroller = _lev_ctrl_CC85_EXT;
2653     break;
2654     case 86:
2655     encodedcontroller = _lev_ctrl_CC86_EXT;
2656     break;
2657     case 87:
2658     encodedcontroller = _lev_ctrl_CC87_EXT;
2659     break;
2660     case 89:
2661     encodedcontroller = _lev_ctrl_CC89_EXT;
2662     break;
2663     case 90:
2664     encodedcontroller = _lev_ctrl_CC90_EXT;
2665     break;
2666     case 96:
2667     encodedcontroller = _lev_ctrl_CC96_EXT;
2668     break;
2669     case 97:
2670     encodedcontroller = _lev_ctrl_CC97_EXT;
2671     break;
2672     case 102:
2673     encodedcontroller = _lev_ctrl_CC102_EXT;
2674     break;
2675     case 103:
2676     encodedcontroller = _lev_ctrl_CC103_EXT;
2677     break;
2678     case 104:
2679     encodedcontroller = _lev_ctrl_CC104_EXT;
2680     break;
2681     case 105:
2682     encodedcontroller = _lev_ctrl_CC105_EXT;
2683     break;
2684     case 106:
2685     encodedcontroller = _lev_ctrl_CC106_EXT;
2686     break;
2687     case 107:
2688     encodedcontroller = _lev_ctrl_CC107_EXT;
2689     break;
2690     case 108:
2691     encodedcontroller = _lev_ctrl_CC108_EXT;
2692     break;
2693     case 109:
2694     encodedcontroller = _lev_ctrl_CC109_EXT;
2695     break;
2696     case 110:
2697     encodedcontroller = _lev_ctrl_CC110_EXT;
2698     break;
2699     case 111:
2700     encodedcontroller = _lev_ctrl_CC111_EXT;
2701     break;
2702     case 112:
2703     encodedcontroller = _lev_ctrl_CC112_EXT;
2704     break;
2705     case 113:
2706     encodedcontroller = _lev_ctrl_CC113_EXT;
2707     break;
2708     case 114:
2709     encodedcontroller = _lev_ctrl_CC114_EXT;
2710     break;
2711     case 115:
2712     encodedcontroller = _lev_ctrl_CC115_EXT;
2713     break;
2714     case 116:
2715     encodedcontroller = _lev_ctrl_CC116_EXT;
2716     break;
2717     case 117:
2718     encodedcontroller = _lev_ctrl_CC117_EXT;
2719     break;
2720     case 118:
2721     encodedcontroller = _lev_ctrl_CC118_EXT;
2722     break;
2723     case 119:
2724     encodedcontroller = _lev_ctrl_CC119_EXT;
2725     break;
2726    
2727 schoenebeck 809 default:
2728     throw gig::Exception("leverage controller number is not supported by the gig format");
2729     }
2730 persson 1182 break;
2731 schoenebeck 809 default:
2732     throw gig::Exception("Unknown leverage controller type.");
2733     }
2734     return encodedcontroller;
2735     }
2736    
2737 schoenebeck 16 DimensionRegion::~DimensionRegion() {
2738     Instances--;
2739     if (!Instances) {
2740     // delete the velocity->volume tables
2741     VelocityTableMap::iterator iter;
2742     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2743     double* pTable = iter->second;
2744     if (pTable) delete[] pTable;
2745     }
2746     pVelocityTables->clear();
2747     delete pVelocityTables;
2748     pVelocityTables = NULL;
2749     }
2750 persson 858 if (VelocityTable) delete[] VelocityTable;
2751 schoenebeck 16 }
2752 schoenebeck 2
2753 schoenebeck 16 /**
2754     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
2755     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
2756     * and VelocityResponseCurveScaling) involved are taken into account to
2757     * calculate the amplitude factor. Use this method when a key was
2758     * triggered to get the volume with which the sample should be played
2759     * back.
2760     *
2761 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
2762     * @returns amplitude factor (between 0.0 and 1.0)
2763 schoenebeck 16 */
2764     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2765     return pVelocityAttenuationTable[MIDIKeyVelocity];
2766     }
2767 schoenebeck 2
2768 persson 613 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2769     return pVelocityReleaseTable[MIDIKeyVelocity];
2770     }
2771    
2772 persson 728 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2773     return pVelocityCutoffTable[MIDIKeyVelocity];
2774     }
2775    
2776 schoenebeck 1358 /**
2777     * Updates the respective member variable and the lookup table / cache
2778     * that depends on this value.
2779     */
2780     void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2781     pVelocityAttenuationTable =
2782     GetVelocityTable(
2783     curve, VelocityResponseDepth, VelocityResponseCurveScaling
2784     );
2785     VelocityResponseCurve = curve;
2786     }
2787    
2788     /**
2789     * Updates the respective member variable and the lookup table / cache
2790     * that depends on this value.
2791     */
2792     void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2793     pVelocityAttenuationTable =
2794     GetVelocityTable(
2795     VelocityResponseCurve, depth, VelocityResponseCurveScaling
2796     );
2797     VelocityResponseDepth = depth;
2798     }
2799    
2800     /**
2801     * Updates the respective member variable and the lookup table / cache
2802     * that depends on this value.
2803     */
2804     void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2805     pVelocityAttenuationTable =
2806     GetVelocityTable(
2807     VelocityResponseCurve, VelocityResponseDepth, scaling
2808     );
2809     VelocityResponseCurveScaling = scaling;
2810     }
2811    
2812     /**
2813     * Updates the respective member variable and the lookup table / cache
2814     * that depends on this value.
2815     */
2816     void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2817     pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2818     ReleaseVelocityResponseCurve = curve;
2819     }
2820    
2821     /**
2822     * Updates the respective member variable and the lookup table / cache
2823     * that depends on this value.
2824     */
2825     void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2826     pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2827     ReleaseVelocityResponseDepth = depth;
2828     }
2829    
2830     /**
2831     * Updates the respective member variable and the lookup table / cache
2832     * that depends on this value.
2833     */
2834     void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2835     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2836     VCFCutoffController = controller;
2837     }
2838    
2839     /**
2840     * Updates the respective member variable and the lookup table / cache
2841     * that depends on this value.
2842     */
2843     void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2844     pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2845     VCFVelocityCurve = curve;
2846     }
2847    
2848     /**
2849     * Updates the respective member variable and the lookup table / cache
2850     * that depends on this value.
2851     */
2852     void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2853     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2854     VCFVelocityDynamicRange = range;
2855     }
2856    
2857     /**
2858     * Updates the respective member variable and the lookup table / cache
2859     * that depends on this value.
2860     */
2861     void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2862     pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2863     VCFVelocityScale = scaling;
2864     }
2865    
2866 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2867 schoenebeck 317
2868 schoenebeck 308 // line-segment approximations of the 15 velocity curves
2869 schoenebeck 16
2870 schoenebeck 308 // linear
2871     const int lin0[] = { 1, 1, 127, 127 };
2872     const int lin1[] = { 1, 21, 127, 127 };
2873     const int lin2[] = { 1, 45, 127, 127 };
2874     const int lin3[] = { 1, 74, 127, 127 };
2875     const int lin4[] = { 1, 127, 127, 127 };
2876 schoenebeck 16
2877 schoenebeck 308 // non-linear
2878     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2879 schoenebeck 317 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2880 schoenebeck 308 127, 127 };
2881     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2882     127, 127 };
2883     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2884     127, 127 };
2885     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2886 schoenebeck 317
2887 schoenebeck 308 // special
2888 schoenebeck 317 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2889 schoenebeck 308 113, 127, 127, 127 };
2890     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2891     118, 127, 127, 127 };
2892 schoenebeck 317 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2893 schoenebeck 308 85, 90, 91, 127, 127, 127 };
2894 schoenebeck 317 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2895 schoenebeck 308 117, 127, 127, 127 };
2896 schoenebeck 317 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2897 schoenebeck 308 127, 127 };
2898 schoenebeck 317
2899 persson 728 // this is only used by the VCF velocity curve
2900     const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2901     91, 127, 127, 127 };
2902    
2903 schoenebeck 308 const int* const curves[] = { non0, non1, non2, non3, non4,
2904 schoenebeck 317 lin0, lin1, lin2, lin3, lin4,
2905 persson 728 spe0, spe1, spe2, spe3, spe4, spe5 };
2906 schoenebeck 317
2907 schoenebeck 308 double* const table = new double[128];
2908    
2909     const int* curve = curves[curveType * 5 + depth];
2910     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2911 schoenebeck 317
2912 schoenebeck 308 table[0] = 0;
2913     for (int x = 1 ; x < 128 ; x++) {
2914    
2915     if (x > curve[2]) curve += 2;
2916 schoenebeck 317 double y = curve[1] + (x - curve[0]) *
2917 schoenebeck 308 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2918     y = y / 127;
2919    
2920     // Scale up for s > 20, down for s < 20. When
2921     // down-scaling, the curve still ends at 1.0.
2922     if (s < 20 && y >= 0.5)
2923     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2924     else
2925     y = y * (s / 20.0);
2926     if (y > 1) y = 1;
2927    
2928     table[x] = y;
2929     }
2930     return table;
2931     }
2932    
2933    
2934 schoenebeck 2 // *************** Region ***************
2935     // *
2936    
2937     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2938     // Initialization
2939     Dimensions = 0;
2940 schoenebeck 347 for (int i = 0; i < 256; i++) {
2941 schoenebeck 2 pDimensionRegions[i] = NULL;
2942     }
2943 schoenebeck 282 Layers = 1;
2944 schoenebeck 347 File* file = (File*) GetParent()->GetParent();
2945     int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2946 schoenebeck 2
2947     // Actual Loading
2948    
2949 schoenebeck 1524 if (!file->GetAutoLoad()) return;
2950    
2951 schoenebeck 2 LoadDimensionRegions(rgnList);
2952    
2953     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2954     if (_3lnk) {
2955     DimensionRegions = _3lnk->ReadUint32();
2956 schoenebeck 347 for (int i = 0; i < dimensionBits; i++) {
2957 schoenebeck 2 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2958     uint8_t bits = _3lnk->ReadUint8();
2959 persson 1199 _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2960     _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2961 persson 774 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2962 schoenebeck 2 if (dimension == dimension_none) { // inactive dimension
2963     pDimensionDefinitions[i].dimension = dimension_none;
2964     pDimensionDefinitions[i].bits = 0;
2965     pDimensionDefinitions[i].zones = 0;
2966     pDimensionDefinitions[i].split_type = split_type_bit;
2967     pDimensionDefinitions[i].zone_size = 0;
2968     }
2969     else { // active dimension
2970     pDimensionDefinitions[i].dimension = dimension;
2971     pDimensionDefinitions[i].bits = bits;
2972 persson 774 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2973 schoenebeck 1113 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2974     pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
2975 schoenebeck 2 Dimensions++;
2976 schoenebeck 282
2977     // if this is a layer dimension, remember the amount of layers
2978     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2979 schoenebeck 2 }
2980 persson 774 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2981 schoenebeck 2 }
2982 persson 834 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2983 schoenebeck 2
2984 persson 858 // if there's a velocity dimension and custom velocity zone splits are used,
2985     // update the VelocityTables in the dimension regions
2986     UpdateVelocityTable();
2987 schoenebeck 2
2988 schoenebeck 317 // jump to start of the wave pool indices (if not already there)
2989     if (file->pVersion && file->pVersion->major == 3)
2990     _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2991     else
2992     _3lnk->SetPos(44);
2993    
2994 schoenebeck 1524 // load sample references (if auto loading is enabled)
2995     if (file->GetAutoLoad()) {
2996     for (uint i = 0; i < DimensionRegions; i++) {
2997     uint32_t wavepoolindex = _3lnk->ReadUint32();
2998     if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2999     }
3000     GetSample(); // load global region sample reference
3001 schoenebeck 2 }
3002 persson 1102 } else {
3003     DimensionRegions = 0;
3004 persson 1182 for (int i = 0 ; i < 8 ; i++) {
3005     pDimensionDefinitions[i].dimension = dimension_none;
3006     pDimensionDefinitions[i].bits = 0;
3007     pDimensionDefinitions[i].zones = 0;
3008     }
3009 schoenebeck 2 }
3010 schoenebeck 823
3011     // make sure there is at least one dimension region
3012     if (!DimensionRegions) {
3013     RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3014     if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3015     RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3016 schoenebeck 1316 pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3017 schoenebeck 823 DimensionRegions = 1;
3018     }
3019 schoenebeck 2 }
3020    
3021 schoenebeck 809 /**
3022     * Apply Region settings and all its DimensionRegions to the respective
3023     * RIFF chunks. You have to call File::Save() to make changes persistent.
3024     *
3025     * Usually there is absolutely no need to call this method explicitly.
3026     * It will be called automatically when File::Save() was called.
3027     *
3028     * @throws gig::Exception if samples cannot be dereferenced
3029     */
3030     void Region::UpdateChunks() {
3031 schoenebeck 1106 // in the gig format we don't care about the Region's sample reference
3032     // but we still have to provide some existing one to not corrupt the
3033     // file, so to avoid the latter we simply always assign the sample of
3034     // the first dimension region of this region
3035     pSample = pDimensionRegions[0]->pSample;
3036    
3037 schoenebeck 809 // first update base class's chunks
3038     DLS::Region::UpdateChunks();
3039    
3040     // update dimension region's chunks
3041 schoenebeck 823 for (int i = 0; i < DimensionRegions; i++) {
3042 persson 1317 pDimensionRegions[i]->UpdateChunks();
3043 schoenebeck 823 }
3044 schoenebeck 809
3045 persson 1317 File* pFile = (File*) GetParent()->GetParent();
3046     bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3047 persson 1247 const int iMaxDimensions = version3 ? 8 : 5;
3048     const int iMaxDimensionRegions = version3 ? 256 : 32;
3049 schoenebeck 809
3050     // make sure '3lnk' chunk exists
3051     RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3052     if (!_3lnk) {
3053 persson 1247 const int _3lnkChunkSize = version3 ? 1092 : 172;
3054 schoenebeck 809 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3055 persson 1182 memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3056 persson 1192
3057     // move 3prg to last position
3058     pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
3059 schoenebeck 809 }
3060    
3061     // update dimension definitions in '3lnk' chunk
3062     uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3063 persson 1179 store32(&pData[0], DimensionRegions);
3064 persson 1199 int shift = 0;
3065 schoenebeck 809 for (int i = 0; i < iMaxDimensions; i++) {
3066 persson 918 pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3067     pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3068 persson 1266 pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3069 persson 1199 pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3070 persson 918 pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3071 persson 1199 // next 3 bytes unknown, always zero?
3072    
3073     shift += pDimensionDefinitions[i].bits;
3074 schoenebeck 809 }
3075    
3076     // update wave pool table in '3lnk' chunk
3077 persson 1247 const int iWavePoolOffset = version3 ? 68 : 44;
3078 schoenebeck 809 for (uint i = 0; i < iMaxDimensionRegions; i++) {
3079     int iWaveIndex = -1;
3080     if (i < DimensionRegions) {
3081 schoenebeck 823 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3082     File::SampleList::iterator iter = pFile->pSamples->begin();
3083     File::SampleList::iterator end = pFile->pSamples->end();
3084 schoenebeck 809 for (int index = 0; iter != end; ++iter, ++index) {
3085 schoenebeck 823 if (*iter == pDimensionRegions[i]->pSample) {
3086     iWaveIndex = index;
3087     break;
3088     }
3089 schoenebeck 809 }
3090     }
3091 persson 1179 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3092 schoenebeck 809 }
3093     }
3094    
3095 schoenebeck 2 void Region::LoadDimensionRegions(RIFF::List* rgn) {
3096     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3097     if (_3prg) {
3098     int dimensionRegionNr = 0;
3099     RIFF::List* _3ewl = _3prg->GetFirstSubList();
3100     while (_3ewl) {
3101     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3102 schoenebeck 1316 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3103 schoenebeck 2 dimensionRegionNr++;
3104     }
3105     _3ewl = _3prg->GetNextSubList();
3106     }
3107     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3108     }
3109     }
3110    
3111 schoenebeck 1335 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3112     // update KeyRange struct and make sure regions are in correct order
3113     DLS::Region::SetKeyRange(Low, High);
3114     // update Region key table for fast lookup
3115     ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3116     }
3117    
3118 persson 858 void Region::UpdateVelocityTable() {
3119     // get velocity dimension's index
3120     int veldim = -1;
3121     for (int i = 0 ; i < Dimensions ; i++) {
3122     if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3123     veldim = i;
3124 schoenebeck 809 break;
3125     }
3126     }
3127 persson 858 if (veldim == -1) return;
3128 schoenebeck 809
3129 persson 858 int step = 1;
3130     for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3131     int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3132     int end = step * pDimensionDefinitions[veldim].zones;
3133 schoenebeck 809
3134 persson 858 // loop through all dimension regions for all dimensions except the velocity dimension
3135     int dim[8] = { 0 };
3136     for (int i = 0 ; i < DimensionRegions ; i++) {
3137    
3138 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3139     pDimensionRegions[i]->VelocityUpperLimit) {
3140 persson 858 // create the velocity table
3141     uint8_t* table = pDimensionRegions[i]->VelocityTable;
3142     if (!table) {
3143     table = new uint8_t[128];
3144     pDimensionRegions[i]->VelocityTable = table;
3145     }
3146     int tableidx = 0;
3147     int velocityZone = 0;
3148 persson 1070 if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3149     for (int k = i ; k < end ; k += step) {
3150     DimensionRegion *d = pDimensionRegions[k];
3151     for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3152     velocityZone++;
3153     }
3154     } else { // gig2
3155     for (int k = i ; k < end ; k += step) {
3156     DimensionRegion *d = pDimensionRegions[k];
3157     for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3158     velocityZone++;
3159     }
3160 persson 858 }
3161     } else {
3162     if (pDimensionRegions[i]->VelocityTable) {
3163     delete[] pDimensionRegions[i]->VelocityTable;
3164     pDimensionRegions[i]->VelocityTable = 0;
3165     }
3166 schoenebeck 809 }
3167 persson 858
3168     int j;
3169     int shift = 0;
3170     for (j = 0 ; j < Dimensions ; j++) {
3171     if (j == veldim) i += skipveldim; // skip velocity dimension
3172     else {
3173     dim[j]++;
3174     if (dim[j] < pDimensionDefinitions[j].zones) break;
3175     else {
3176     // skip unused dimension regions
3177     dim[j] = 0;
3178     i += ((1 << pDimensionDefinitions[j].bits) -
3179     pDimensionDefinitions[j].zones) << shift;
3180     }
3181     }
3182     shift += pDimensionDefinitions[j].bits;
3183     }
3184     if (j == Dimensions) break;
3185 schoenebeck 809 }
3186     }
3187    
3188     /** @brief Einstein would have dreamed of it - create a new dimension.
3189     *
3190     * Creates a new dimension with the dimension definition given by
3191     * \a pDimDef. The appropriate amount of DimensionRegions will be created.
3192     * There is a hard limit of dimensions and total amount of "bits" all
3193     * dimensions can have. This limit is dependant to what gig file format
3194     * version this file refers to. The gig v2 (and lower) format has a
3195     * dimension limit and total amount of bits limit of 5, whereas the gig v3
3196     * format has a limit of 8.
3197     *
3198     * @param pDimDef - defintion of the new dimension
3199     * @throws gig::Exception if dimension of the same type exists already
3200     * @throws gig::Exception if amount of dimensions or total amount of
3201     * dimension bits limit is violated
3202     */
3203     void Region::AddDimension(dimension_def_t* pDimDef) {
3204 schoenebeck 2547 // some initial sanity checks of the given dimension definition
3205     if (pDimDef->zones < 2)
3206     throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3207     if (pDimDef->bits < 1)
3208     throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3209     if (pDimDef->dimension == dimension_samplechannel) {
3210     if (pDimDef->zones != 2)
3211     throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3212     if (pDimDef->bits != 1)
3213     throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3214     }
3215    
3216 schoenebeck 809 // check if max. amount of dimensions reached
3217     File* file = (File*) GetParent()->GetParent();
3218     const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3219     if (Dimensions >= iMaxDimensions)
3220     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3221     // check if max. amount of dimension bits reached
3222     int iCurrentBits = 0;
3223     for (int i = 0; i < Dimensions; i++)
3224     iCurrentBits += pDimensionDefinitions[i].bits;
3225     if (iCurrentBits >= iMaxDimensions)
3226     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3227     const int iNewBits = iCurrentBits + pDimDef->bits;
3228     if (iNewBits > iMaxDimensions)
3229     throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3230     // check if there's already a dimensions of the same type
3231     for (int i = 0; i < Dimensions; i++)
3232     if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3233     throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3234    
3235 persson 1301 // pos is where the new dimension should be placed, normally
3236     // last in list, except for the samplechannel dimension which
3237     // has to be first in list
3238     int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3239     int bitpos = 0;
3240     for (int i = 0 ; i < pos ; i++)
3241     bitpos += pDimensionDefinitions[i].bits;
3242    
3243     // make room for the new dimension
3244     for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3245     for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3246     for (int j = Dimensions ; j > pos ; j--) {
3247     pDimensionRegions[i]->DimensionUpperLimits[j] =
3248     pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3249     }
3250     }
3251    
3252 schoenebeck 809 // assign definition of new dimension
3253 persson 1301 pDimensionDefinitions[pos] = *pDimDef;
3254 schoenebeck 809
3255 schoenebeck 1113 // auto correct certain dimension definition fields (where possible)
3256 persson 1301 pDimensionDefinitions[pos].split_type =
3257     __resolveSplitType(pDimensionDefinitions[pos].dimension);
3258     pDimensionDefinitions[pos].zone_size =
3259     __resolveZoneSize(pDimensionDefinitions[pos]);
3260 schoenebeck 1113
3261 persson 1301 // create new dimension region(s) for this new dimension, and make
3262     // sure that the dimension regions are placed correctly in both the
3263     // RIFF list and the pDimensionRegions array
3264     RIFF::Chunk* moveTo = NULL;
3265     RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3266     for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3267     for (int k = 0 ; k < (1 << bitpos) ; k++) {
3268     pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3269     }
3270     for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3271     for (int k = 0 ; k < (1 << bitpos) ; k++) {
3272     RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3273     if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3274     // create a new dimension region and copy all parameter values from
3275     // an existing dimension region
3276     pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3277     new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3278 persson 1247
3279 persson 1301 DimensionRegions++;
3280     }
3281     }
3282     moveTo = pDimensionRegions[i]->pParentList;
3283 schoenebeck 809 }
3284    
3285 persson 1247 // initialize the upper limits for this dimension
3286 persson 1301 int mask = (1 << bitpos) - 1;
3287     for (int z = 0 ; z < pDimDef->zones ; z++) {
3288 persson 1264 uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3289 persson 1247 for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3290 persson 1301 pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3291     (z << bitpos) |
3292     (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3293 persson 1247 }
3294     }
3295    
3296 schoenebeck 809 Dimensions++;
3297    
3298     // if this is a layer dimension, update 'Layers' attribute
3299     if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3300    
3301 persson 858 UpdateVelocityTable();
3302 schoenebeck 809 }
3303    
3304     /** @brief Delete an existing dimension.
3305     *
3306     * Deletes the dimension given by \a pDimDef and deletes all respective
3307     * dimension regions, that is all dimension regions where the dimension's
3308     * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
3309     * for example this would delete all dimension regions for the case(s)
3310     * where the sustain pedal is pressed down.
3311     *
3312     * @param pDimDef - dimension to delete
3313     * @throws gig::Exception if given dimension cannot be found
3314     */
3315     void Region::DeleteDimension(dimension_def_t* pDimDef) {
3316     // get dimension's index
3317     int iDimensionNr = -1;
3318     for (int i = 0; i < Dimensions; i++) {
3319     if (&pDimensionDefinitions[i] == pDimDef) {
3320     iDimensionNr = i;
3321     break;
3322     }
3323     }
3324     if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3325    
3326     // get amount of bits below the dimension to delete
3327     int iLowerBits = 0;
3328     for (int i = 0; i < iDimensionNr; i++)
3329     iLowerBits += pDimensionDefinitions[i].bits;
3330    
3331     // get amount ot bits above the dimension to delete
3332     int iUpperBits = 0;
3333     for (int i = iDimensionNr + 1; i < Dimensions; i++)
3334     iUpperBits += pDimensionDefinitions[i].bits;
3335    
3336 persson 1247 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3337    
3338 schoenebeck 809 // delete dimension regions which belong to the given dimension
3339     // (that is where the dimension's bit > 0)
3340     for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3341     for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3342     for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3343     int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3344     iObsoleteBit << iLowerBits |
3345     iLowerBit;
3346 persson 1247
3347     _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3348 schoenebeck 809 delete pDimensionRegions[iToDelete];
3349     pDimensionRegions[iToDelete] = NULL;
3350     DimensionRegions--;
3351     }
3352     }
3353     }
3354    
3355     // defrag pDimensionRegions array
3356     // (that is remove the NULL spaces within the pDimensionRegions array)
3357     for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3358     if (!pDimensionRegions[iTo]) {
3359     if (iFrom <= iTo) iFrom = iTo + 1;
3360     while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3361     if (iFrom < 256 && pDimensionRegions[iFrom]) {
3362     pDimensionRegions[iTo] = pDimensionRegions[iFrom];
3363     pDimensionRegions[iFrom] = NULL;
3364     }
3365     }
3366     }
3367    
3368 persson 1247 // remove the this dimension from the upper limits arrays
3369     for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3370     DimensionRegion* d = pDimensionRegions[j];
3371     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3372     d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3373     }
3374     d->DimensionUpperLimits[Dimensions - 1] = 127;
3375     }
3376    
3377 schoenebeck 809 // 'remove' dimension definition
3378     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3379     pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
3380     }
3381     pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3382     pDimensionDefinitions[Dimensions - 1].bits = 0;
3383     pDimensionDefinitions[Dimensions - 1].zones = 0;
3384    
3385     Dimensions--;
3386    
3387     // if this was a layer dimension, update 'Layers' attribute
3388     if (pDimDef->dimension == dimension_layer) Layers = 1;
3389     }
3390    
3391 schoenebeck 2547 /**
3392     * Searches in the current Region for a dimension of the given dimension
3393     * type and returns the precise configuration of that dimension in this
3394     * Region.
3395     *
3396     * @param type - dimension type of the sought dimension
3397     * @returns dimension definition or NULL if there is no dimension with
3398     * sought type in this Region.
3399     */
3400     dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3401     for (int i = 0; i < Dimensions; ++i)
3402     if (pDimensionDefinitions[i].dimension == type)
3403     return &pDimensionDefinitions[i];
3404     return NULL;
3405     }
3406    
3407 schoenebeck 2 Region::~Region() {
3408 schoenebeck 350 for (int i = 0; i < 256; i++) {
3409 schoenebeck 2 if (pDimensionRegions[i]) delete pDimensionRegions[i];
3410     }
3411     }
3412    
3413     /**
3414     * Use this method in your audio engine to get the appropriate dimension
3415     * region with it's articulation data for the current situation. Just
3416     * call the method with the current MIDI controller values and you'll get
3417     * the DimensionRegion with the appropriate articulation data for the
3418     * current situation (for this Region of course only). To do that you'll
3419     * first have to look which dimensions with which controllers and in
3420     * which order are defined for this Region when you load the .gig file.
3421     * Special cases are e.g. layer or channel dimensions where you just put
3422     * in the index numbers instead of a MIDI controller value (means 0 for
3423     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
3424     * etc.).
3425     *
3426 schoenebeck 347 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
3427 schoenebeck 2 * @returns adress to the DimensionRegion for the given situation
3428     * @see pDimensionDefinitions
3429     * @see Dimensions
3430     */
3431 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3432 persson 858 uint8_t bits;
3433     int veldim = -1;
3434     int velbitpos;
3435     int bitpos = 0;
3436     int dimregidx = 0;
3437 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
3438 persson 858 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3439     // the velocity dimension must be handled after the other dimensions
3440     veldim = i;
3441     velbitpos = bitpos;
3442     } else {
3443     switch (pDimensionDefinitions[i].split_type) {
3444     case split_type_normal:
3445 persson 1070 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3446     // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3447     for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3448     if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3449     }
3450     } else {
3451     // gig2: evenly sized zones
3452     bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3453     }
3454 persson 858 break;
3455     case split_type_bit: // the value is already the sought dimension bit number
3456     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3457     bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3458     break;
3459     }
3460     dimregidx |= bits << bitpos;
3461 schoenebeck 2 }
3462 persson 858 bitpos += pDimensionDefinitions[i].bits;
3463 schoenebeck 2 }
3464 persson 858 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3465     if (veldim != -1) {
3466     // (dimreg is now the dimension region for the lowest velocity)
3467 persson 1070 if (dimreg->VelocityTable) // custom defined zone ranges
3468 persson 858 bits = dimreg->VelocityTable[DimValues[veldim]];
3469     else // normal split type
3470     bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
3471    
3472     dimregidx |= bits << velbitpos;
3473     dimreg = pDimensionRegions[dimregidx];
3474     }
3475     return dimreg;
3476 schoenebeck 2 }
3477    
3478     /**
3479     * Returns the appropriate DimensionRegion for the given dimension bit
3480     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
3481     * instead of calling this method directly!
3482     *
3483 schoenebeck 347 * @param DimBits Bit numbers for dimension 0 to 7
3484 schoenebeck 2 * @returns adress to the DimensionRegion for the given dimension
3485     * bit numbers
3486     * @see GetDimensionRegionByValue()
3487     */
3488 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
3489     return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3490     << pDimensionDefinitions[5].bits | DimBits[5])
3491     << pDimensionDefinitions[4].bits | DimBits[4])
3492     << pDimensionDefinitions[3].bits | DimBits[3])
3493     << pDimensionDefinitions[2].bits | DimBits[2])
3494     << pDimensionDefinitions[1].bits | DimBits[1])
3495     << pDimensionDefinitions[0].bits | DimBits[0]];
3496 schoenebeck 2 }
3497    
3498     /**
3499     * Returns pointer address to the Sample referenced with this region.
3500     * This is the global Sample for the entire Region (not sure if this is
3501     * actually used by the Gigasampler engine - I would only use the Sample
3502     * referenced by the appropriate DimensionRegion instead of this sample).
3503     *
3504     * @returns address to Sample or NULL if there is no reference to a
3505     * sample saved in the .gig file
3506     */
3507     Sample* Region::GetSample() {
3508     if (pSample) return static_cast<gig::Sample*>(pSample);
3509     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3510     }
3511    
3512 schoenebeck 515 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3513 schoenebeck 352 if ((int32_t)WavePoolTableIndex == -1) return NULL;
3514 schoenebeck 2 File* file = (File*) GetParent()->GetParent();
3515 persson 902 if (!file->pWavePoolTable) return NULL;
3516 schoenebeck 2 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3517 persson 666 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3518 schoenebeck 515 Sample* sample = file->GetFirstSample(pProgress);
3519 schoenebeck 2 while (sample) {
3520 persson 666 if (sample->ulWavePoolOffset == soughtoffset &&
3521 persson 918 sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3522 schoenebeck 2 sample = file->GetNextSample();
3523     }
3524     return NULL;
3525     }
3526 schoenebeck 2394
3527     /**
3528     * Make a (semi) deep copy of the Region object given by @a orig
3529     * and assign it to this object.
3530     *
3531     * Note that all sample pointers referenced by @a orig are simply copied as
3532     * memory address. Thus the respective samples are shared, not duplicated!
3533     *
3534     * @param orig - original Region object to be copied from
3535     */
3536     void Region::CopyAssign(const Region* orig) {
3537 schoenebeck 2482 CopyAssign(orig, NULL);
3538     }
3539    
3540     /**
3541     * Make a (semi) deep copy of the Region object given by @a orig and
3542     * assign it to this object
3543     *
3544     * @param mSamples - crosslink map between the foreign file's samples and
3545     * this file's samples
3546     */
3547     void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3548 schoenebeck 2394 // handle base classes
3549     DLS::Region::CopyAssign(orig);
3550    
3551 schoenebeck 2482 if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3552     pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3553     }
3554    
3555 schoenebeck 2394 // handle own member variables
3556     for (int i = Dimensions - 1; i >= 0; --i) {
3557     DeleteDimension(&pDimensionDefinitions[i]);
3558     }
3559     Layers = 0; // just to be sure
3560     for (int i = 0; i < orig->Dimensions; i++) {
3561     // we need to copy the dim definition here, to avoid the compiler
3562     // complaining about const-ness issue
3563     dimension_def_t def = orig->pDimensionDefinitions[i];
3564     AddDimension(&def);
3565     }
3566     for (int i = 0; i < 256; i++) {
3567     if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3568     pDimensionRegions[i]->CopyAssign(
3569 schoenebeck 2482 orig->pDimensionRegions[i],
3570     mSamples
3571 schoenebeck 2394 );
3572     }
3573     }
3574     Layers = orig->Layers;
3575     }
3576 schoenebeck 2
3577    
3578 persson 1627 // *************** MidiRule ***************
3579     // *
3580 schoenebeck 2
3581 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3582     _3ewg->SetPos(36);
3583     Triggers = _3ewg->ReadUint8();
3584     _3ewg->SetPos(40);
3585     ControllerNumber = _3ewg->ReadUint8();
3586     _3ewg->SetPos(46);
3587     for (int i = 0 ; i < Triggers ; i++) {
3588     pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3589     pTriggers[i].Descending = _3ewg->ReadUint8();
3590     pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3591     pTriggers[i].Key = _3ewg->ReadUint8();
3592     pTriggers[i].NoteOff = _3ewg->ReadUint8();
3593     pTriggers[i].Velocity = _3ewg->ReadUint8();
3594     pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3595     _3ewg->ReadUint8();
3596     }
3597 persson 1627 }
3598    
3599 persson 2450 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3600     ControllerNumber(0),
3601     Triggers(0) {
3602     }
3603 persson 1627
3604 persson 2450 void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3605     pData[32] = 4;
3606     pData[33] = 16;
3607     pData[36] = Triggers;
3608     pData[40] = ControllerNumber;
3609     for (int i = 0 ; i < Triggers ; i++) {
3610     pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3611     pData[47 + i * 8] = pTriggers[i].Descending;
3612     pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3613     pData[49 + i * 8] = pTriggers[i].Key;
3614     pData[50 + i * 8] = pTriggers[i].NoteOff;
3615     pData[51 + i * 8] = pTriggers[i].Velocity;
3616     pData[52 + i * 8] = pTriggers[i].OverridePedal;
3617     }
3618     }
3619    
3620     MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3621     _3ewg->SetPos(36);
3622     LegatoSamples = _3ewg->ReadUint8(); // always 12
3623     _3ewg->SetPos(40);
3624     BypassUseController = _3ewg->ReadUint8();
3625     BypassKey = _3ewg->ReadUint8();
3626     BypassController = _3ewg->ReadUint8();
3627     ThresholdTime = _3ewg->ReadUint16();
3628     _3ewg->ReadInt16();
3629     ReleaseTime = _3ewg->ReadUint16();
3630     _3ewg->ReadInt16();
3631     KeyRange.low = _3ewg->ReadUint8();
3632     KeyRange.high = _3ewg->ReadUint8();
3633     _3ewg->SetPos(64);
3634     ReleaseTriggerKey = _3ewg->ReadUint8();
3635     AltSustain1Key = _3ewg->ReadUint8();
3636     AltSustain2Key = _3ewg->ReadUint8();
3637     }
3638    
3639     MidiRuleLegato::MidiRuleLegato() :
3640     LegatoSamples(12),
3641     BypassUseController(false),
3642     BypassKey(0),
3643     BypassController(1),
3644     ThresholdTime(20),
3645     ReleaseTime(20),
3646     ReleaseTriggerKey(0),
3647     AltSustain1Key(0),
3648     AltSustain2Key(0)
3649     {
3650     KeyRange.low = KeyRange.high = 0;
3651     }
3652    
3653     void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3654     pData[32] = 0;
3655     pData[33] = 16;
3656     pData[36] = LegatoSamples;
3657     pData[40] = BypassUseController;
3658     pData[41] = BypassKey;
3659     pData[42] = BypassController;
3660     store16(&pData[43], ThresholdTime);
3661     store16(&pData[47], ReleaseTime);
3662     pData[51] = KeyRange.low;
3663     pData[52] = KeyRange.high;
3664     pData[64] = ReleaseTriggerKey;
3665     pData[65] = AltSustain1Key;
3666     pData[66] = AltSustain2Key;
3667     }
3668    
3669     MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3670     _3ewg->SetPos(36);
3671     Articulations = _3ewg->ReadUint8();
3672     int flags = _3ewg->ReadUint8();
3673     Polyphonic = flags & 8;
3674     Chained = flags & 4;
3675     Selector = (flags & 2) ? selector_controller :
3676     (flags & 1) ? selector_key_switch : selector_none;
3677     Patterns = _3ewg->ReadUint8();
3678     _3ewg->ReadUint8(); // chosen row
3679     _3ewg->ReadUint8(); // unknown
3680     _3ewg->ReadUint8(); // unknown
3681     _3ewg->ReadUint8(); // unknown
3682     KeySwitchRange.low = _3ewg->ReadUint8();
3683     KeySwitchRange.high = _3ewg->ReadUint8();
3684     Controller = _3ewg->ReadUint8();
3685     PlayRange.low = _3ewg->ReadUint8();
3686     PlayRange.high = _3ewg->ReadUint8();
3687    
3688     int n = std::min(int(Articulations), 32);
3689     for (int i = 0 ; i < n ; i++) {
3690     _3ewg->ReadString(pArticulations[i], 32);
3691     }
3692     _3ewg->SetPos(1072);
3693     n = std::min(int(Patterns), 32);
3694     for (int i = 0 ; i < n ; i++) {
3695     _3ewg->ReadString(pPatterns[i].Name, 16);
3696     pPatterns[i].Size = _3ewg->ReadUint8();
3697     _3ewg->Read(&pPatterns[i][0], 1, 32);
3698     }
3699     }
3700    
3701     MidiRuleAlternator::MidiRuleAlternator() :
3702     Articulations(0),
3703     Patterns(0),
3704     Selector(selector_none),
3705     Controller(0),
3706     Polyphonic(false),
3707     Chained(false)
3708     {
3709     PlayRange.low = PlayRange.high = 0;
3710     KeySwitchRange.low = KeySwitchRange.high = 0;
3711     }
3712    
3713     void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3714     pData[32] = 3;
3715     pData[33] = 16;
3716     pData[36] = Articulations;
3717     pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3718     (Selector == selector_controller ? 2 :
3719     (Selector == selector_key_switch ? 1 : 0));
3720     pData[38] = Patterns;
3721    
3722     pData[43] = KeySwitchRange.low;
3723     pData[44] = KeySwitchRange.high;
3724     pData[45] = Controller;
3725     pData[46] = PlayRange.low;
3726     pData[47] = PlayRange.high;
3727    
3728     char* str = reinterpret_cast<char*>(pData);
3729     int pos = 48;
3730     int n = std::min(int(Articulations), 32);
3731     for (int i = 0 ; i < n ; i++, pos += 32) {
3732     strncpy(&str[pos], pArticulations[i].c_str(), 32);
3733     }
3734    
3735     pos = 1072;
3736     n = std::min(int(Patterns), 32);
3737     for (int i = 0 ; i < n ; i++, pos += 49) {
3738     strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3739     pData[pos + 16] = pPatterns[i].Size;
3740     memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3741     }
3742     }
3743    
3744 schoenebeck 2 // *************** Instrument ***************
3745     // *
3746    
3747 schoenebeck 515 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
3748 schoenebeck 1416 static const DLS::Info::string_length_t fixedStringLengths[] = {
3749 persson 1180 { CHUNK_ID_INAM, 64 },
3750     { CHUNK_ID_ISFT, 12 },
3751     { 0, 0 }
3752     };
3753 schoenebeck 1416 pInfo->SetFixedStringLengths(fixedStringLengths);
3754 persson 918
3755 schoenebeck 2 // Initialization
3756     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3757 persson 1182 EffectSend = 0;
3758     Attenuation = 0;
3759     FineTune = 0;
3760     PitchbendRange = 0;
3761     PianoReleaseMode = false;
3762     DimensionKeyRange.low = 0;
3763     DimensionKeyRange.high = 0;
3764 persson 1678 pMidiRules = new MidiRule*[3];
3765     pMidiRules[0] = NULL;
3766 schoenebeck 2
3767     // Loading
3768     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
3769     if (lart) {
3770     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3771     if (_3ewg) {
3772     EffectSend = _3ewg->ReadUint16();
3773     Attenuation = _3ewg->ReadInt32();
3774     FineTune = _3ewg->ReadInt16();
3775     PitchbendRange = _3ewg->ReadInt16();
3776     uint8_t dimkeystart = _3ewg->ReadUint8();
3777     PianoReleaseMode = dimkeystart & 0x01;
3778     DimensionKeyRange.low = dimkeystart >> 1;
3779     DimensionKeyRange.high = _3ewg->ReadUint8();
3780 persson 1627
3781     if (_3ewg->GetSize() > 32) {
3782     // read MIDI rules
3783 persson 1678 int i = 0;
3784 persson 1627 _3ewg->SetPos(32);
3785     uint8_t id1 = _3ewg->ReadUint8();
3786     uint8_t id2 = _3ewg->ReadUint8();
3787    
3788 persson 2450 if (id2 == 16) {
3789     if (id1 == 4) {
3790     pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3791     } else if (id1 == 0) {
3792     pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3793     } else if (id1 == 3) {
3794     pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3795     } else {
3796     pMidiRules[i++] = new MidiRuleUnknown;
3797     }
3798 persson 1627 }
3799 persson 2450 else if (id1 != 0 || id2 != 0) {
3800     pMidiRules[i++] = new MidiRuleUnknown;
3801     }
3802 persson 1627 //TODO: all the other types of rules
3803 persson 1678
3804     pMidiRules[i] = NULL;
3805 persson 1627 }
3806 schoenebeck 2 }
3807     }
3808    
3809 schoenebeck 1524 if (pFile->GetAutoLoad()) {
3810     if (!pRegions) pRegions = new RegionList;
3811     RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3812     if (lrgn) {
3813     RIFF::List* rgn = lrgn->GetFirstSubList();
3814     while (rgn) {
3815     if (rgn->GetListType() == LIST_TYPE_RGN) {
3816     __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3817     pRegions->push_back(new Region(this, rgn));
3818     }
3819     rgn = lrgn->GetNextSubList();
3820 schoenebeck 809 }
3821 schoenebeck 1524 // Creating Region Key Table for fast lookup
3822     UpdateRegionKeyTable();
3823 schoenebeck 2 }
3824     }
3825    
3826 schoenebeck 809 __notify_progress(pProgress, 1.0f); // notify done
3827     }
3828    
3829     void Instrument::UpdateRegionKeyTable() {
3830 schoenebeck 1335 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3831 schoenebeck 823 RegionList::iterator iter = pRegions->begin();
3832     RegionList::iterator end = pRegions->end();
3833     for (; iter != end; ++iter) {
3834     gig::Region* pRegion = static_cast<gig::Region*>(*iter);
3835     for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
3836     RegionKeyTable[iKey] = pRegion;
3837 schoenebeck 2 }
3838     }
3839     }
3840    
3841     Instrument::~Instrument() {
3842 persson 1950 for (int i = 0 ; pMidiRules[i] ; i++) {
3843     delete pMidiRules[i];
3844     }
3845 persson 1678 delete[] pMidiRules;
3846 schoenebeck 2 }
3847    
3848     /**
3849 schoenebeck 809 * Apply Instrument with all its Regions to the respective RIFF chunks.
3850     * You have to call File::Save() to make changes persistent.
3851     *
3852     * Usually there is absolutely no need to call this method explicitly.
3853     * It will be called automatically when File::Save() was called.
3854     *
3855     * @throws gig::Exception if samples cannot be dereferenced
3856     */
3857     void Instrument::UpdateChunks() {
3858     // first update base classes' chunks
3859     DLS::Instrument::UpdateChunks();
3860    
3861     // update Regions' chunks
3862 schoenebeck 823 {
3863     RegionList::iterator iter = pRegions->begin();
3864     RegionList::iterator end = pRegions->end();
3865     for (; iter != end; ++iter)
3866     (*iter)->UpdateChunks();
3867     }
3868 schoenebeck 809
3869     // make sure 'lart' RIFF list chunk exists
3870     RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
3871     if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3872     // make sure '3ewg' RIFF chunk exists
3873     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3874 persson 1264 if (!_3ewg) {
3875     File* pFile = (File*) GetParent();
3876    
3877     // 3ewg is bigger in gig3, as it includes the iMIDI rules
3878     int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3879     _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3880     memset(_3ewg->LoadChunkData(), 0, size);
3881     }
3882 schoenebeck 809 // update '3ewg' RIFF chunk
3883     uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3884 persson 1179 store16(&pData[0], EffectSend);
3885     store32(&pData[2], Attenuation);
3886     store16(&pData[6], FineTune);
3887     store16(&pData[8], PitchbendRange);
3888 persson 1266 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3889 schoenebeck 809 DimensionKeyRange.low << 1;
3890 persson 1179 pData[10] = dimkeystart;
3891     pData[11] = DimensionKeyRange.high;
3892 persson 2450
3893     if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3894     pData[32] = 0;
3895     pData[33] = 0;
3896     } else {
3897     for (int i = 0 ; pMidiRules[i] ; i++) {
3898     pMidiRules[i]->UpdateChunks(pData);
3899     }
3900     }
3901 schoenebeck 809 }
3902    
3903     /**
3904 schoenebeck 2 * Returns the appropriate Region for a triggered note.
3905     *
3906     * @param Key MIDI Key number of triggered note / key (0 - 127)
3907     * @returns pointer adress to the appropriate Region or NULL if there
3908     * there is no Region defined for the given \a Key
3909     */
3910     Region* Instrument::GetRegion(unsigned int Key) {
3911 schoenebeck 1335 if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3912 schoenebeck 2 return RegionKeyTable[Key];
3913 schoenebeck 823
3914 schoenebeck 2 /*for (int i = 0; i < Regions; i++) {
3915     if (Key <= pRegions[i]->KeyRange.high &&
3916     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
3917     }
3918     return NULL;*/
3919     }
3920    
3921     /**
3922     * Returns the first Region of the instrument. You have to call this
3923     * method once before you use GetNextRegion().
3924     *
3925     * @returns pointer address to first region or NULL if there is none
3926     * @see GetNextRegion()
3927     */
3928     Region* Instrument::GetFirstRegion() {
3929 schoenebeck 823 if (!pRegions) return NULL;
3930     RegionsIterator = pRegions->begin();
3931     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3932 schoenebeck 2 }
3933    
3934     /**
3935     * Returns the next Region of the instrument. You have to call
3936     * GetFirstRegion() once before you can use this method. By calling this
3937     * method multiple times it iterates through the available Regions.
3938     *
3939     * @returns pointer address to the next region or NULL if end reached
3940     * @see GetFirstRegion()
3941     */
3942     Region* Instrument::GetNextRegion() {
3943 schoenebeck 823 if (!pRegions) return NULL;
3944     RegionsIterator++;
3945     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3946 schoenebeck 2 }
3947    
3948 schoenebeck 809 Region* Instrument::AddRegion() {
3949     // create new Region object (and its RIFF chunks)
3950     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3951     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3952     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3953     Region* pNewRegion = new Region(this, rgn);
3954 schoenebeck 823 pRegions->push_back(pNewRegion);
3955     Regions = pRegions->size();
3956 schoenebeck 809 // update Region key table for fast lookup
3957     UpdateRegionKeyTable();
3958     // done
3959     return pNewRegion;
3960     }
3961 schoenebeck 2
3962 schoenebeck 809 void Instrument::DeleteRegion(Region* pRegion) {
3963     if (!pRegions) return;
3964 schoenebeck 823 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
3965 schoenebeck 809 // update Region key table for fast lookup
3966     UpdateRegionKeyTable();
3967     }
3968 schoenebeck 2
3969 persson 1627 /**
3970 persson 1678 * Returns a MIDI rule of the instrument.
3971 persson 1627 *
3972     * The list of MIDI rules, at least in gig v3, always contains at
3973     * most two rules. The second rule can only be the DEF filter
3974     * (which currently isn't supported by libgig).
3975     *
3976 persson 1678 * @param i - MIDI rule number
3977     * @returns pointer address to MIDI rule number i or NULL if there is none
3978 persson 1627 */
3979 persson 1678 MidiRule* Instrument::GetMidiRule(int i) {
3980     return pMidiRules[i];
3981 persson 1627 }
3982 persson 2450
3983 schoenebeck 2394 /**
3984 persson 2450 * Adds the "controller trigger" MIDI rule to the instrument.
3985     *
3986     * @returns the new MIDI rule
3987     */
3988     MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3989     delete pMidiRules[0];
3990     MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3991     pMidiRules[0] = r;
3992     pMidiRules[1] = 0;
3993     return r;
3994     }
3995    
3996     /**
3997     * Adds the legato MIDI rule to the instrument.
3998     *
3999     * @returns the new MIDI rule
4000     */
4001     MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4002     delete pMidiRules[0];
4003     MidiRuleLegato* r = new MidiRuleLegato;
4004     pMidiRules[0] = r;
4005     pMidiRules[1] = 0;
4006     return r;
4007     }
4008    
4009     /**
4010     * Adds the alternator MIDI rule to the instrument.
4011     *
4012     * @returns the new MIDI rule
4013     */
4014     MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4015     delete pMidiRules[0];
4016     MidiRuleAlternator* r = new MidiRuleAlternator;
4017     pMidiRules[0] = r;
4018     pMidiRules[1] = 0;
4019     return r;
4020     }
4021    
4022     /**
4023     * Deletes a MIDI rule from the instrument.
4024     *
4025     * @param i - MIDI rule number
4026     */
4027     void Instrument::DeleteMidiRule(int i) {
4028     delete pMidiRules[i];
4029     pMidiRules[i] = 0;
4030     }
4031    
4032     /**
4033 schoenebeck 2394 * Make a (semi) deep copy of the Instrument object given by @a orig
4034     * and assign it to this object.
4035     *
4036     * Note that all sample pointers referenced by @a orig are simply copied as
4037     * memory address. Thus the respective samples are shared, not duplicated!
4038     *
4039     * @param orig - original Instrument object to be copied from
4040     */
4041     void Instrument::CopyAssign(const Instrument* orig) {
4042 schoenebeck 2482 CopyAssign(orig, NULL);
4043     }
4044    
4045     /**
4046     * Make a (semi) deep copy of the Instrument object given by @a orig
4047     * and assign it to this object.
4048     *
4049     * @param orig - original Instrument object to be copied from
4050     * @param mSamples - crosslink map between the foreign file's samples and
4051     * this file's samples
4052     */
4053     void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4054 schoenebeck 2394 // handle base class
4055     // (without copying DLS region stuff)
4056     DLS::Instrument::CopyAssignCore(orig);
4057    
4058     // handle own member variables
4059     Attenuation = orig->Attenuation;
4060     EffectSend = orig->EffectSend;
4061     FineTune = orig->FineTune;
4062     PitchbendRange = orig->PitchbendRange;
4063     PianoReleaseMode = orig->PianoReleaseMode;
4064     DimensionKeyRange = orig->DimensionKeyRange;
4065    
4066     // free old midi rules
4067     for (int i = 0 ; pMidiRules[i] ; i++) {
4068     delete pMidiRules[i];
4069     }
4070     //TODO: MIDI rule copying
4071     pMidiRules[0] = NULL;
4072    
4073     // delete all old regions
4074     while (Regions) DeleteRegion(GetFirstRegion());
4075     // create new regions and copy them from original
4076     {
4077     RegionList::const_iterator it = orig->pRegions->begin();
4078     for (int i = 0; i < orig->Regions; ++i, ++it) {
4079     Region* dstRgn = AddRegion();
4080     //NOTE: Region does semi-deep copy !
4081     dstRgn->CopyAssign(
4082 schoenebeck 2482 static_cast<gig::Region*>(*it),
4083     mSamples
4084 schoenebeck 2394 );
4085     }
4086     }
4087 schoenebeck 809
4088 schoenebeck 2394 UpdateRegionKeyTable();
4089     }
4090 schoenebeck 809
4091 schoenebeck 2394
4092 schoenebeck 929 // *************** Group ***************
4093     // *
4094    
4095     /** @brief Constructor.
4096     *
4097 schoenebeck 930 * @param file - pointer to the gig::File object
4098     * @param ck3gnm - pointer to 3gnm chunk associated with this group or
4099     * NULL if this is a new Group
4100 schoenebeck 929 */
4101 schoenebeck 930 Group::Group(File* file, RIFF::Chunk* ck3gnm) {
4102 schoenebeck 929 pFile = file;
4103     pNameChunk = ck3gnm;
4104     ::LoadString(pNameChunk, Name);
4105     }
4106    
4107     Group::~Group() {
4108 schoenebeck 1099 // remove the chunk associated with this group (if any)
4109     if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4110 schoenebeck 929 }
4111    
4112     /** @brief Update chunks with current group settings.
4113     *
4114 schoenebeck 1098 * Apply current Group field values to the respective chunks. You have
4115     * to call File::Save() to make changes persistent.
4116     *
4117     * Usually there is absolutely no need to call this method explicitly.
4118     * It will be called automatically when File::Save() was called.
4119 schoenebeck 929 */
4120     void Group::UpdateChunks() {
4121     // make sure <3gri> and <3gnl> list chunks exist
4122 schoenebeck 930 RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
4123 persson 1192 if (!_3gri) {
4124     _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
4125     pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4126     }
4127 schoenebeck 929 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4128 persson 1182 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4129 persson 1266
4130     if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
4131     // v3 has a fixed list of 128 strings, find a free one
4132     for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
4133     if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
4134     pNameChunk = ck;
4135     break;
4136     }
4137     }
4138     }
4139    
4140 schoenebeck 929 // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
4141     ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
4142     }
4143    
4144 schoenebeck 930 /**
4145     * Returns the first Sample of this Group. You have to call this method
4146     * once before you use GetNextSample().
4147     *
4148     * <b>Notice:</b> this method might block for a long time, in case the
4149     * samples of this .gig file were not scanned yet
4150     *
4151     * @returns pointer address to first Sample or NULL if there is none
4152     * applied to this Group
4153     * @see GetNextSample()
4154     */
4155     Sample* Group::GetFirstSample() {
4156     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4157     for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
4158     if (pSample->GetGroup() == this) return pSample;
4159     }
4160     return NULL;
4161     }
4162 schoenebeck 929
4163 schoenebeck 930 /**
4164     * Returns the next Sample of the Group. You have to call
4165     * GetFirstSample() once before you can use this method. By calling this
4166     * method multiple times it iterates through the Samples assigned to
4167     * this Group.
4168     *
4169     * @returns pointer address to the next Sample of this Group or NULL if
4170     * end reached
4171     * @see GetFirstSample()
4172     */
4173     Sample* Group::GetNextSample() {
4174     // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4175     for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
4176     if (pSample->GetGroup() == this) return pSample;
4177     }
4178     return NULL;
4179     }
4180 schoenebeck 929
4181 schoenebeck 930 /**
4182     * Move Sample given by \a pSample from another Group to this Group.
4183     */
4184     void Group::AddSample(Sample* pSample) {
4185     pSample->pGroup = this;
4186     }
4187    
4188     /**
4189     * Move all members of this group to another group (preferably the 1st
4190     * one except this). This method is called explicitly by
4191     * File::DeleteGroup() thus when a Group was deleted. This code was
4192     * intentionally not placed in the destructor!
4193     */
4194     void Group::MoveAll() {
4195     // get "that" other group first
4196     Group* pOtherGroup = NULL;
4197     for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
4198     if (pOtherGroup != this) break;
4199     }
4200     if (!pOtherGroup) throw Exception(
4201     "Could not move samples to another group, since there is no "
4202     "other Group. This is a bug, report it!"
4203     );
4204     // now move all samples of this group to the other group
4205     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4206     pOtherGroup->AddSample(pSample);
4207     }
4208     }
4209    
4210    
4211    
4212 schoenebeck 2 // *************** File ***************
4213     // *
4214    
4215 schoenebeck 1384 /// Reflects Gigasampler file format version 2.0 (1998-06-28).
4216 persson 1199 const DLS::version_t File::VERSION_2 = {
4217     0, 2, 19980628 & 0xffff, 19980628 >> 16
4218     };
4219    
4220 schoenebeck 1384 /// Reflects Gigasampler file format version 3.0 (2003-03-31).
4221 persson 1199 const DLS::version_t File::VERSION_3 = {
4222     0, 3, 20030331 & 0xffff, 20030331 >> 16
4223     };
4224    
4225 schoenebeck 1416 static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
4226 persson 1180 { CHUNK_ID_IARL, 256 },
4227     { CHUNK_ID_IART, 128 },
4228     { CHUNK_ID_ICMS, 128 },
4229     { CHUNK_ID_ICMT, 1024 },
4230     { CHUNK_ID_ICOP, 128 },
4231     { CHUNK_ID_ICRD, 128 },
4232     { CHUNK_ID_IENG, 128 },
4233     { CHUNK_ID_IGNR, 128 },
4234     { CHUNK_ID_IKEY, 128 },
4235     { CHUNK_ID_IMED, 128 },
4236     { CHUNK_ID_INAM, 128 },
4237     { CHUNK_ID_IPRD, 128 },
4238     { CHUNK_ID_ISBJ, 128 },
4239     { CHUNK_ID_ISFT, 128 },
4240     { CHUNK_ID_ISRC, 128 },
4241     { CHUNK_ID_ISRF, 128 },
4242     { CHUNK_ID_ITCH, 128 },
4243     { 0, 0 }
4244     };
4245    
4246 schoenebeck 809 File::File() : DLS::File() {
4247 schoenebeck 1524 bAutoLoad = true;
4248 persson 1264 *pVersion = VERSION_3;
4249 schoenebeck 929 pGroups = NULL;
4250 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4251 persson 1182 pInfo->ArchivalLocation = String(256, ' ');
4252 persson 1192
4253     // add some mandatory chunks to get the file chunks in right
4254     // order (INFO chunk will be moved to first position later)
4255     pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
4256     pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
4257 persson 1209 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
4258    
4259     GenerateDLSID();
4260 schoenebeck 809 }
4261    
4262 schoenebeck 2 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
4263 schoenebeck 1524 bAutoLoad = true;
4264 schoenebeck 929 pGroups = NULL;
4265 schoenebeck 1416 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4266 schoenebeck 2 }
4267    
4268 schoenebeck 929 File::~File() {
4269     if (pGroups) {
4270     std::list<Group*>::iterator iter = pGroups->begin();
4271     std::list<Group*>::iterator end = pGroups->end();
4272     while (iter != end) {
4273     delete *iter;
4274     ++iter;
4275     }
4276     delete pGroups;
4277     }
4278     }
4279    
4280 schoenebeck 515 Sample* File::GetFirstSample(progress_t* pProgress) {
4281     if (!pSamples) LoadSamples(pProgress);
4282 schoenebeck 2 if (!pSamples) return NULL;
4283     SamplesIterator = pSamples->begin();
4284     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
4285     }
4286    
4287     Sample* File::GetNextSample() {
4288     if (!pSamples) return NULL;
4289     SamplesIterator++;
4290     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
4291     }
4292 schoenebeck 2482
4293     /**
4294     * Returns Sample object of @a index.
4295     *
4296     * @returns sample object or NULL if index is out of bounds
4297     */
4298     Sample* File::GetSample(uint index) {
4299     if (!pSamples) LoadSamples();
4300     if (!pSamples) return NULL;
4301     DLS::File::SampleList::iterator it = pSamples->begin();
4302     for (int i = 0; i < index; ++i) {
4303     ++it;
4304     if (it == pSamples->end()) return NULL;
4305     }
4306     if (it == pSamples->end()) return NULL;
4307     return static_cast<gig::Sample*>( *it );
4308     }
4309 schoenebeck 2
4310 schoenebeck 809 /** @brief Add a new sample.
4311     *
4312     * This will create a new Sample object for the gig file. You have to
4313     * call Save() to make this persistent to the file.
4314     *
4315     * @returns pointer to new Sample object
4316     */
4317     Sample* File::AddSample() {
4318     if (!pSamples) LoadSamples();
4319     __ensureMandatoryChunksExist();
4320     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
4321     // create new Sample object and its respective 'wave' list chunk
4322     RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
4323     Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
4324 persson 1192
4325     // add mandatory chunks to get the chunks in right order
4326     wave->AddSubChunk(CHUNK_ID_FMT, 16);
4327     wave->AddSubList(LIST_TYPE_INFO);
4328    
4329 schoenebeck 809 pSamples->push_back(pSample);
4330     return pSample;
4331     }
4332    
4333     /** @brief Delete a sample.
4334     *
4335 schoenebeck 1292 * This will delete the given Sample object from the gig file. Any
4336     * references to this sample from Regions and DimensionRegions will be
4337     * removed. You have to call Save() to make this persistent to the file.
4338 schoenebeck 809 *
4339     * @param pSample - sample to delete
4340     * @throws gig::Exception if given sample could not be found
4341     */
4342     void File::DeleteSample(Sample* pSample) {
4343 schoenebeck 823 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
4344     SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
4345 schoenebeck 809 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
4346 schoenebeck 1083 if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
4347 schoenebeck 809 pSamples->erase(iter);
4348     delete pSample;
4349 persson 1266
4350 persson 1678 SampleList::iterator tmp = SamplesIterator;
4351 persson 1266 // remove all references to the sample
4352     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4353     instrument = GetNextInstrument()) {
4354     for (Region* region = instrument->GetFirstRegion() ; region ;
4355     region = instrument->GetNextRegion()) {
4356    
4357     if (region->GetSample() == pSample) region->SetSample(NULL);
4358    
4359     for (int i = 0 ; i < region->DimensionRegions ; i++) {
4360     gig::DimensionRegion *d = region->pDimensionRegions[i];
4361     if (d->pSample == pSample) d->pSample = NULL;
4362     }
4363     }
4364     }
4365 persson 1678 SamplesIterator = tmp; // restore iterator
4366 schoenebeck 809 }
4367    
4368 schoenebeck 823 void File::LoadSamples() {
4369     LoadSamples(NULL);
4370     }
4371    
4372 schoenebeck 515 void File::LoadSamples(progress_t* pProgress) {
4373 schoenebeck 930 // Groups must be loaded before samples, because samples will try
4374     // to resolve the group they belong to
4375 schoenebeck 1158 if (!pGroups) LoadGroups();
4376 schoenebeck 930
4377 schoenebeck 823 if (!pSamples) pSamples = new SampleList;
4378    
4379 persson 666 RIFF::File* file = pRIFF;
4380 schoenebeck 515
4381 persson 666 // just for progress calculation
4382     int iSampleIndex = 0;
4383     int iTotalSamples = WavePoolCount;
4384 schoenebeck 515
4385 persson 666 // check if samples should be loaded from extension files
4386     int lastFileNo = 0;
4387     for (int i = 0 ; i < WavePoolCount ; i++) {
4388     if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
4389     }
4390 schoenebeck 780 String name(pRIFF->GetFileName());
4391     int nameLen = name.length();
4392 persson 666 char suffix[6];
4393 schoenebeck 780 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
4394 schoenebeck 515
4395 persson 666 for (int fileNo = 0 ; ; ) {
4396     RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
4397     if (wvpl) {
4398     unsigned long wvplFileOffset = wvpl->GetFilePos();
4399     RIFF::List* wave = wvpl->GetFirstSubList();
4400     while (wave) {
4401     if (wave->GetListType() == LIST_TYPE_WAVE) {
4402     // notify current progress
4403     const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
4404     __notify_progress(pProgress, subprogress);
4405    
4406     unsigned long waveFileOffset = wave->GetFilePos();
4407     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
4408    
4409     iSampleIndex++;
4410     }
4411     wave = wvpl->GetNextSubList();
4412 schoenebeck 2 }
4413 persson 666
4414     if (fileNo == lastFileNo) break;
4415    
4416     // open extension file (*.gx01, *.gx02, ...)
4417     fileNo++;
4418     sprintf(suffix, ".gx%02d", fileNo);
4419     name.replace(nameLen, 5, suffix);
4420     file = new RIFF::File(name);
4421     ExtensionFiles.push_back(file);
4422 schoenebeck 823 } else break;
4423 schoenebeck 2 }
4424 persson 666
4425     __notify_progress(pProgress, 1.0); // notify done
4426 schoenebeck 2 }
4427    
4428     Instrument* File::GetFirstInstrument() {
4429     if (!pInstruments) LoadInstruments();
4430     if (!pInstruments) return NULL;
4431     InstrumentsIterator = pInstruments->begin();
4432 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
4433 schoenebeck 2 }
4434    
4435     Instrument* File::GetNextInstrument() {
4436     if (!pInstruments) return NULL;
4437     InstrumentsIterator++;
4438 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
4439 schoenebeck 2 }
4440    
4441 schoenebeck 21 /**
4442     * Returns the instrument with the given index.
4443     *
4444 schoenebeck 515 * @param index - number of the sought instrument (0..n)
4445     * @param pProgress - optional: callback function for progress notification
4446 schoenebeck 21 * @returns sought instrument or NULL if there's no such instrument
4447     */
4448 schoenebeck 515 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
4449     if (!pInstruments) {
4450     // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
4451    
4452     // sample loading subtask
4453     progress_t subprogress;
4454     __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
4455     __notify_progress(&subprogress, 0.0f);
4456 schoenebeck 1524 if (GetAutoLoad())
4457     GetFirstSample(&subprogress); // now force all samples to be loaded
4458 schoenebeck 515 __notify_progress(&subprogress, 1.0f);
4459    
4460     // instrument loading subtask
4461     if (pProgress && pProgress->callback) {
4462     subprogress.__range_min = subprogress.__range_max;
4463     subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
4464     }
4465     __notify_progress(&subprogress, 0.0f);
4466     LoadInstruments(&subprogress);
4467     __notify_progress(&subprogress, 1.0f);
4468     }
4469 schoenebeck 21 if (!pInstruments) return NULL;
4470     InstrumentsIterator = pInstruments->begin();
4471     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
4472 schoenebeck 823 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
4473 schoenebeck 21 InstrumentsIterator++;
4474     }
4475     return NULL;
4476     }
4477    
4478 schoenebeck 809 /** @brief Add a new instrument definition.
4479     *
4480     * This will create a new Instrument object for the gig file. You have
4481     * to call Save() to make this persistent to the file.
4482     *
4483     * @returns pointer to new Instrument object
4484     */
4485     Instrument* File::AddInstrument() {
4486     if (!pInstruments) LoadInstruments();
4487     __ensureMandatoryChunksExist();
4488     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4489     RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4490 persson 1192
4491     // add mandatory chunks to get the chunks in right order
4492     lstInstr->AddSubList(LIST_TYPE_INFO);
4493 persson 1209 lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4494 persson 1192
4495 schoenebeck 809 Instrument* pInstrument = new Instrument(this, lstInstr);
4496 persson 1209 pInstrument->GenerateDLSID();
4497 persson 1182
4498 persson 1192 lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4499    
4500 persson 1182 // this string is needed for the gig to be loadable in GSt:
4501     pInstrument->pInfo->Software = "Endless Wave";
4502    
4503 schoenebeck 809 pInstruments->push_back(pInstrument);
4504     return pInstrument;
4505     }
4506 schoenebeck 2394
4507     /** @brief Add a duplicate of an existing instrument.
4508     *
4509     * Duplicates the instrument definition given by @a orig and adds it
4510     * to this file. This allows in an instrument editor application to
4511     * easily create variations of an instrument, which will be stored in
4512     * the same .gig file, sharing i.e. the same samples.
4513     *
4514     * Note that all sample pointers referenced by @a orig are simply copied as
4515     * memory address. Thus the respective samples are shared, not duplicated!
4516     *
4517     * You have to call Save() to make this persistent to the file.
4518     *
4519     * @param orig - original instrument to be copied
4520     * @returns duplicated copy of the given instrument
4521     */
4522     Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4523     Instrument* instr = AddInstrument();
4524     instr->CopyAssign(orig);
4525     return instr;
4526     }
4527 schoenebeck 2482
4528     /** @brief Add content of another existing file.
4529     *
4530     * Duplicates the samples, groups and instruments of the original file
4531     * given by @a pFile and adds them to @c this File. In case @c this File is
4532     * a new one that you haven't saved before, then you have to call
4533     * SetFileName() before calling AddContentOf(), because this method will
4534     * automatically save this file during operation, which is required for
4535     * writing the sample waveform data by disk streaming.
4536     *
4537     * @param pFile - original file whose's content shall be copied from
4538     */
4539     void File::AddContentOf(File* pFile) {
4540     static int iCallCount = -1;
4541     iCallCount++;
4542     std::map<Group*,Group*> mGroups;
4543     std::map<Sample*,Sample*> mSamples;
4544    
4545     // clone sample groups
4546     for (int i = 0; pFile->GetGroup(i); ++i) {
4547     Group* g = AddGroup();
4548     g->Name =
4549     "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4550     mGroups[pFile->GetGroup(i)] = g;
4551     }
4552    
4553     // clone samples (not waveform data here yet)
4554     for (int i = 0; pFile->GetSample(i); ++i) {
4555     Sample* s = AddSample();
4556     s->CopyAssignMeta(pFile->GetSample(i));
4557     mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4558     mSamples[pFile->GetSample(i)] = s;
4559     }
4560    
4561     //BUG: For some reason this method only works with this additional
4562     // Save() call in between here.
4563     //
4564     // Important: The correct one of the 2 Save() methods has to be called
4565     // here, depending on whether the file is completely new or has been
4566     // saved to disk already, otherwise it will result in data corruption.
4567     if (pRIFF->IsNew())
4568     Save(GetFileName());
4569     else
4570     Save();
4571    
4572     // clone instruments
4573     // (passing the crosslink table here for the cloned samples)
4574     for (int i = 0; pFile->GetInstrument(i); ++i) {
4575     Instrument* instr = AddInstrument();
4576     instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4577     }
4578    
4579     // Mandatory: file needs to be saved to disk at this point, so this
4580     // file has the correct size and data layout for writing the samples'
4581     // waveform data to disk.
4582     Save();
4583    
4584     // clone samples' waveform data
4585     // (using direct read & write disk streaming)
4586     for (int i = 0; pFile->GetSample(i); ++i) {
4587     mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4588     }
4589     }
4590 schoenebeck 809
4591     /** @brief Delete an instrument.
4592     *
4593     * This will delete the given Instrument object from the gig file. You
4594     * have to call Save() to make this persistent to the file.
4595     *
4596     * @param pInstrument - instrument to delete
4597 schoenebeck 1081 * @throws gig::Exception if given instrument could not be found
4598 schoenebeck 809 */
4599     void File::DeleteInstrument(Instrument* pInstrument) {
4600     if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
4601 schoenebeck 823 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
4602 schoenebeck 809 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
4603     pInstruments->erase(iter);
4604     delete pInstrument;
4605     }
4606    
4607 schoenebeck 823 void File::LoadInstruments() {
4608     LoadInstruments(NULL);
4609     }
4610    
4611 schoenebeck 515 void File::LoadInstruments(progress_t* pProgress) {
4612 schoenebeck 823 if (!pInstruments) pInstruments = new InstrumentList;
4613 schoenebeck 2 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4614     if (lstInstruments) {
4615 schoenebeck 515 int iInstrumentIndex = 0;
4616 schoenebeck 2 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
4617     while (lstInstr) {
4618     if (lstInstr->GetListType() == LIST_TYPE_INS) {
4619 schoenebeck 515 // notify current progress
4620     const float localProgress = (float) iInstrumentIndex / (float) Instruments;
4621     __notify_progress(pProgress, localProgress);
4622    
4623     // divide local progress into subprogress for loading current Instrument
4624     progress_t subprogress;
4625     __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
4626    
4627     pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
4628    
4629     iInstrumentIndex++;
4630 schoenebeck 2 }
4631     lstInstr = lstInstruments->GetNextSubList();
4632     }
4633 schoenebeck 515 __notify_progress(pProgress, 1.0); // notify done
4634 schoenebeck 2 }
4635     }
4636    
4637 persson 1207 /// Updates the 3crc chunk with the checksum of a sample. The
4638     /// update is done directly to disk, as this method is called
4639     /// after File::Save()
4640 persson 1199 void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4641     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4642     if (!_3crc) return;
4643 persson 1207
4644     // get the index of the sample
4645 persson 1199 int iWaveIndex = -1;
4646     File::SampleList::iterator iter = pSamples->begin();
4647     File::SampleList::iterator end = pSamples->end();
4648     for (int index = 0; iter != end; ++iter, ++index) {
4649     if (*iter == pSample) {
4650     iWaveIndex = index;
4651     break;
4652     }
4653     }
4654     if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4655    
4656 persson 1207 // write the CRC-32 checksum to disk
4657 persson 1199 _3crc->SetPos(iWaveIndex * 8);
4658     uint32_t tmp = 1;
4659     _3crc->WriteUint32(&tmp); // unknown, always 1?
4660     _3crc->WriteUint32(&crc);
4661     }
4662    
4663 schoenebeck 929 Group* File::GetFirstGroup() {
4664     if (!pGroups) LoadGroups();
4665 schoenebeck 930 // there must always be at least one group
4666 schoenebeck 929 GroupsIterator = pGroups->begin();
4667 schoenebeck 930 return *GroupsIterator;
4668 schoenebeck 929 }
4669 schoenebeck 2
4670 schoenebeck 929 Group* File::GetNextGroup() {
4671     if (!pGroups) return NULL;
4672     ++GroupsIterator;
4673     return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
4674     }
4675 schoenebeck 2
4676 schoenebeck 929 /**
4677     * Returns the group with the given index.
4678     *
4679     * @param index - number of the sought group (0..n)
4680     * @returns sought group or NULL if there's no such group
4681     */
4682     Group* File::GetGroup(uint index) {
4683     if (!pGroups) LoadGroups();
4684     GroupsIterator = pGroups->begin();
4685     for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4686     if (i == index) return *GroupsIterator;
4687     ++GroupsIterator;
4688     }
4689     return NULL;
4690     }
4691    
4692 schoenebeck 2543 /**
4693     * Returns the group with the given group name.
4694     *
4695     * Note: group names don't have to be unique in the gig format! So there
4696     * can be multiple groups with the same name. This method will simply
4697     * return the first group found with the given name.
4698     *
4699     * @param name - name of the sought group
4700     * @returns sought group or NULL if there's no group with that name
4701     */
4702     Group* File::GetGroup(String name) {
4703     if (!pGroups) LoadGroups();
4704     GroupsIterator = pGroups->begin();
4705     for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
4706     if ((*GroupsIterator)->Name == name) return *GroupsIterator;
4707     return NULL;
4708     }
4709    
4710 schoenebeck 929 Group* File::AddGroup() {
4711     if (!pGroups) LoadGroups();
4712 schoenebeck 930 // there must always be at least one group
4713 schoenebeck 929 __ensureMandatoryChunksExist();
4714 schoenebeck 930 Group* pGroup = new Group(this, NULL);
4715 schoenebeck 929 pGroups->push_back(pGroup);
4716     return pGroup;
4717     }
4718    
4719 schoenebeck 1081 /** @brief Delete a group and its samples.
4720     *
4721     * This will delete the given Group object and all the samples that
4722     * belong to this group from the gig file. You have to call Save() to
4723     * make this persistent to the file.
4724     *
4725     * @param pGroup - group to delete
4726     * @throws gig::Exception if given group could not be found
4727     */
4728 schoenebeck 929 void File::DeleteGroup(Group* pGroup) {
4729 schoenebeck 930 if (!pGroups) LoadGroups();
4730 schoenebeck 929 std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4731     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4732 schoenebeck 930 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4733 schoenebeck 1081 // delete all members of this group
4734     for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
4735     DeleteSample(pSample);
4736     }
4737     // now delete this group object
4738     pGroups->erase(iter);
4739     delete pGroup;
4740     }
4741    
4742     /** @brief Delete a group.
4743     *
4744     * This will delete the given Group object from the gig file. All the
4745     * samples that belong to this group will not be deleted, but instead
4746     * be moved to another group. You have to call Save() to make this
4747     * persistent to the file.
4748     *
4749     * @param pGroup - group to delete
4750     * @throws gig::Exception if given group could not be found
4751     */
4752     void File::DeleteGroupOnly(Group* pGroup) {
4753     if (!pGroups) LoadGroups();
4754     std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4755     if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4756     if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4757 schoenebeck 930 // move all members of this group to another group
4758     pGroup->MoveAll();
4759 schoenebeck 929 pGroups->erase(iter);
4760     delete pGroup;
4761     }
4762    
4763     void File::LoadGroups() {
4764     if (!pGroups) pGroups = new std::list<Group*>;
4765 schoenebeck 930 // try to read defined groups from file
4766 schoenebeck 929 RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4767 schoenebeck 930 if (lst3gri) {
4768     RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
4769     if (lst3gnl) {
4770     RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4771     while (ck) {
4772     if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4773 persson 1266 if (pVersion && pVersion->major == 3 &&
4774     strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4775    
4776 schoenebeck 930 pGroups->push_back(new Group(this, ck));
4777     }
4778     ck = lst3gnl->GetNextSubChunk();
4779 schoenebeck 929 }
4780     }
4781     }
4782 schoenebeck 930 // if there were no group(s), create at least the mandatory default group
4783     if (!pGroups->size()) {
4784     Group* pGroup = new Group(this, NULL);
4785     pGroup->Name = "Default Group";
4786     pGroups->push_back(pGroup);
4787     }
4788 schoenebeck 929 }
4789    
4790 schoenebeck 1098 /**
4791     * Apply all the gig file's current instruments, samples, groups and settings
4792     * to the respective RIFF chunks. You have to call Save() to make changes
4793     * persistent.
4794     *
4795     * Usually there is absolutely no need to call this method explicitly.
4796     * It will be called automatically when File::Save() was called.
4797     *
4798     * @throws Exception - on errors
4799     */
4800     void File::UpdateChunks() {
4801 persson 1199 bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4802 persson 1192
4803 persson 1247 b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4804    
4805 schoenebeck 1098 // first update base class's chunks
4806     DLS::File::UpdateChunks();
4807 schoenebeck 929
4808 persson 1199 if (newFile) {
4809 persson 1192 // INFO was added by Resource::UpdateChunks - make sure it
4810     // is placed first in file
4811 persson 1199 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4812 persson 1192 RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4813     if (first != info) {
4814     pRIFF->MoveSubChunk(info, first);
4815     }
4816     }
4817    
4818 schoenebeck 1098 // update group's chunks
4819     if (pGroups) {
4820 schoenebeck 2467 // make sure '3gri' and '3gnl' list chunks exist
4821     // (before updating the Group chunks)
4822     RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4823     if (!_3gri) {
4824     _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4825     pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4826 schoenebeck 1098 }
4827 schoenebeck 2467 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4828     if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4829 persson 1266
4830     // v3: make sure the file has 128 3gnm chunks
4831 schoenebeck 2467 // (before updating the Group chunks)
4832 persson 1266 if (pVersion && pVersion->major == 3) {
4833     RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4834     for (int i = 0 ; i < 128 ; i++) {
4835     if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4836     if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4837     }
4838     }
4839 schoenebeck 2467
4840     std::list<Group*>::iterator iter = pGroups->begin();
4841     std::list<Group*>::iterator end = pGroups->end();
4842     for (; iter != end; ++iter) {
4843     (*iter)->UpdateChunks();
4844     }
4845 schoenebeck 1098 }
4846 persson 1199
4847     // update einf chunk
4848    
4849     // The einf chunk contains statistics about the gig file, such
4850     // as the number of regions and samples used by each
4851     // instrument. It is divided in equally sized parts, where the
4852     // first part contains information about the whole gig file,
4853     // and the rest of the parts map to each instrument in the
4854     // file.
4855     //
4856     // At the end of each part there is a bit map of each sample
4857     // in the file, where a set bit means that the sample is used
4858     // by the file/instrument.
4859     //
4860     // Note that there are several fields with unknown use. These
4861     // are set to zero.
4862    
4863     int sublen = pSamples->size() / 8 + 49;
4864     int einfSize = (Instruments + 1) * sublen;
4865    
4866     RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4867     if (einf) {
4868     if (einf->GetSize() != einfSize) {
4869     einf->Resize(einfSize);
4870     memset(einf->LoadChunkData(), 0, einfSize);
4871     }
4872     } else if (newFile) {
4873     einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4874     }
4875     if (einf) {
4876     uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4877    
4878     std::map<gig::Sample*,int> sampleMap;
4879     int sampleIdx = 0;
4880     for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4881     sampleMap[pSample] = sampleIdx++;
4882     }
4883    
4884     int totnbusedsamples = 0;
4885     int totnbusedchannels = 0;
4886     int totnbregions = 0;
4887     int totnbdimregions = 0;
4888 persson 1264 int totnbloops = 0;
4889 persson 1199 int instrumentIdx = 0;
4890    
4891     memset(&pData[48], 0, sublen - 48);
4892    
4893     for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4894     instrument = GetNextInstrument()) {
4895     int nbusedsamples = 0;
4896     int nbusedchannels = 0;
4897     int nbdimregions = 0;
4898 persson 1264 int nbloops = 0;
4899 persson 1199
4900     memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4901    
4902     for (Region* region = instrument->GetFirstRegion() ; region ;
4903     region = instrument->GetNextRegion()) {
4904     for (int i = 0 ; i < region->DimensionRegions ; i++) {
4905     gig::DimensionRegion *d = region->pDimensionRegions[i];
4906     if (d->pSample) {
4907     int sampleIdx = sampleMap[d->pSample];
4908     int byte = 48 + sampleIdx / 8;
4909     int bit = 1 << (sampleIdx & 7);
4910     if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4911     pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4912     nbusedsamples++;
4913     nbusedchannels += d->pSample->Channels;
4914    
4915     if ((pData[byte] & bit) == 0) {
4916     pData[byte] |= bit;
4917     totnbusedsamples++;
4918     totnbusedchannels += d->pSample->Channels;
4919     }
4920     }
4921     }
4922 persson 1264 if (d->SampleLoops) nbloops++;
4923 persson 1199 }
4924     nbdimregions += region->DimensionRegions;
4925     }
4926     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4927     // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4928     store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4929     store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4930     store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4931     store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4932     store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4933 persson 1264 store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4934     // next 8 bytes unknown
4935 persson 1199 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4936     store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4937     // next 4 bytes unknown
4938    
4939     totnbregions += instrument->Regions;
4940     totnbdimregions += nbdimregions;
4941 persson 1264 totnbloops += nbloops;
4942 persson 1199 instrumentIdx++;
4943     }
4944     // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4945     // store32(&pData[0], sublen);
4946     store32(&pData[4], totnbusedchannels);
4947     store32(&pData[8], totnbusedsamples);
4948     store32(&pData[12], Instruments);
4949     store32(&pData[16], totnbregions);
4950     store32(&pData[20], totnbdimregions);
4951 persson 1264 store32(&pData[24], totnbloops);
4952     // next 8 bytes unknown
4953     // next 4 bytes unknown, not always 0
4954 persson 1199 store32(&pData[40], pSamples->size());
4955     // next 4 bytes unknown
4956     }
4957    
4958     // update 3crc chunk
4959    
4960     // The 3crc chunk contains CRC-32 checksums for the
4961     // samples. The actual checksum values will be filled in
4962     // later, by Sample::Write.
4963    
4964     RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4965     if (_3crc) {
4966     _3crc->Resize(pSamples->size() * 8);
4967     } else if (newFile) {
4968     _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4969     _3crc->LoadChunkData();
4970 persson 1264
4971     // the order of einf and 3crc is not the same in v2 and v3
4972     if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4973 persson 1199 }
4974 schoenebeck 1098 }
4975 schoenebeck 929
4976 schoenebeck 1524 /**
4977     * Enable / disable automatic loading. By default this properyt is
4978     * enabled and all informations are loaded automatically. However
4979     * loading all Regions, DimensionRegions and especially samples might
4980     * take a long time for large .gig files, and sometimes one might only
4981     * be interested in retrieving very superficial informations like the
4982     * amount of instruments and their names. In this case one might disable
4983     * automatic loading to avoid very slow response times.
4984     *
4985     * @e CAUTION: by disabling this property many pointers (i.e. sample
4986     * references) and informations will have invalid or even undefined
4987     * data! This feature is currently only intended for retrieving very
4988     * superficial informations in a very fast way. Don't use it to retrieve
4989     * details like synthesis informations or even to modify .gig files!
4990     */
4991     void File::SetAutoLoad(bool b) {
4992     bAutoLoad = b;
4993     }
4994 schoenebeck 1098
4995 schoenebeck 1524 /**
4996     * Returns whether automatic loading is enabled.
4997     * @see SetAutoLoad()
4998     */
4999     bool File::GetAutoLoad() {
5000     return bAutoLoad;
5001     }
5002 schoenebeck 1098
5003 schoenebeck 1524
5004    
5005 schoenebeck 2 // *************** Exception ***************
5006     // *
5007    
5008     Exception::Exception(String Message) : DLS::Exception(Message) {
5009     }
5010    
5011     void Exception::PrintMessage() {
5012     std::cout << "gig::Exception: " << Message << std::endl;
5013     }
5014    
5015 schoenebeck 518
5016     // *************** functions ***************
5017     // *
5018    
5019     /**
5020     * Returns the name of this C++ library. This is usually "libgig" of
5021     * course. This call is equivalent to RIFF::libraryName() and
5022     * DLS::libraryName().
5023     */
5024     String libraryName() {
5025     return PACKAGE;
5026     }
5027    
5028     /**
5029     * Returns version of this C++ library. This call is equivalent to
5030     * RIFF::libraryVersion() and DLS::libraryVersion().
5031     */
5032     String libraryVersion() {
5033     return VERSION;
5034     }
5035    
5036 schoenebeck 2 } // namespace gig

  ViewVC Help
Powered by ViewVC