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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2482 - (hide annotations) (download)
Mon Nov 25 02:22:38 2013 UTC (10 years, 4 months ago) by schoenebeck
File size: 195665 byte(s)
* Added new command line tool "gigmerge" which allows to merge
  a list of gig files to one single gig file.
* Added new "man" page for new tool "gigmerge".
* src/gig.h: Added new method File::AddContentOf().
* src/DLS.h: Added new method File::SetFileName().
* src/RIFF.h: Added new method File::SetFileName().
* src/RIFF.h: Added new method File::IsNew().
* Added "const" keyword to several methods.
* Bumped version to 3.3.0.svn6.

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

  ViewVC Help
Powered by ViewVC