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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2990 - (show annotations) (download)
Sat Sep 24 15:02:28 2016 UTC (7 years, 6 months ago) by schoenebeck
File size: 277005 byte(s)
* gig.cpp: Changed default value of DimensionRegion::EG2Release
  (filter release time) to 60s.
* Bumped version (4.0.0.svn10).

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

  ViewVC Help
Powered by ViewVC