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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2912 - (show annotations) (download)
Tue May 17 14:30:10 2016 UTC (7 years, 11 months ago) by schoenebeck
File size: 270839 byte(s)
* gig.cpp/.h: GIG FORMAT EXTENSION: Added support for saving gig file
  larger than 4 GB as one single monolithic gig file. A new custom RIFF
  chunk "FFmt" was added to distinguish such monolithic large .gig files
  from old ones which were splitted over several (.gx01, .gx02, ...)
  "extension" files before.
* DLS.cpp/.h: Sample class: wave pool offsets are now 64 bits (to allow
  support for files larger than 4 GB).
* RIFF.cpp/.h: Addded support for RIFF files larger than 4 GB, by default
  the required internal RIFF file offset size is automatically detected
  (that is RIFF files < 4 GB automatically use 32 bit offsets while
  files >= 4 GB automatically use 64 bit offsets), a particular offset
  size can be forced with a new option added to the RIFF File constructor
  though.
* RIFF.cpp/.h: When saving a modified, grown RIFF file, the temporary file
  size during Save() operation will no longer be larger than the final
  grown file size.
* Automake: Set environment variable GCC_COLORS=auto to allow GCC to auto
  detect whether it (sh/c)ould output its messages in color.
* Bumped version (4.0.0.svn3).

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

  ViewVC Help
Powered by ViewVC