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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3138 - (show annotations) (download)
Wed May 3 14:41:58 2017 UTC (6 years, 10 months ago) by schoenebeck
File size: 281449 byte(s)
* Added new "Serialization" framework (and equally named namespace)
  which allows to serialize and deserialize native C++ objects
  in a portable, easy and flexible way.
* gig.cpp/gig.h: Added support for serializing & deserializing
  DimensionRegion objects (and crossfade_t and leverage_ctrl_t
  objects).
* Bumped version (4.0.0.svn15).

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

  ViewVC Help
Powered by ViewVC