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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3140 - (show annotations) (download)
Wed May 3 16:19:53 2017 UTC (6 years, 10 months ago) by schoenebeck
File size: 281476 byte(s)
- gig.h: Don't include Serialization.h by default.

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

  ViewVC Help
Powered by ViewVC