libgig 4.6.1
gig.cpp
1/***************************************************************************
2 * *
3 * libgig - C++ cross-platform Gigasampler format file access library *
4 * *
5 * Copyright (C) 2003-2026 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
36#define GIG_FILE_EXT_VERSION 2
37
43#define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
44
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
62namespace gig {
63
64// *************** Internal functions for sample decompression ***************
65// *
66
67namespace {
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// *************** Other Internal functions ***************
237// *
238
239 static split_type_t __resolveSplitType(dimension_t dimension) {
240 return (
241 dimension == dimension_layer ||
242 dimension == dimension_samplechannel ||
243 dimension == dimension_releasetrigger ||
244 dimension == dimension_keyboard ||
245 dimension == dimension_roundrobin ||
246 dimension == dimension_random ||
247 dimension == dimension_smartmidi ||
250 }
251
252 static int __resolveZoneSize(dimension_def_t& dimension_definition) {
253 return (dimension_definition.split_type == split_type_normal)
254 ? int(128.0 / dimension_definition.zones) : 0;
255 }
256
257
258
259// *************** leverage_ctrl_t ***************
260// *
261
262 void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
263 SRLZ(type);
264 SRLZ(controller_number);
265 }
266
267
268
269// *************** crossfade_t ***************
270// *
271
272 void crossfade_t::serialize(Serialization::Archive* archive) {
273 SRLZ(in_start);
274 SRLZ(in_end);
275 SRLZ(out_start);
276 SRLZ(out_end);
277 }
278
279
280
281// *************** eg_opt_t ***************
282// *
283
284 eg_opt_t::eg_opt_t() {
285 AttackCancel = true;
286 AttackHoldCancel = true;
287 Decay1Cancel = true;
288 Decay2Cancel = true;
289 ReleaseCancel = true;
290 }
291
292 void eg_opt_t::serialize(Serialization::Archive* archive) {
293 SRLZ(AttackCancel);
294 SRLZ(AttackHoldCancel);
295 SRLZ(Decay1Cancel);
296 SRLZ(Decay2Cancel);
297 SRLZ(ReleaseCancel);
298 }
299
300
301
302// *************** Sample ***************
303// *
304
305 size_t Sample::Instances = 0;
307
327 Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
328 : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
329 {
330 static const DLS::Info::string_length_t fixedStringLengths[] = {
331 { CHUNK_ID_INAM, 64 },
332 { 0, 0 }
333 };
334 pInfo->SetFixedStringLengths(fixedStringLengths);
335 Instances++;
336 FileNo = fileNo;
337
338 __resetCRC(crc);
339 // if this is not a new sample, try to get the sample's already existing
340 // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
341 // checksum of the time when the sample was consciously modified by the
342 // user for the last time (by calling Sample::Write() that is).
343 if (index >= 0) { // not a new file ...
344 try {
345 uint32_t crc = pFile->GetSampleChecksumByIndex(index);
346 this->crc = crc;
347 } catch (...) {}
348 }
349
350 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
351 if (pCk3gix) {
352 pCk3gix->SetPos(0);
353
354 uint16_t iSampleGroup = pCk3gix->ReadInt16();
355 pGroup = pFile->GetGroup(iSampleGroup);
356 } else { // '3gix' chunk missing
357 // by default assigned to that mandatory "Default Group"
358 pGroup = pFile->GetGroup(0);
359 }
360
361 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
362 if (pCkSmpl) {
363 pCkSmpl->SetPos(0);
364
365 Manufacturer = pCkSmpl->ReadInt32();
366 Product = pCkSmpl->ReadInt32();
367 SamplePeriod = pCkSmpl->ReadInt32();
368 MIDIUnityNote = pCkSmpl->ReadInt32();
369 FineTune = pCkSmpl->ReadInt32();
370 pCkSmpl->Read(&SMPTEFormat, 1, 4);
371 SMPTEOffset = pCkSmpl->ReadInt32();
372 Loops = pCkSmpl->ReadInt32();
373 pCkSmpl->ReadInt32(); // manufByt
374 LoopID = pCkSmpl->ReadInt32();
375 pCkSmpl->Read(&LoopType, 1, 4);
376 LoopStart = pCkSmpl->ReadInt32();
377 LoopEnd = pCkSmpl->ReadInt32();
378 LoopFraction = pCkSmpl->ReadInt32();
379 LoopPlayCount = pCkSmpl->ReadInt32();
380 } else { // 'smpl' chunk missing
381 // use default values
382 Manufacturer = 0;
383 Product = 0;
384 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
385 MIDIUnityNote = 60;
386 FineTune = 0;
388 SMPTEOffset = 0;
389 Loops = 0;
390 LoopID = 0;
392 LoopStart = 0;
393 LoopEnd = 0;
394 LoopFraction = 0;
395 LoopPlayCount = 0;
396 }
397
398 FrameTable = NULL;
399 SamplePos = 0;
400 RAMCache.Size = 0;
401 RAMCache.pStart = NULL;
403
404 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
405
406 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
407 Compressed = ewav;
408 Dithered = false;
409 TruncatedBits = 0;
410 if (Compressed) {
411 ewav->SetPos(0);
412
413 uint32_t version = ewav->ReadInt32();
414 if (version > 2 && BitDepth == 24) {
415 Dithered = ewav->ReadInt32();
416 ewav->SetPos(Channels == 2 ? 84 : 64);
417 TruncatedBits = ewav->ReadInt32();
418 }
419 ScanCompressedSample();
420 }
421
422 // we use a buffer for decompression only
424 InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
425 InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
426 }
427 FrameOffset = 0; // just for streaming compressed samples
428
429 LoopSize = LoopEnd - LoopStart + 1;
430 }
431
447 void Sample::CopyAssignMeta(const Sample* orig) {
448 // handle base classes
450
451 // handle actual own attributes of this class
453 Product = orig->Product;
456 FineTune = orig->FineTune;
457 SMPTEFormat = orig->SMPTEFormat;
458 SMPTEOffset = orig->SMPTEOffset;
459 Loops = orig->Loops;
460 LoopID = orig->LoopID;
461 LoopType = orig->LoopType;
462 LoopStart = orig->LoopStart;
463 LoopEnd = orig->LoopEnd;
464 LoopSize = orig->LoopSize;
467
468 // schedule resizing this sample to the given sample's size
469 Resize(orig->GetSize());
470 }
471
483 void Sample::CopyAssignWave(const Sample* orig) {
484 const int iReadAtOnce = 32*1024;
485 char* buf = new char[iReadAtOnce * orig->FrameSize];
486 Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
487 file_offset_t restorePos = pOrig->GetPos();
488 pOrig->SetPos(0);
489 SetPos(0);
490 for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
491 n = pOrig->Read(buf, iReadAtOnce))
492 {
493 Write(buf, n);
494 }
495 pOrig->SetPos(restorePos);
496 delete [] buf;
497 }
498
511 void Sample::UpdateChunks(progress_t* pProgress) {
512 // first update base class's chunks
513 DLS::Sample::UpdateChunks(pProgress);
514
515 // make sure 'smpl' chunk exists
516 pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
517 if (!pCkSmpl) {
518 pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
519 memset(pCkSmpl->LoadChunkData(), 0, 60);
520 }
521 // update 'smpl' chunk
522 uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
523 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
524 store32(&pData[0], Manufacturer);
525 store32(&pData[4], Product);
526 store32(&pData[8], SamplePeriod);
527 store32(&pData[12], MIDIUnityNote);
528 store32(&pData[16], FineTune);
529 store32(&pData[20], SMPTEFormat);
530 store32(&pData[24], SMPTEOffset);
531 store32(&pData[28], Loops);
532
533 // we skip 'manufByt' for now (4 bytes)
534
535 store32(&pData[36], LoopID);
536 store32(&pData[40], LoopType);
537 store32(&pData[44], LoopStart);
538 store32(&pData[48], LoopEnd);
539 store32(&pData[52], LoopFraction);
540 store32(&pData[56], LoopPlayCount);
541
542 // make sure '3gix' chunk exists
543 pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
544 if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
545 // determine appropriate sample group index (to be stored in chunk)
546 uint16_t iSampleGroup = 0; // 0 refers to default sample group
547 File* pFile = static_cast<File*>(pParent);
548 if (pFile->pGroups) {
549 std::vector<Group*>::iterator iter = pFile->pGroups->begin();
550 std::vector<Group*>::iterator end = pFile->pGroups->end();
551 for (int i = 0; iter != end; i++, iter++) {
552 if (*iter == pGroup) {
553 iSampleGroup = i;
554 break; // found
555 }
556 }
557 }
558 // update '3gix' chunk
559 pData = (uint8_t*) pCk3gix->LoadChunkData();
560 store16(&pData[0], iSampleGroup);
561
562 // if the library user toggled the "Compressed" attribute from true to
563 // false, then the EWAV chunk associated with compressed samples needs
564 // to be deleted
565 RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
566 if (ewav && !Compressed) {
567 pWaveList->DeleteSubChunk(ewav);
568 }
569 }
570
572 void Sample::ScanCompressedSample() {
573 //TODO: we have to add some more scans here (e.g. determine compression rate)
574 this->SamplesTotal = 0;
575 std::list<file_offset_t> frameOffsets;
576
577 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
578 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
579
580 // Scanning
581 pCkData->SetPos(0);
582 if (Channels == 2) { // Stereo
583 for (int i = 0 ; ; i++) {
584 // for 24 bit samples every 8:th frame offset is
585 // stored, to save some memory
586 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
587
588 const int mode_l = pCkData->ReadUint8();
589 const int mode_r = pCkData->ReadUint8();
590 if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
591 const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
592
593 if (pCkData->RemainingBytes() <= frameSize) {
595 ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
596 (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
598 break;
599 }
601 pCkData->SetPos(frameSize, RIFF::stream_curpos);
602 }
603 }
604 else { // Mono
605 for (int i = 0 ; ; i++) {
606 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
607
608 const int mode = pCkData->ReadUint8();
609 if (mode > 5) throw gig::Exception("Unknown compression mode");
610 const file_offset_t frameSize = bytesPerFrame[mode];
611
612 if (pCkData->RemainingBytes() <= frameSize) {
614 ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
616 break;
617 }
619 pCkData->SetPos(frameSize, RIFF::stream_curpos);
620 }
621 }
622 pCkData->SetPos(0);
623
624 // Build the frames table (which is used for fast resolving of a frame's chunk offset)
625 if (FrameTable) delete[] FrameTable;
626 FrameTable = new file_offset_t[frameOffsets.size()];
627 std::list<file_offset_t>::iterator end = frameOffsets.end();
628 std::list<file_offset_t>::iterator iter = frameOffsets.begin();
629 for (int i = 0; iter != end; i++, iter++) {
630 FrameTable[i] = *iter;
631 }
632 }
633
644 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
645 }
646
669 buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
670 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
671 }
672
693 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
694 }
695
728 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
729 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
730 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
731 file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
732 SetPos(0); // reset read position to begin of sample
733 RAMCache.pStart = new int8_t[allocationsize];
734 RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
735 RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
736 // fill the remaining buffer space with silence samples
737 memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
738 return GetCache();
739 }
740
752 // return a copy of the buffer_t structure
753 buffer_t result;
754 result.Size = this->RAMCache.Size;
755 result.pStart = this->RAMCache.pStart;
757 return result;
758 }
759
767 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
768 RAMCache.pStart = NULL;
769 RAMCache.Size = 0;
771 }
772
803 void Sample::Resize(file_offset_t NewSize) {
804 if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
805 DLS::Sample::Resize(NewSize);
806 }
807
829 file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
830 if (Compressed) {
831 switch (Whence) {
832 case RIFF::stream_curpos:
833 this->SamplePos += SampleCount;
834 break;
835 case RIFF::stream_end:
836 this->SamplePos = this->SamplesTotal - 1 - SampleCount;
837 break;
838 case RIFF::stream_backward:
839 this->SamplePos -= SampleCount;
840 break;
841 case RIFF::stream_start: default:
842 this->SamplePos = SampleCount;
843 break;
844 }
845 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
846
847 file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
848 this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
849 pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
850 return this->SamplePos;
851 }
852 else { // not compressed
853 file_offset_t orderedBytes = SampleCount * this->FrameSize;
854 file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
855 return (result == orderedBytes) ? SampleCount
856 : result / this->FrameSize;
857 }
858 }
859
863 file_offset_t Sample::GetPos() const {
864 if (Compressed) return SamplePos;
865 else return pCkData->GetPos() / FrameSize;
866 }
867
902 file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
903 DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
904 file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
905 uint8_t* pDst = (uint8_t*) pBuffer;
906
907 SetPos(pPlaybackState->position); // recover position from the last time
908
909 if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
910
911 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
912 const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
913
914 if (GetPos() <= loopEnd) {
915 switch (loop.LoopType) {
916
917 case loop_type_bidirectional: { //TODO: not tested yet!
918 do {
919 // if not endless loop check if max. number of loop cycles have been passed
920 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
921
922 if (!pPlaybackState->reverse) { // forward playback
923 do {
924 samplestoloopend = loopEnd - GetPos();
925 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
926 samplestoread -= readsamples;
927 totalreadsamples += readsamples;
928 if (readsamples == samplestoloopend) {
929 pPlaybackState->reverse = true;
930 break;
931 }
932 } while (samplestoread && readsamples);
933 }
934 else { // backward playback
935
936 // as we can only read forward from disk, we have to
937 // determine the end position within the loop first,
938 // read forward from that 'end' and finally after
939 // reading, swap all sample frames so it reflects
940 // backward playback
941
942 file_offset_t swapareastart = totalreadsamples;
943 file_offset_t loopoffset = GetPos() - loop.LoopStart;
944 file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
945 file_offset_t reverseplaybackend = GetPos() - samplestoreadinloop;
946
947 SetPos(reverseplaybackend);
948
949 // read samples for backward playback
950 do {
951 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
952 samplestoreadinloop -= readsamples;
953 samplestoread -= readsamples;
954 totalreadsamples += readsamples;
955 } while (samplestoreadinloop && readsamples);
956
957 SetPos(reverseplaybackend); // pretend we really read backwards
958
959 if (reverseplaybackend == loop.LoopStart) {
960 pPlaybackState->loop_cycles_left--;
961 pPlaybackState->reverse = false;
962 }
963
964 // reverse the sample frames for backward playback
965 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!
966 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
967 }
968 } while (samplestoread && readsamples);
969 break;
970 }
971
972 case loop_type_backward: { // TODO: not tested yet!
973 // forward playback (not entered the loop yet)
974 if (!pPlaybackState->reverse) do {
975 samplestoloopend = loopEnd - GetPos();
976 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
977 samplestoread -= readsamples;
978 totalreadsamples += readsamples;
979 if (readsamples == samplestoloopend) {
980 pPlaybackState->reverse = true;
981 break;
982 }
983 } while (samplestoread && readsamples);
984
985 if (!samplestoread) break;
986
987 // as we can only read forward from disk, we have to
988 // determine the end position within the loop first,
989 // read forward from that 'end' and finally after
990 // reading, swap all sample frames so it reflects
991 // backward playback
992
993 file_offset_t swapareastart = totalreadsamples;
994 file_offset_t loopoffset = GetPos() - loop.LoopStart;
995 file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
996 : samplestoread;
997 file_offset_t reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
998
999 SetPos(reverseplaybackend);
1000
1001 // read samples for backward playback
1002 do {
1003 // if not endless loop check if max. number of loop cycles have been passed
1004 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1005 samplestoloopend = loopEnd - GetPos();
1006 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1007 samplestoreadinloop -= readsamples;
1008 samplestoread -= readsamples;
1009 totalreadsamples += readsamples;
1010 if (readsamples == samplestoloopend) {
1011 pPlaybackState->loop_cycles_left--;
1012 SetPos(loop.LoopStart);
1013 }
1014 } while (samplestoreadinloop && readsamples);
1015
1016 SetPos(reverseplaybackend); // pretend we really read backwards
1017
1018 // reverse the sample frames for backward playback
1019 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1020 break;
1021 }
1022
1023 default: case loop_type_normal: {
1024 do {
1025 // if not endless loop check if max. number of loop cycles have been passed
1026 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1027 samplestoloopend = loopEnd - GetPos();
1028 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1029 samplestoread -= readsamples;
1030 totalreadsamples += readsamples;
1031 if (readsamples == samplestoloopend) {
1032 pPlaybackState->loop_cycles_left--;
1033 SetPos(loop.LoopStart);
1034 }
1035 } while (samplestoread && readsamples);
1036 break;
1037 }
1038 }
1039 }
1040 }
1041
1042 // read on without looping
1043 if (samplestoread) do {
1044 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1045 samplestoread -= readsamples;
1046 totalreadsamples += readsamples;
1047 } while (readsamples && samplestoread);
1048
1049 // store current position
1050 pPlaybackState->position = GetPos();
1051
1052 return totalreadsamples;
1053 }
1054
1077 file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1078 if (SampleCount == 0) return 0;
1079 if (!Compressed) {
1080 if (BitDepth == 24) {
1081 return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1082 }
1083 else { // 16 bit
1084 // (pCkData->Read does endian correction)
1085 return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1086 : pCkData->Read(pBuffer, SampleCount, 2);
1087 }
1088 }
1089 else {
1090 if (this->SamplePos >= this->SamplesTotal) return 0;
1091 //TODO: efficiency: maybe we should test for an average compression rate
1092 file_offset_t assumedsize = GuessSize(SampleCount),
1093 remainingbytes = 0, // remaining bytes in the local buffer
1094 remainingsamples = SampleCount,
1095 copysamples, skipsamples,
1096 currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1097 this->FrameOffset = 0;
1098
1099 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1100
1101 // if decompression buffer too small, then reduce amount of samples to read
1102 if (pDecompressionBuffer->Size < assumedsize) {
1103 std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1104 SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1105 remainingsamples = SampleCount;
1106 assumedsize = GuessSize(SampleCount);
1107 }
1108
1109 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1110 int16_t* pDst = static_cast<int16_t*>(pBuffer);
1111 uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1112 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1113
1114 while (remainingsamples && remainingbytes) {
1115 file_offset_t framesamples = SamplesPerFrame;
1116 file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1117
1118 int mode_l = *pSrc++, mode_r = 0;
1119
1120 if (Channels == 2) {
1121 mode_r = *pSrc++;
1122 framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1123 rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1124 nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1125 if (remainingbytes < framebytes) { // last frame in sample
1126 framesamples = SamplesInLastFrame;
1127 if (mode_l == 4 && (framesamples & 1)) {
1128 rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1129 }
1130 else {
1131 rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1132 }
1133 }
1134 }
1135 else {
1136 framebytes = bytesPerFrame[mode_l] + 1;
1137 nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1138 if (remainingbytes < framebytes) {
1139 framesamples = SamplesInLastFrame;
1140 }
1141 }
1142
1143 // determine how many samples in this frame to skip and read
1144 if (currentframeoffset + remainingsamples >= framesamples) {
1145 if (currentframeoffset <= framesamples) {
1146 copysamples = framesamples - currentframeoffset;
1147 skipsamples = currentframeoffset;
1148 }
1149 else {
1150 copysamples = 0;
1151 skipsamples = framesamples;
1152 }
1153 }
1154 else {
1155 // This frame has enough data for pBuffer, but not
1156 // all of the frame is needed. Set file position
1157 // to start of this frame for next call to Read.
1158 copysamples = remainingsamples;
1159 skipsamples = currentframeoffset;
1160 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1161 this->FrameOffset = currentframeoffset + copysamples;
1162 }
1163 remainingsamples -= copysamples;
1164
1165 if (remainingbytes > framebytes) {
1166 remainingbytes -= framebytes;
1167 if (remainingsamples == 0 &&
1168 currentframeoffset + copysamples == framesamples) {
1169 // This frame has enough data for pBuffer, and
1170 // all of the frame is needed. Set file
1171 // position to start of next frame for next
1172 // call to Read. FrameOffset is 0.
1173 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1174 }
1175 }
1176 else remainingbytes = 0;
1177
1178 currentframeoffset -= skipsamples;
1179
1180 if (copysamples == 0) {
1181 // skip this frame
1182 pSrc += framebytes - Channels;
1183 }
1184 else {
1185 const unsigned char* const param_l = pSrc;
1186 if (BitDepth == 24) {
1187 if (mode_l != 2) pSrc += 12;
1188
1189 if (Channels == 2) { // Stereo
1190 const unsigned char* const param_r = pSrc;
1191 if (mode_r != 2) pSrc += 12;
1192
1193 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1194 skipsamples, copysamples, TruncatedBits);
1195 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1196 skipsamples, copysamples, TruncatedBits);
1197 pDst24 += copysamples * 6;
1198 }
1199 else { // Mono
1200 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1201 skipsamples, copysamples, TruncatedBits);
1202 pDst24 += copysamples * 3;
1203 }
1204 }
1205 else { // 16 bit
1206 if (mode_l) pSrc += 4;
1207
1208 int step;
1209 if (Channels == 2) { // Stereo
1210 const unsigned char* const param_r = pSrc;
1211 if (mode_r) pSrc += 4;
1212
1213 step = (2 - mode_l) + (2 - mode_r);
1214 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1215 Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1216 skipsamples, copysamples);
1217 pDst += copysamples << 1;
1218 }
1219 else { // Mono
1220 step = 2 - mode_l;
1221 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1222 pDst += copysamples;
1223 }
1224 }
1225 pSrc += nextFrameOffset;
1226 }
1227
1228 // reload from disk to local buffer if needed
1229 if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1230 assumedsize = GuessSize(remainingsamples);
1231 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1232 if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1233 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1234 pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1235 }
1236 } // while
1237
1238 this->SamplePos += (SampleCount - remainingsamples);
1239 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1240 return (SampleCount - remainingsamples);
1241 }
1242 }
1243
1266 file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1267 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1268
1269 // if this is the first write in this sample, reset the
1270 // checksum calculator
1271 if (pCkData->GetPos() == 0) {
1272 __resetCRC(crc);
1273 }
1274 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1275 file_offset_t res;
1276 if (BitDepth == 24) {
1277 res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1278 } else { // 16 bit
1279 res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1280 : pCkData->Write(pBuffer, SampleCount, 2);
1281 }
1282 #if WORDS_BIGENDIAN
1283 // temporarily swap bytes to little-endian for CRC calculation
1284 // (24 bit samples are already stored as little-endian, thus no byte
1285 // swapping is required in this case)
1286 if (BitDepth != 24)
1287 swapBytesOfWords(pBuffer, res * Channels, 2);
1288 #endif
1289 __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1290 #if WORDS_BIGENDIAN
1291 // revert temporary byte swapping
1292 if (BitDepth != 24)
1293 swapBytesOfWords(pBuffer, res * Channels, 2);
1294 #endif
1295
1296 // if this is the last write, update the checksum chunk in the
1297 // file
1298 if (pCkData->GetPos() == std::min(pCkData->GetSize(), pCkData->GetNewSize())) {
1299 __finalizeCRC(crc);
1300 File* pFile = static_cast<File*>(GetParent());
1301 pFile->SetSampleChecksum(this, crc);
1302 }
1303 return res;
1304 }
1305
1322 buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1323 buffer_t result;
1324 const double worstCaseHeaderOverhead =
1325 (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1326 result.Size = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1327 result.pStart = new int8_t[result.Size];
1328 result.NullExtensionSize = 0;
1329 return result;
1330 }
1331
1340 if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1341 delete[] (int8_t*) DecompressionBuffer.pStart;
1342 DecompressionBuffer.pStart = NULL;
1343 DecompressionBuffer.Size = 0;
1344 DecompressionBuffer.NullExtensionSize = 0;
1345 }
1346 }
1347
1356 Group* Sample::GetGroup() const {
1357 return pGroup;
1358 }
1359
1373 return crc;
1374 }
1375
1401 bool Sample::VerifyWaveData(uint32_t* pActually) {
1402 //File* pFile = static_cast<File*>(GetParent());
1403 uint32_t crc = CalculateWaveDataChecksum();
1404 if (pActually) *pActually = crc;
1405 return crc == this->crc;
1406 }
1407
1408 uint32_t Sample::CalculateWaveDataChecksum() {
1409 const size_t sz = 20*1024; // 20kB buffer size
1410 std::vector<uint8_t> buffer(sz);
1411 buffer.resize(sz);
1412
1413 const size_t n = sz / FrameSize;
1414 SetPos(0);
1415 uint32_t crc = 0;
1416 __resetCRC(crc);
1417 while (true) {
1418 file_offset_t nRead = Read(&buffer[0], n);
1419 if (nRead <= 0) break;
1420 #if WORDS_BIGENDIAN
1421 // temporarily swap bytes to little-endian for CRC calculation
1422 // (24 bit samples are already stored as little-endian, thus no
1423 // byte swapping is required in this case)
1424 if (BitDepth != 24)
1425 swapBytesOfWords(&buffer[0], nRead * Channels, 2);
1426 #endif
1427 __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1428 #if WORDS_BIGENDIAN
1429 // revert temporary byte swapping
1430 if (BitDepth != 24)
1431 swapBytesOfWords(&buffer[0], nRead * Channels, 2);
1432 #endif
1433 }
1434 __finalizeCRC(crc);
1435 return crc;
1436 }
1437
1439 Instances--;
1441 delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1444 }
1445 if (FrameTable) delete[] FrameTable;
1446 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1447 }
1448
1449
1450
1451// *************** DimensionRegion ***************
1452// *
1453
1454 size_t DimensionRegion::Instances = 0;
1455 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1456
1457 DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1458 Instances++;
1459
1460 pSample = NULL;
1461 pRegion = pParent;
1462
1463 if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1464 else memset(&Crossfade, 0, 4);
1465
1466 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1467
1468 RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1469 if (_3ewa) { // if '3ewa' chunk exists
1470 _3ewa->SetPos(0);
1471
1472 _3ewa->ReadInt32(); // unknown, always == chunk size ?
1473 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1474 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1475 _3ewa->ReadInt16(); // unknown
1476 LFO1InternalDepth = _3ewa->ReadUint16();
1477 _3ewa->ReadInt16(); // unknown
1478 LFO3InternalDepth = _3ewa->ReadInt16();
1479 _3ewa->ReadInt16(); // unknown
1480 LFO1ControlDepth = _3ewa->ReadUint16();
1481 _3ewa->ReadInt16(); // unknown
1482 LFO3ControlDepth = _3ewa->ReadInt16();
1483 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1484 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1485 _3ewa->ReadInt16(); // unknown
1486 EG1Sustain = _3ewa->ReadUint16();
1487 EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1488 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1489 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1490 EG1ControllerInvert = eg1ctrloptions & 0x01;
1491 EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1492 EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1493 EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1494 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1495 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1496 EG2ControllerInvert = eg2ctrloptions & 0x01;
1497 EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1498 EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1499 EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1500 LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1501 EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1502 EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1503 _3ewa->ReadInt16(); // unknown
1504 EG2Sustain = _3ewa->ReadUint16();
1505 EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1506 _3ewa->ReadInt16(); // unknown
1507 LFO2ControlDepth = _3ewa->ReadUint16();
1508 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1509 _3ewa->ReadInt16(); // unknown
1510 LFO2InternalDepth = _3ewa->ReadUint16();
1511 int32_t eg1decay2 = _3ewa->ReadInt32();
1512 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1513 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1514 _3ewa->ReadInt16(); // unknown
1515 EG1PreAttack = _3ewa->ReadUint16();
1516 int32_t eg2decay2 = _3ewa->ReadInt32();
1517 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1518 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1519 _3ewa->ReadInt16(); // unknown
1520 EG2PreAttack = _3ewa->ReadUint16();
1521 uint8_t velocityresponse = _3ewa->ReadUint8();
1522 if (velocityresponse < 5) {
1523 VelocityResponseCurve = curve_type_nonlinear;
1524 VelocityResponseDepth = velocityresponse;
1525 } else if (velocityresponse < 10) {
1526 VelocityResponseCurve = curve_type_linear;
1527 VelocityResponseDepth = velocityresponse - 5;
1528 } else if (velocityresponse < 15) {
1529 VelocityResponseCurve = curve_type_special;
1530 VelocityResponseDepth = velocityresponse - 10;
1531 } else {
1532 VelocityResponseCurve = curve_type_unknown;
1533 VelocityResponseDepth = 0;
1534 }
1535 uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1536 if (releasevelocityresponse < 5) {
1537 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1538 ReleaseVelocityResponseDepth = releasevelocityresponse;
1539 } else if (releasevelocityresponse < 10) {
1540 ReleaseVelocityResponseCurve = curve_type_linear;
1541 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1542 } else if (releasevelocityresponse < 15) {
1543 ReleaseVelocityResponseCurve = curve_type_special;
1544 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1545 } else {
1546 ReleaseVelocityResponseCurve = curve_type_unknown;
1547 ReleaseVelocityResponseDepth = 0;
1548 }
1549 VelocityResponseCurveScaling = _3ewa->ReadUint8();
1550 AttenuationControllerThreshold = _3ewa->ReadInt8();
1551 _3ewa->ReadInt32(); // unknown
1552 SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1553 _3ewa->ReadInt16(); // unknown
1554 uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1555 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1556 if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1557 else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1558 else DimensionBypass = dim_bypass_ctrl_none;
1559 uint8_t pan = _3ewa->ReadUint8();
1560 Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1561 SelfMask = _3ewa->ReadInt8() & 0x01;
1562 _3ewa->ReadInt8(); // unknown
1563 uint8_t lfo3ctrl = _3ewa->ReadUint8();
1564 LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1565 LFO3Sync = lfo3ctrl & 0x20; // bit 5
1566 InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1567 AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1568 uint8_t lfo2ctrl = _3ewa->ReadUint8();
1569 LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1570 LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1571 LFO2Sync = lfo2ctrl & 0x20; // bit 5
1572 bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1573 uint8_t lfo1ctrl = _3ewa->ReadUint8();
1574 LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1575 LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1576 LFO1Sync = lfo1ctrl & 0x40; // bit 6
1577 VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1579 uint16_t eg3depth = _3ewa->ReadUint16();
1580 EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1581 : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1582 _3ewa->ReadInt16(); // unknown
1583 ChannelOffset = _3ewa->ReadUint8() / 4;
1584 uint8_t regoptions = _3ewa->ReadUint8();
1585 MSDecode = regoptions & 0x01; // bit 0
1586 SustainDefeat = regoptions & 0x02; // bit 1
1587 _3ewa->ReadInt16(); // unknown
1588 VelocityUpperLimit = _3ewa->ReadInt8();
1589 _3ewa->ReadInt8(); // unknown
1590 _3ewa->ReadInt16(); // unknown
1591 ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1592 _3ewa->ReadInt8(); // unknown
1593 _3ewa->ReadInt8(); // unknown
1594 EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1595 uint8_t vcfcutoff = _3ewa->ReadUint8();
1596 VCFEnabled = vcfcutoff & 0x80; // bit 7
1597 VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1598 VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1599 uint8_t vcfvelscale = _3ewa->ReadUint8();
1600 VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1601 VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1602 _3ewa->ReadInt8(); // unknown
1603 uint8_t vcfresonance = _3ewa->ReadUint8();
1604 VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1605 VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1606 uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1607 VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1608 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1609 uint8_t vcfvelocity = _3ewa->ReadUint8();
1610 VCFVelocityDynamicRange = vcfvelocity % 5;
1611 VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1612 VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1613 if (VCFType == vcf_type_lowpass) {
1614 if (lfo3ctrl & 0x40) // bit 6
1615 VCFType = vcf_type_lowpassturbo;
1616 }
1617 if (_3ewa->RemainingBytes() >= 8) {
1618 _3ewa->Read(DimensionUpperLimits, 1, 8);
1619 } else {
1620 memset(DimensionUpperLimits, 0, 8);
1621 }
1622 } else { // '3ewa' chunk does not exist yet
1623 // use default values
1624 LFO3Frequency = 1.0;
1625 EG3Attack = 0.0;
1626 LFO1InternalDepth = 0;
1627 LFO3InternalDepth = 0;
1628 LFO1ControlDepth = 0;
1629 LFO3ControlDepth = 0;
1630 EG1Attack = 0.0;
1631 EG1Decay1 = 0.005;
1632 EG1Sustain = 1000;
1633 EG1Release = 0.3;
1634 EG1Controller.type = eg1_ctrl_t::type_none;
1635 EG1Controller.controller_number = 0;
1636 EG1ControllerInvert = false;
1637 EG1ControllerAttackInfluence = 0;
1638 EG1ControllerDecayInfluence = 0;
1639 EG1ControllerReleaseInfluence = 0;
1640 EG2Controller.type = eg2_ctrl_t::type_none;
1641 EG2Controller.controller_number = 0;
1642 EG2ControllerInvert = false;
1643 EG2ControllerAttackInfluence = 0;
1644 EG2ControllerDecayInfluence = 0;
1645 EG2ControllerReleaseInfluence = 0;
1646 LFO1Frequency = 1.0;
1647 EG2Attack = 0.0;
1648 EG2Decay1 = 0.005;
1649 EG2Sustain = 1000;
1650 EG2Release = 60;
1651 LFO2ControlDepth = 0;
1652 LFO2Frequency = 1.0;
1653 LFO2InternalDepth = 0;
1654 EG1Decay2 = 0.0;
1655 EG1InfiniteSustain = true;
1656 EG1PreAttack = 0;
1657 EG2Decay2 = 0.0;
1658 EG2InfiniteSustain = true;
1659 EG2PreAttack = 0;
1660 VelocityResponseCurve = curve_type_nonlinear;
1661 VelocityResponseDepth = 3;
1662 ReleaseVelocityResponseCurve = curve_type_nonlinear;
1663 ReleaseVelocityResponseDepth = 3;
1664 VelocityResponseCurveScaling = 32;
1665 AttenuationControllerThreshold = 0;
1666 SampleStartOffset = 0;
1667 PitchTrack = true;
1668 DimensionBypass = dim_bypass_ctrl_none;
1669 Pan = 0;
1670 SelfMask = true;
1671 LFO3Controller = lfo3_ctrl_modwheel;
1672 LFO3Sync = false;
1673 InvertAttenuationController = false;
1674 AttenuationController.type = attenuation_ctrl_t::type_none;
1675 AttenuationController.controller_number = 0;
1676 LFO2Controller = lfo2_ctrl_internal;
1677 LFO2FlipPhase = false;
1678 LFO2Sync = false;
1679 LFO1Controller = lfo1_ctrl_internal;
1680 LFO1FlipPhase = false;
1681 LFO1Sync = false;
1682 VCFResonanceController = vcf_res_ctrl_none;
1683 EG3Depth = 0;
1684 ChannelOffset = 0;
1685 MSDecode = false;
1686 SustainDefeat = false;
1687 VelocityUpperLimit = 0;
1688 ReleaseTriggerDecay = 0;
1689 EG1Hold = false;
1690 VCFEnabled = false;
1691 VCFCutoff = 0;
1692 VCFCutoffController = vcf_cutoff_ctrl_none;
1693 VCFCutoffControllerInvert = false;
1694 VCFVelocityScale = 0;
1695 VCFResonance = 0;
1696 VCFResonanceDynamic = false;
1697 VCFKeyboardTracking = false;
1698 VCFKeyboardTrackingBreakpoint = 0;
1699 VCFVelocityDynamicRange = 0x04;
1700 VCFVelocityCurve = curve_type_linear;
1701 VCFType = vcf_type_lowpass;
1702 memset(DimensionUpperLimits, 127, 8);
1703 }
1704
1705 // chunk for own format extensions, these will *NOT* work with Gigasampler/GigaStudio !
1706 RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE);
1707 if (lsde) { // format extension for EG behavior options
1708 lsde->SetPos(0);
1709
1710 eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };
1711 for (int i = 0; i < 2; ++i) { // NOTE: we reserved a 3rd byte for a potential future EG3 option
1712 unsigned char byte = lsde->ReadUint8();
1713 pEGOpts[i]->AttackCancel = byte & 1;
1714 pEGOpts[i]->AttackHoldCancel = byte & (1 << 1);
1715 pEGOpts[i]->Decay1Cancel = byte & (1 << 2);
1716 pEGOpts[i]->Decay2Cancel = byte & (1 << 3);
1717 pEGOpts[i]->ReleaseCancel = byte & (1 << 4);
1718 }
1719 }
1720 // format extension for sustain pedal up effect on release trigger samples
1721 if (lsde && lsde->GetSize() > 3) { // NOTE: we reserved the 3rd byte for a potential future EG3 option
1722 lsde->SetPos(3);
1723 uint8_t byte = lsde->ReadUint8();
1724 SustainReleaseTrigger = static_cast<sust_rel_trg_t>(byte & 0x03);
1725 NoNoteOffReleaseTrigger = byte >> 7;
1726 } else {
1727 SustainReleaseTrigger = sust_rel_trg_none;
1728 NoNoteOffReleaseTrigger = false;
1729 }
1730 // format extension for LFOs' wave form, phase displacement and for
1731 // LFO3's flip phase
1732 if (lsde && lsde->GetSize() > 4) {
1733 lsde->SetPos(4);
1734 LFO1WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1735 LFO2WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1736 LFO3WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1737 lsde->ReadUint16(); // unused 16 bits, reserved for potential future use
1738 LFO1Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1739 LFO2Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1740 LFO3Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1741 const uint32_t flags = lsde->ReadInt32();
1742 LFO3FlipPhase = flags & 1;
1743 } else {
1744 LFO1WaveForm = lfo_wave_sine;
1745 LFO2WaveForm = lfo_wave_sine;
1746 LFO3WaveForm = lfo_wave_sine;
1747 LFO1Phase = 0.0;
1748 LFO2Phase = 0.0;
1749 LFO3Phase = 0.0;
1750 LFO3FlipPhase = false;
1751 }
1752
1753 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1754 VelocityResponseDepth,
1755 VelocityResponseCurveScaling);
1756
1757 pVelocityReleaseTable = GetReleaseVelocityTable(
1758 ReleaseVelocityResponseCurve,
1759 ReleaseVelocityResponseDepth
1760 );
1761
1762 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1763 VCFVelocityDynamicRange,
1764 VCFVelocityScale,
1765 VCFCutoffController);
1766
1767 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1768 VelocityTable = 0;
1769 }
1770
1771 /*
1772 * Constructs a DimensionRegion by copying all parameters from
1773 * another DimensionRegion
1774 */
1775 DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1776 Instances++;
1777 //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1778 *this = src; // default memberwise shallow copy of all parameters
1779 pParentList = _3ewl; // restore the chunk pointer
1780
1781 // deep copy of owned structures
1782 if (src.VelocityTable) {
1783 VelocityTable = new uint8_t[128];
1784 for (int k = 0 ; k < 128 ; k++)
1785 VelocityTable[k] = src.VelocityTable[k];
1786 }
1787 if (src.pSampleLoops) {
1788 pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1789 for (int k = 0 ; k < src.SampleLoops ; k++)
1790 pSampleLoops[k] = src.pSampleLoops[k];
1791 }
1792 }
1793
1803 void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1804 CopyAssign(orig, NULL);
1805 }
1806
1815 void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1816 // delete all allocated data first
1817 if (VelocityTable) delete [] VelocityTable;
1818 if (pSampleLoops) delete [] pSampleLoops;
1819
1820 // backup parent list pointer
1821 RIFF::List* p = pParentList;
1822
1823 gig::Sample* pOriginalSample = pSample;
1824 gig::Region* pOriginalRegion = pRegion;
1825
1826 //NOTE: copy code copied from assignment constructor above, see comment there as well
1827
1828 *this = *orig; // default memberwise shallow copy of all parameters
1829
1830 // restore members that shall not be altered
1831 pParentList = p; // restore the chunk pointer
1832 pRegion = pOriginalRegion;
1833
1834 // only take the raw sample reference reference if the
1835 // two DimensionRegion objects are part of the same file
1836 if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1837 pSample = pOriginalSample;
1838 }
1839
1840 if (mSamples && mSamples->count(orig->pSample)) {
1841 pSample = mSamples->find(orig->pSample)->second;
1842 }
1843
1844 // deep copy of owned structures
1845 if (orig->VelocityTable) {
1846 VelocityTable = new uint8_t[128];
1847 for (int k = 0 ; k < 128 ; k++)
1848 VelocityTable[k] = orig->VelocityTable[k];
1849 }
1850 if (orig->pSampleLoops) {
1852 for (int k = 0 ; k < orig->SampleLoops ; k++)
1853 pSampleLoops[k] = orig->pSampleLoops[k];
1854 }
1855 }
1856
1857 void DimensionRegion::serialize(Serialization::Archive* archive) {
1858 // in case this class will become backward incompatible one day,
1859 // then set a version and minimum version for this class like:
1860 //archive->setVersion(*this, 2);
1861 //archive->setMinVersion(*this, 1);
1862
1863 SRLZ(VelocityUpperLimit);
1864 SRLZ(EG1PreAttack);
1865 SRLZ(EG1Attack);
1866 SRLZ(EG1Decay1);
1867 SRLZ(EG1Decay2);
1868 SRLZ(EG1InfiniteSustain);
1869 SRLZ(EG1Sustain);
1870 SRLZ(EG1Release);
1871 SRLZ(EG1Hold);
1872 SRLZ(EG1Controller);
1873 SRLZ(EG1ControllerInvert);
1877 SRLZ(LFO1WaveForm);
1878 SRLZ(LFO1Frequency);
1879 SRLZ(LFO1Phase);
1880 SRLZ(LFO1InternalDepth);
1881 SRLZ(LFO1ControlDepth);
1882 SRLZ(LFO1Controller);
1883 SRLZ(LFO1FlipPhase);
1884 SRLZ(LFO1Sync);
1885 SRLZ(EG2PreAttack);
1886 SRLZ(EG2Attack);
1887 SRLZ(EG2Decay1);
1888 SRLZ(EG2Decay2);
1889 SRLZ(EG2InfiniteSustain);
1890 SRLZ(EG2Sustain);
1891 SRLZ(EG2Release);
1892 SRLZ(EG2Controller);
1893 SRLZ(EG2ControllerInvert);
1897 SRLZ(LFO2WaveForm);
1898 SRLZ(LFO2Frequency);
1899 SRLZ(LFO2Phase);
1900 SRLZ(LFO2InternalDepth);
1901 SRLZ(LFO2ControlDepth);
1902 SRLZ(LFO2Controller);
1903 SRLZ(LFO2FlipPhase);
1904 SRLZ(LFO2Sync);
1905 SRLZ(EG3Attack);
1906 SRLZ(EG3Depth);
1907 SRLZ(LFO3WaveForm);
1908 SRLZ(LFO3Frequency);
1909 SRLZ(LFO3Phase);
1910 SRLZ(LFO3InternalDepth);
1911 SRLZ(LFO3ControlDepth);
1912 SRLZ(LFO3Controller);
1913 SRLZ(LFO3FlipPhase);
1914 SRLZ(LFO3Sync);
1915 SRLZ(VCFEnabled);
1916 SRLZ(VCFType);
1917 SRLZ(VCFCutoffController);
1919 SRLZ(VCFCutoff);
1920 SRLZ(VCFVelocityCurve);
1921 SRLZ(VCFVelocityScale);
1923 SRLZ(VCFResonance);
1924 SRLZ(VCFResonanceDynamic);
1926 SRLZ(VCFKeyboardTracking);
1933 SRLZ(ReleaseTriggerDecay);
1934 SRLZ(Crossfade);
1935 SRLZ(PitchTrack);
1936 SRLZ(DimensionBypass);
1937 SRLZ(Pan);
1938 SRLZ(SelfMask);
1942 SRLZ(ChannelOffset);
1943 SRLZ(SustainDefeat);
1944 SRLZ(MSDecode);
1945 //SRLZ(SampleStartOffset);
1946 SRLZ(SampleAttenuation);
1947 SRLZ(EG1Options);
1948 SRLZ(EG2Options);
1951
1952 // derived attributes from DLS::Sampler
1953 SRLZ(FineTune);
1954 SRLZ(Gain);
1955 }
1956
1961 void DimensionRegion::SetGain(int32_t gain) {
1962 DLS::Sampler::SetGain(gain);
1963 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1964 }
1965
1975 void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1976 // first update base class's chunk
1977 DLS::Sampler::UpdateChunks(pProgress);
1978
1979 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1980 uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1981 pData[12] = Crossfade.in_start;
1982 pData[13] = Crossfade.in_end;
1983 pData[14] = Crossfade.out_start;
1984 pData[15] = Crossfade.out_end;
1985
1986 // make sure '3ewa' chunk exists
1987 RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1988 if (!_3ewa) {
1989 File* pFile = (File*) GetParent()->GetParent()->GetParent();
1990 bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;
1991 _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, versiongt2 ? 148 : 140);
1992 }
1993 pData = (uint8_t*) _3ewa->LoadChunkData();
1994
1995 // update '3ewa' chunk with DimensionRegion's current settings
1996
1997 const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1998 store32(&pData[0], chunksize); // unknown, always chunk size?
1999
2000 const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
2001 store32(&pData[4], lfo3freq);
2002
2003 const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
2004 store32(&pData[8], eg3attack);
2005
2006 // next 2 bytes unknown
2007
2008 store16(&pData[14], LFO1InternalDepth);
2009
2010 // next 2 bytes unknown
2011
2012 store16(&pData[18], LFO3InternalDepth);
2013
2014 // next 2 bytes unknown
2015
2016 store16(&pData[22], LFO1ControlDepth);
2017
2018 // next 2 bytes unknown
2019
2020 store16(&pData[26], LFO3ControlDepth);
2021
2022 const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
2023 store32(&pData[28], eg1attack);
2024
2025 const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
2026 store32(&pData[32], eg1decay1);
2027
2028 // next 2 bytes unknown
2029
2030 store16(&pData[38], EG1Sustain);
2031
2032 const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
2033 store32(&pData[40], eg1release);
2034
2035 const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
2036 pData[44] = eg1ctl;
2037
2038 const uint8_t eg1ctrloptions =
2039 (EG1ControllerInvert ? 0x01 : 0x00) |
2040 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
2041 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
2042 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
2043 pData[45] = eg1ctrloptions;
2044
2045 const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
2046 pData[46] = eg2ctl;
2047
2048 const uint8_t eg2ctrloptions =
2049 (EG2ControllerInvert ? 0x01 : 0x00) |
2050 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
2051 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
2052 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
2053 pData[47] = eg2ctrloptions;
2054
2055 const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
2056 store32(&pData[48], lfo1freq);
2057
2058 const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
2059 store32(&pData[52], eg2attack);
2060
2061 const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
2062 store32(&pData[56], eg2decay1);
2063
2064 // next 2 bytes unknown
2065
2066 store16(&pData[62], EG2Sustain);
2067
2068 const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
2069 store32(&pData[64], eg2release);
2070
2071 // next 2 bytes unknown
2072
2073 store16(&pData[70], LFO2ControlDepth);
2074
2075 const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
2076 store32(&pData[72], lfo2freq);
2077
2078 // next 2 bytes unknown
2079
2080 store16(&pData[78], LFO2InternalDepth);
2081
2082 const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
2083 store32(&pData[80], eg1decay2);
2084
2085 // next 2 bytes unknown
2086
2087 store16(&pData[86], EG1PreAttack);
2088
2089 const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
2090 store32(&pData[88], eg2decay2);
2091
2092 // next 2 bytes unknown
2093
2094 store16(&pData[94], EG2PreAttack);
2095
2096 {
2097 if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
2098 uint8_t velocityresponse = VelocityResponseDepth;
2099 switch (VelocityResponseCurve) {
2101 break;
2102 case curve_type_linear:
2103 velocityresponse += 5;
2104 break;
2105 case curve_type_special:
2106 velocityresponse += 10;
2107 break;
2108 case curve_type_unknown:
2109 default:
2110 throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
2111 }
2112 pData[96] = velocityresponse;
2113 }
2114
2115 {
2116 if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
2117 uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
2120 break;
2121 case curve_type_linear:
2122 releasevelocityresponse += 5;
2123 break;
2124 case curve_type_special:
2125 releasevelocityresponse += 10;
2126 break;
2127 case curve_type_unknown:
2128 default:
2129 throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
2130 }
2131 pData[97] = releasevelocityresponse;
2132 }
2133
2134 pData[98] = VelocityResponseCurveScaling;
2135
2137
2138 // next 4 bytes unknown
2139
2140 store16(&pData[104], SampleStartOffset);
2141
2142 // next 2 bytes unknown
2143
2144 {
2145 uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
2146 switch (DimensionBypass) {
2147 case dim_bypass_ctrl_94:
2148 pitchTrackDimensionBypass |= 0x10;
2149 break;
2150 case dim_bypass_ctrl_95:
2151 pitchTrackDimensionBypass |= 0x20;
2152 break;
2154 //FIXME: should we set anything here?
2155 break;
2156 default:
2157 throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
2158 }
2159 pData[108] = pitchTrackDimensionBypass;
2160 }
2161
2162 const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
2163 pData[109] = pan;
2164
2165 const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
2166 pData[110] = selfmask;
2167
2168 // next byte unknown
2169
2170 {
2171 uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
2172 if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
2173 if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
2174 if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
2175 pData[112] = lfo3ctrl;
2176 }
2177
2178 const uint8_t attenctl = EncodeLeverageController(AttenuationController);
2179 pData[113] = attenctl;
2180
2181 {
2182 uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
2183 if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
2184 if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
2185 if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
2186 pData[114] = lfo2ctrl;
2187 }
2188
2189 {
2190 uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
2191 if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
2192 if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
2194 lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
2195 pData[115] = lfo1ctrl;
2196 }
2197
2198 const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2199 : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2200 store16(&pData[116], eg3depth);
2201
2202 // next 2 bytes unknown
2203
2204 const uint8_t channeloffset = ChannelOffset * 4;
2205 pData[120] = channeloffset;
2206
2207 {
2208 uint8_t regoptions = 0;
2209 if (MSDecode) regoptions |= 0x01; // bit 0
2210 if (SustainDefeat) regoptions |= 0x02; // bit 1
2211 pData[121] = regoptions;
2212 }
2213
2214 // next 2 bytes unknown
2215
2216 pData[124] = VelocityUpperLimit;
2217
2218 // next 3 bytes unknown
2219
2220 pData[128] = ReleaseTriggerDecay;
2221
2222 // next 2 bytes unknown
2223
2224 const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2225 pData[131] = eg1hold;
2226
2227 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2228 (VCFCutoff & 0x7f); /* lower 7 bits */
2229 pData[132] = vcfcutoff;
2230
2231 pData[133] = VCFCutoffController;
2232
2233 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2234 (VCFVelocityScale & 0x7f); /* lower 7 bits */
2235 pData[134] = vcfvelscale;
2236
2237 // next byte unknown
2238
2239 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2240 (VCFResonance & 0x7f); /* lower 7 bits */
2241 pData[136] = vcfresonance;
2242
2243 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2244 (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2245 pData[137] = vcfbreakpoint;
2246
2247 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2248 VCFVelocityCurve * 5;
2249 pData[138] = vcfvelocity;
2250
2251 const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2252 pData[139] = vcftype;
2253
2254 if (chunksize >= 148) {
2255 memcpy(&pData[140], DimensionUpperLimits, 8);
2256 }
2257
2258 // chunk for own format extensions, these will *NOT* work with
2259 // Gigasampler/GigaStudio !
2260 RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);
2261 const int lsdeSize =
2262 3 /* EG cancel options */ +
2263 1 /* sustain pedal up on release trigger option */ +
2264 8 /* LFOs' wave forms */ + 12 /* LFOs' phase */ + 4 /* flags (LFO3FlipPhase) */;
2265 if (!lsde && UsesAnyGigFormatExtension()) {
2266 // only add this "LSDE" chunk if there is some (format extension)
2267 // setting effective that would require our "LSDE" format extension
2268 // chunk to be stored
2269 lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize);
2270 // move LSDE chunk to the end of parent list
2271 pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);
2272 }
2273 if (lsde) {
2274 if (lsde->GetNewSize() < lsdeSize)
2275 lsde->Resize(lsdeSize);
2276 // format extension for EG behavior options
2277 unsigned char* pData = (unsigned char*) lsde->LoadChunkData();
2278 eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };
2279 for (int i = 0; i < 2; ++i) { // NOTE: we reserved the 3rd byte for a potential future EG3 option
2280 pData[i] =
2281 (pEGOpts[i]->AttackCancel ? 1 : 0) |
2282 (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) |
2283 (pEGOpts[i]->Decay1Cancel ? (1<<2) : 0) |
2284 (pEGOpts[i]->Decay2Cancel ? (1<<3) : 0) |
2285 (pEGOpts[i]->ReleaseCancel ? (1<<4) : 0);
2286 }
2287 // format extension for release trigger options
2288 pData[3] = static_cast<uint8_t>(SustainReleaseTrigger) | (NoNoteOffReleaseTrigger ? (1<<7) : 0);
2289 // format extension for LFOs' wave form, phase displacement and for
2290 // LFO3's flip phase
2291 store16(&pData[4], LFO1WaveForm);
2292 store16(&pData[6], LFO2WaveForm);
2293 store16(&pData[8], LFO3WaveForm);
2294 //NOTE: 16 bits reserved here for potential future use !
2295 const int32_t lfo1Phase = (int32_t) GIG_EXP_ENCODE(LFO1Phase);
2296 const int32_t lfo2Phase = (int32_t) GIG_EXP_ENCODE(LFO2Phase);
2297 const int32_t lfo3Phase = (int32_t) GIG_EXP_ENCODE(LFO3Phase);
2298 store32(&pData[12], lfo1Phase);
2299 store32(&pData[16], lfo2Phase);
2300 store32(&pData[20], lfo3Phase);
2301 const int32_t flags = LFO3FlipPhase ? 1 : 0;
2302 store32(&pData[24], flags);
2303
2304 // compile time sanity check: is our last store access here
2305 // consistent with the initial lsdeSize value assignment?
2306 static_assert(lsdeSize == 28, "Inconsistency in assumed 'LSDE' RIFF chunk size");
2307 }
2308 }
2309
2325 bool DimensionRegion::UsesAnyGigFormatExtension() const {
2326 eg_opt_t defaultOpt;
2327 return memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) ||
2328 memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)) ||
2333 }
2334
2335 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2336 curve_type_t curveType = releaseVelocityResponseCurve;
2337 uint8_t depth = releaseVelocityResponseDepth;
2338 // this models a strange behaviour or bug in GSt: two of the
2339 // velocity response curves for release time are not used even
2340 // if specified, instead another curve is chosen.
2341 if ((curveType == curve_type_nonlinear && depth == 0) ||
2342 (curveType == curve_type_special && depth == 4)) {
2343 curveType = curve_type_nonlinear;
2344 depth = 3;
2345 }
2346 return GetVelocityTable(curveType, depth, 0);
2347 }
2348
2349 double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2350 uint8_t vcfVelocityDynamicRange,
2351 uint8_t vcfVelocityScale,
2352 vcf_cutoff_ctrl_t vcfCutoffController)
2353 {
2354 curve_type_t curveType = vcfVelocityCurve;
2355 uint8_t depth = vcfVelocityDynamicRange;
2356 // even stranger GSt: two of the velocity response curves for
2357 // filter cutoff are not used, instead another special curve
2358 // is chosen. This curve is not used anywhere else.
2359 if ((curveType == curve_type_nonlinear && depth == 0) ||
2360 (curveType == curve_type_special && depth == 4)) {
2361 curveType = curve_type_special;
2362 depth = 5;
2363 }
2364 return GetVelocityTable(curveType, depth,
2365 (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2366 ? vcfVelocityScale : 0);
2367 }
2368
2369 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2370 double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2371 {
2372 // sanity check input parameters
2373 // (fallback to some default parameters on ill input)
2374 switch (curveType) {
2376 case curve_type_linear:
2377 if (depth > 4) {
2378 printf("Warning: Invalid depth (0x%x) for velocity curve type (0x%x).\n", depth, curveType);
2379 depth = 0;
2380 scaling = 0;
2381 }
2382 break;
2383 case curve_type_special:
2384 if (depth > 5) {
2385 printf("Warning: Invalid depth (0x%x) for velocity curve type 'special'.\n", depth);
2386 depth = 0;
2387 scaling = 0;
2388 }
2389 break;
2390 case curve_type_unknown:
2391 default:
2392 printf("Warning: Unknown velocity curve type (0x%x).\n", curveType);
2393 curveType = curve_type_linear;
2394 depth = 0;
2395 scaling = 0;
2396 break;
2397 }
2398
2399 double* table;
2400 uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2401 if (pVelocityTables->count(tableKey)) { // if key exists
2402 table = (*pVelocityTables)[tableKey];
2403 }
2404 else {
2405 table = CreateVelocityTable(curveType, depth, scaling);
2406 (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2407 }
2408 return table;
2409 }
2410
2411 Region* DimensionRegion::GetParent() const {
2412 return pRegion;
2413 }
2414
2415// show error if some _lev_ctrl_* enum entry is not listed in the following function
2416// (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2417// TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2418//#pragma GCC diagnostic push
2419//#pragma GCC diagnostic error "-Wswitch"
2420
2421 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2422 leverage_ctrl_t decodedcontroller;
2423 switch (EncodedController) {
2424 // special controller
2425 case _lev_ctrl_none:
2426 decodedcontroller.type = leverage_ctrl_t::type_none;
2427 decodedcontroller.controller_number = 0;
2428 break;
2429 case _lev_ctrl_velocity:
2430 decodedcontroller.type = leverage_ctrl_t::type_velocity;
2431 decodedcontroller.controller_number = 0;
2432 break;
2433 case _lev_ctrl_channelaftertouch:
2434 decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2435 decodedcontroller.controller_number = 0;
2436 break;
2437
2438 // ordinary MIDI control change controller
2439 case _lev_ctrl_modwheel:
2440 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441 decodedcontroller.controller_number = 1;
2442 break;
2443 case _lev_ctrl_breath:
2444 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445 decodedcontroller.controller_number = 2;
2446 break;
2447 case _lev_ctrl_foot:
2448 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2449 decodedcontroller.controller_number = 4;
2450 break;
2451 case _lev_ctrl_effect1:
2452 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2453 decodedcontroller.controller_number = 12;
2454 break;
2455 case _lev_ctrl_effect2:
2456 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2457 decodedcontroller.controller_number = 13;
2458 break;
2459 case _lev_ctrl_genpurpose1:
2460 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2461 decodedcontroller.controller_number = 16;
2462 break;
2463 case _lev_ctrl_genpurpose2:
2464 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2465 decodedcontroller.controller_number = 17;
2466 break;
2467 case _lev_ctrl_genpurpose3:
2468 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2469 decodedcontroller.controller_number = 18;
2470 break;
2471 case _lev_ctrl_genpurpose4:
2472 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2473 decodedcontroller.controller_number = 19;
2474 break;
2475 case _lev_ctrl_portamentotime:
2476 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2477 decodedcontroller.controller_number = 5;
2478 break;
2479 case _lev_ctrl_sustainpedal:
2480 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2481 decodedcontroller.controller_number = 64;
2482 break;
2483 case _lev_ctrl_portamento:
2484 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2485 decodedcontroller.controller_number = 65;
2486 break;
2487 case _lev_ctrl_sostenutopedal:
2488 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2489 decodedcontroller.controller_number = 66;
2490 break;
2491 case _lev_ctrl_softpedal:
2492 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2493 decodedcontroller.controller_number = 67;
2494 break;
2495 case _lev_ctrl_genpurpose5:
2496 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2497 decodedcontroller.controller_number = 80;
2498 break;
2499 case _lev_ctrl_genpurpose6:
2500 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2501 decodedcontroller.controller_number = 81;
2502 break;
2503 case _lev_ctrl_genpurpose7:
2504 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2505 decodedcontroller.controller_number = 82;
2506 break;
2507 case _lev_ctrl_genpurpose8:
2508 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2509 decodedcontroller.controller_number = 83;
2510 break;
2511 case _lev_ctrl_effect1depth:
2512 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2513 decodedcontroller.controller_number = 91;
2514 break;
2515 case _lev_ctrl_effect2depth:
2516 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2517 decodedcontroller.controller_number = 92;
2518 break;
2519 case _lev_ctrl_effect3depth:
2520 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2521 decodedcontroller.controller_number = 93;
2522 break;
2523 case _lev_ctrl_effect4depth:
2524 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2525 decodedcontroller.controller_number = 94;
2526 break;
2527 case _lev_ctrl_effect5depth:
2528 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2529 decodedcontroller.controller_number = 95;
2530 break;
2531
2532 // format extension (these controllers are so far only supported by
2533 // LinuxSampler & gigedit) they will *NOT* work with
2534 // Gigasampler/GigaStudio !
2535 case _lev_ctrl_CC3_EXT:
2536 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2537 decodedcontroller.controller_number = 3;
2538 break;
2539 case _lev_ctrl_CC6_EXT:
2540 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2541 decodedcontroller.controller_number = 6;
2542 break;
2543 case _lev_ctrl_CC7_EXT:
2544 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2545 decodedcontroller.controller_number = 7;
2546 break;
2547 case _lev_ctrl_CC8_EXT:
2548 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2549 decodedcontroller.controller_number = 8;
2550 break;
2551 case _lev_ctrl_CC9_EXT:
2552 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2553 decodedcontroller.controller_number = 9;
2554 break;
2555 case _lev_ctrl_CC10_EXT:
2556 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2557 decodedcontroller.controller_number = 10;
2558 break;
2559 case _lev_ctrl_CC11_EXT:
2560 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2561 decodedcontroller.controller_number = 11;
2562 break;
2563 case _lev_ctrl_CC14_EXT:
2564 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2565 decodedcontroller.controller_number = 14;
2566 break;
2567 case _lev_ctrl_CC15_EXT:
2568 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2569 decodedcontroller.controller_number = 15;
2570 break;
2571 case _lev_ctrl_CC20_EXT:
2572 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2573 decodedcontroller.controller_number = 20;
2574 break;
2575 case _lev_ctrl_CC21_EXT:
2576 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2577 decodedcontroller.controller_number = 21;
2578 break;
2579 case _lev_ctrl_CC22_EXT:
2580 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2581 decodedcontroller.controller_number = 22;
2582 break;
2583 case _lev_ctrl_CC23_EXT:
2584 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2585 decodedcontroller.controller_number = 23;
2586 break;
2587 case _lev_ctrl_CC24_EXT:
2588 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2589 decodedcontroller.controller_number = 24;
2590 break;
2591 case _lev_ctrl_CC25_EXT:
2592 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2593 decodedcontroller.controller_number = 25;
2594 break;
2595 case _lev_ctrl_CC26_EXT:
2596 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2597 decodedcontroller.controller_number = 26;
2598 break;
2599 case _lev_ctrl_CC27_EXT:
2600 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2601 decodedcontroller.controller_number = 27;
2602 break;
2603 case _lev_ctrl_CC28_EXT:
2604 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2605 decodedcontroller.controller_number = 28;
2606 break;
2607 case _lev_ctrl_CC29_EXT:
2608 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2609 decodedcontroller.controller_number = 29;
2610 break;
2611 case _lev_ctrl_CC30_EXT:
2612 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2613 decodedcontroller.controller_number = 30;
2614 break;
2615 case _lev_ctrl_CC31_EXT:
2616 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2617 decodedcontroller.controller_number = 31;
2618 break;
2619 case _lev_ctrl_CC68_EXT:
2620 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2621 decodedcontroller.controller_number = 68;
2622 break;
2623 case _lev_ctrl_CC69_EXT:
2624 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2625 decodedcontroller.controller_number = 69;
2626 break;
2627 case _lev_ctrl_CC70_EXT:
2628 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2629 decodedcontroller.controller_number = 70;
2630 break;
2631 case _lev_ctrl_CC71_EXT:
2632 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2633 decodedcontroller.controller_number = 71;
2634 break;
2635 case _lev_ctrl_CC72_EXT:
2636 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2637 decodedcontroller.controller_number = 72;
2638 break;
2639 case _lev_ctrl_CC73_EXT:
2640 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2641 decodedcontroller.controller_number = 73;
2642 break;
2643 case _lev_ctrl_CC74_EXT:
2644 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2645 decodedcontroller.controller_number = 74;
2646 break;
2647 case _lev_ctrl_CC75_EXT:
2648 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2649 decodedcontroller.controller_number = 75;
2650 break;
2651 case _lev_ctrl_CC76_EXT:
2652 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2653 decodedcontroller.controller_number = 76;
2654 break;
2655 case _lev_ctrl_CC77_EXT:
2656 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2657 decodedcontroller.controller_number = 77;
2658 break;
2659 case _lev_ctrl_CC78_EXT:
2660 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2661 decodedcontroller.controller_number = 78;
2662 break;
2663 case _lev_ctrl_CC79_EXT:
2664 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2665 decodedcontroller.controller_number = 79;
2666 break;
2667 case _lev_ctrl_CC84_EXT:
2668 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2669 decodedcontroller.controller_number = 84;
2670 break;
2671 case _lev_ctrl_CC85_EXT:
2672 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2673 decodedcontroller.controller_number = 85;
2674 break;
2675 case _lev_ctrl_CC86_EXT:
2676 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2677 decodedcontroller.controller_number = 86;
2678 break;
2679 case _lev_ctrl_CC87_EXT:
2680 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2681 decodedcontroller.controller_number = 87;
2682 break;
2683 case _lev_ctrl_CC89_EXT:
2684 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2685 decodedcontroller.controller_number = 89;
2686 break;
2687 case _lev_ctrl_CC90_EXT:
2688 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2689 decodedcontroller.controller_number = 90;
2690 break;
2691 case _lev_ctrl_CC96_EXT:
2692 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2693 decodedcontroller.controller_number = 96;
2694 break;
2695 case _lev_ctrl_CC97_EXT:
2696 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2697 decodedcontroller.controller_number = 97;
2698 break;
2699 case _lev_ctrl_CC102_EXT:
2700 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2701 decodedcontroller.controller_number = 102;
2702 break;
2703 case _lev_ctrl_CC103_EXT:
2704 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2705 decodedcontroller.controller_number = 103;
2706 break;
2707 case _lev_ctrl_CC104_EXT:
2708 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2709 decodedcontroller.controller_number = 104;
2710 break;
2711 case _lev_ctrl_CC105_EXT:
2712 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2713 decodedcontroller.controller_number = 105;
2714 break;
2715 case _lev_ctrl_CC106_EXT:
2716 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2717 decodedcontroller.controller_number = 106;
2718 break;
2719 case _lev_ctrl_CC107_EXT:
2720 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2721 decodedcontroller.controller_number = 107;
2722 break;
2723 case _lev_ctrl_CC108_EXT:
2724 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2725 decodedcontroller.controller_number = 108;
2726 break;
2727 case _lev_ctrl_CC109_EXT:
2728 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2729 decodedcontroller.controller_number = 109;
2730 break;
2731 case _lev_ctrl_CC110_EXT:
2732 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2733 decodedcontroller.controller_number = 110;
2734 break;
2735 case _lev_ctrl_CC111_EXT:
2736 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2737 decodedcontroller.controller_number = 111;
2738 break;
2739 case _lev_ctrl_CC112_EXT:
2740 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2741 decodedcontroller.controller_number = 112;
2742 break;
2743 case _lev_ctrl_CC113_EXT:
2744 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2745 decodedcontroller.controller_number = 113;
2746 break;
2747 case _lev_ctrl_CC114_EXT:
2748 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2749 decodedcontroller.controller_number = 114;
2750 break;
2751 case _lev_ctrl_CC115_EXT:
2752 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2753 decodedcontroller.controller_number = 115;
2754 break;
2755 case _lev_ctrl_CC116_EXT:
2756 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2757 decodedcontroller.controller_number = 116;
2758 break;
2759 case _lev_ctrl_CC117_EXT:
2760 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2761 decodedcontroller.controller_number = 117;
2762 break;
2763 case _lev_ctrl_CC118_EXT:
2764 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2765 decodedcontroller.controller_number = 118;
2766 break;
2767 case _lev_ctrl_CC119_EXT:
2768 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2769 decodedcontroller.controller_number = 119;
2770 break;
2771
2772 // unknown controller type
2773 default:
2774 decodedcontroller.type = leverage_ctrl_t::type_none;
2775 decodedcontroller.controller_number = 0;
2776 printf("Warning: Unknown leverage controller type (0x%x).\n", EncodedController);
2777 break;
2778 }
2779 return decodedcontroller;
2780 }
2781
2782// see above (diagnostic push not supported prior GCC 4.6)
2783//#pragma GCC diagnostic pop
2784
2785 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2786 _lev_ctrl_t encodedcontroller;
2787 switch (DecodedController.type) {
2788 // special controller
2790 encodedcontroller = _lev_ctrl_none;
2791 break;
2793 encodedcontroller = _lev_ctrl_velocity;
2794 break;
2796 encodedcontroller = _lev_ctrl_channelaftertouch;
2797 break;
2798
2799 // ordinary MIDI control change controller
2801 switch (DecodedController.controller_number) {
2802 case 1:
2803 encodedcontroller = _lev_ctrl_modwheel;
2804 break;
2805 case 2:
2806 encodedcontroller = _lev_ctrl_breath;
2807 break;
2808 case 4:
2809 encodedcontroller = _lev_ctrl_foot;
2810 break;
2811 case 12:
2812 encodedcontroller = _lev_ctrl_effect1;
2813 break;
2814 case 13:
2815 encodedcontroller = _lev_ctrl_effect2;
2816 break;
2817 case 16:
2818 encodedcontroller = _lev_ctrl_genpurpose1;
2819 break;
2820 case 17:
2821 encodedcontroller = _lev_ctrl_genpurpose2;
2822 break;
2823 case 18:
2824 encodedcontroller = _lev_ctrl_genpurpose3;
2825 break;
2826 case 19:
2827 encodedcontroller = _lev_ctrl_genpurpose4;
2828 break;
2829 case 5:
2830 encodedcontroller = _lev_ctrl_portamentotime;
2831 break;
2832 case 64:
2833 encodedcontroller = _lev_ctrl_sustainpedal;
2834 break;
2835 case 65:
2836 encodedcontroller = _lev_ctrl_portamento;
2837 break;
2838 case 66:
2839 encodedcontroller = _lev_ctrl_sostenutopedal;
2840 break;
2841 case 67:
2842 encodedcontroller = _lev_ctrl_softpedal;
2843 break;
2844 case 80:
2845 encodedcontroller = _lev_ctrl_genpurpose5;
2846 break;
2847 case 81:
2848 encodedcontroller = _lev_ctrl_genpurpose6;
2849 break;
2850 case 82:
2851 encodedcontroller = _lev_ctrl_genpurpose7;
2852 break;
2853 case 83:
2854 encodedcontroller = _lev_ctrl_genpurpose8;
2855 break;
2856 case 91:
2857 encodedcontroller = _lev_ctrl_effect1depth;
2858 break;
2859 case 92:
2860 encodedcontroller = _lev_ctrl_effect2depth;
2861 break;
2862 case 93:
2863 encodedcontroller = _lev_ctrl_effect3depth;
2864 break;
2865 case 94:
2866 encodedcontroller = _lev_ctrl_effect4depth;
2867 break;
2868 case 95:
2869 encodedcontroller = _lev_ctrl_effect5depth;
2870 break;
2871
2872 // format extension (these controllers are so far only
2873 // supported by LinuxSampler & gigedit) they will *NOT*
2874 // work with Gigasampler/GigaStudio !
2875 case 3:
2876 encodedcontroller = _lev_ctrl_CC3_EXT;
2877 break;
2878 case 6:
2879 encodedcontroller = _lev_ctrl_CC6_EXT;
2880 break;
2881 case 7:
2882 encodedcontroller = _lev_ctrl_CC7_EXT;
2883 break;
2884 case 8:
2885 encodedcontroller = _lev_ctrl_CC8_EXT;
2886 break;
2887 case 9:
2888 encodedcontroller = _lev_ctrl_CC9_EXT;
2889 break;
2890 case 10:
2891 encodedcontroller = _lev_ctrl_CC10_EXT;
2892 break;
2893 case 11:
2894 encodedcontroller = _lev_ctrl_CC11_EXT;
2895 break;
2896 case 14:
2897 encodedcontroller = _lev_ctrl_CC14_EXT;
2898 break;
2899 case 15:
2900 encodedcontroller = _lev_ctrl_CC15_EXT;
2901 break;
2902 case 20:
2903 encodedcontroller = _lev_ctrl_CC20_EXT;
2904 break;
2905 case 21:
2906 encodedcontroller = _lev_ctrl_CC21_EXT;
2907 break;
2908 case 22:
2909 encodedcontroller = _lev_ctrl_CC22_EXT;
2910 break;
2911 case 23:
2912 encodedcontroller = _lev_ctrl_CC23_EXT;
2913 break;
2914 case 24:
2915 encodedcontroller = _lev_ctrl_CC24_EXT;
2916 break;
2917 case 25:
2918 encodedcontroller = _lev_ctrl_CC25_EXT;
2919 break;
2920 case 26:
2921 encodedcontroller = _lev_ctrl_CC26_EXT;
2922 break;
2923 case 27:
2924 encodedcontroller = _lev_ctrl_CC27_EXT;
2925 break;
2926 case 28:
2927 encodedcontroller = _lev_ctrl_CC28_EXT;
2928 break;
2929 case 29:
2930 encodedcontroller = _lev_ctrl_CC29_EXT;
2931 break;
2932 case 30:
2933 encodedcontroller = _lev_ctrl_CC30_EXT;
2934 break;
2935 case 31:
2936 encodedcontroller = _lev_ctrl_CC31_EXT;
2937 break;
2938 case 68:
2939 encodedcontroller = _lev_ctrl_CC68_EXT;
2940 break;
2941 case 69:
2942 encodedcontroller = _lev_ctrl_CC69_EXT;
2943 break;
2944 case 70:
2945 encodedcontroller = _lev_ctrl_CC70_EXT;
2946 break;
2947 case 71:
2948 encodedcontroller = _lev_ctrl_CC71_EXT;
2949 break;
2950 case 72:
2951 encodedcontroller = _lev_ctrl_CC72_EXT;
2952 break;
2953 case 73:
2954 encodedcontroller = _lev_ctrl_CC73_EXT;
2955 break;
2956 case 74:
2957 encodedcontroller = _lev_ctrl_CC74_EXT;
2958 break;
2959 case 75:
2960 encodedcontroller = _lev_ctrl_CC75_EXT;
2961 break;
2962 case 76:
2963 encodedcontroller = _lev_ctrl_CC76_EXT;
2964 break;
2965 case 77:
2966 encodedcontroller = _lev_ctrl_CC77_EXT;
2967 break;
2968 case 78:
2969 encodedcontroller = _lev_ctrl_CC78_EXT;
2970 break;
2971 case 79:
2972 encodedcontroller = _lev_ctrl_CC79_EXT;
2973 break;
2974 case 84:
2975 encodedcontroller = _lev_ctrl_CC84_EXT;
2976 break;
2977 case 85:
2978 encodedcontroller = _lev_ctrl_CC85_EXT;
2979 break;
2980 case 86:
2981 encodedcontroller = _lev_ctrl_CC86_EXT;
2982 break;
2983 case 87:
2984 encodedcontroller = _lev_ctrl_CC87_EXT;
2985 break;
2986 case 89:
2987 encodedcontroller = _lev_ctrl_CC89_EXT;
2988 break;
2989 case 90:
2990 encodedcontroller = _lev_ctrl_CC90_EXT;
2991 break;
2992 case 96:
2993 encodedcontroller = _lev_ctrl_CC96_EXT;
2994 break;
2995 case 97:
2996 encodedcontroller = _lev_ctrl_CC97_EXT;
2997 break;
2998 case 102:
2999 encodedcontroller = _lev_ctrl_CC102_EXT;
3000 break;
3001 case 103:
3002 encodedcontroller = _lev_ctrl_CC103_EXT;
3003 break;
3004 case 104:
3005 encodedcontroller = _lev_ctrl_CC104_EXT;
3006 break;
3007 case 105:
3008 encodedcontroller = _lev_ctrl_CC105_EXT;
3009 break;
3010 case 106:
3011 encodedcontroller = _lev_ctrl_CC106_EXT;
3012 break;
3013 case 107:
3014 encodedcontroller = _lev_ctrl_CC107_EXT;
3015 break;
3016 case 108:
3017 encodedcontroller = _lev_ctrl_CC108_EXT;
3018 break;
3019 case 109:
3020 encodedcontroller = _lev_ctrl_CC109_EXT;
3021 break;
3022 case 110:
3023 encodedcontroller = _lev_ctrl_CC110_EXT;
3024 break;
3025 case 111:
3026 encodedcontroller = _lev_ctrl_CC111_EXT;
3027 break;
3028 case 112:
3029 encodedcontroller = _lev_ctrl_CC112_EXT;
3030 break;
3031 case 113:
3032 encodedcontroller = _lev_ctrl_CC113_EXT;
3033 break;
3034 case 114:
3035 encodedcontroller = _lev_ctrl_CC114_EXT;
3036 break;
3037 case 115:
3038 encodedcontroller = _lev_ctrl_CC115_EXT;
3039 break;
3040 case 116:
3041 encodedcontroller = _lev_ctrl_CC116_EXT;
3042 break;
3043 case 117:
3044 encodedcontroller = _lev_ctrl_CC117_EXT;
3045 break;
3046 case 118:
3047 encodedcontroller = _lev_ctrl_CC118_EXT;
3048 break;
3049 case 119:
3050 encodedcontroller = _lev_ctrl_CC119_EXT;
3051 break;
3052
3053 default:
3054 throw gig::Exception("leverage controller number is not supported by the gig format");
3055 }
3056 break;
3057 default:
3058 throw gig::Exception("Unknown leverage controller type.");
3059 }
3060 return encodedcontroller;
3061 }
3062
3063 DimensionRegion::~DimensionRegion() {
3064 Instances--;
3065 if (!Instances) {
3066 // delete the velocity->volume tables
3067 VelocityTableMap::iterator iter;
3068 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
3069 double* pTable = iter->second;
3070 if (pTable) delete[] pTable;
3071 }
3072 pVelocityTables->clear();
3073 delete pVelocityTables;
3074 pVelocityTables = NULL;
3075 }
3076 if (VelocityTable) delete[] VelocityTable;
3077 }
3078
3090 double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
3091 return pVelocityAttenuationTable[MIDIKeyVelocity];
3092 }
3093
3094 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
3095 return pVelocityReleaseTable[MIDIKeyVelocity];
3096 }
3097
3098 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
3099 return pVelocityCutoffTable[MIDIKeyVelocity];
3100 }
3101
3107 pVelocityAttenuationTable =
3108 GetVelocityTable(
3110 );
3111 VelocityResponseCurve = curve;
3112 }
3113
3119 pVelocityAttenuationTable =
3120 GetVelocityTable(
3122 );
3123 VelocityResponseDepth = depth;
3124 }
3125
3131 pVelocityAttenuationTable =
3132 GetVelocityTable(
3134 );
3136 }
3137
3143 pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
3145 }
3146
3152 pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
3154 }
3155
3161 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
3162 VCFCutoffController = controller;
3163 }
3164
3170 pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
3171 VCFVelocityCurve = curve;
3172 }
3173
3179 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
3181 }
3182
3188 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
3189 VCFVelocityScale = scaling;
3190 }
3191
3192 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
3193
3194 // line-segment approximations of the 15 velocity curves
3195
3196 // linear
3197 const int lin0[] = { 1, 1, 127, 127 };
3198 const int lin1[] = { 1, 21, 127, 127 };
3199 const int lin2[] = { 1, 45, 127, 127 };
3200 const int lin3[] = { 1, 74, 127, 127 };
3201 const int lin4[] = { 1, 127, 127, 127 };
3202
3203 // non-linear
3204 const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
3205 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
3206 127, 127 };
3207 const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
3208 127, 127 };
3209 const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
3210 127, 127 };
3211 const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
3212
3213 // special
3214 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
3215 113, 127, 127, 127 };
3216 const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
3217 118, 127, 127, 127 };
3218 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
3219 85, 90, 91, 127, 127, 127 };
3220 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
3221 117, 127, 127, 127 };
3222 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
3223 127, 127 };
3224
3225 // this is only used by the VCF velocity curve
3226 const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
3227 91, 127, 127, 127 };
3228
3229 const int* const curves[] = { non0, non1, non2, non3, non4,
3230 lin0, lin1, lin2, lin3, lin4,
3231 spe0, spe1, spe2, spe3, spe4, spe5 };
3232
3233 double* const table = new double[128];
3234
3235 const int* curve = curves[curveType * 5 + depth];
3236 const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
3237
3238 table[0] = 0;
3239 for (int x = 1 ; x < 128 ; x++) {
3240
3241 if (x > curve[2]) curve += 2;
3242 double y = curve[1] + (x - curve[0]) *
3243 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
3244 y = y / 127;
3245
3246 // Scale up for s > 20, down for s < 20. When
3247 // down-scaling, the curve still ends at 1.0.
3248 if (s < 20 && y >= 0.5)
3249 y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
3250 else
3251 y = y * (s / 20.0);
3252 if (y > 1) y = 1;
3253
3254 table[x] = y;
3255 }
3256 return table;
3257 }
3258
3259
3260// *************** Region ***************
3261// *
3262
3263 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
3264 // Initialization
3265 Dimensions = 0;
3266 for (int i = 0; i < 256; i++) {
3267 pDimensionRegions[i] = NULL;
3268 }
3269 Layers = 1;
3270 File* file = (File*) GetParent()->GetParent();
3271 int dimensionBits = (file->pVersion && file->pVersion->major > 2) ? 8 : 5;
3272
3273 // Actual Loading
3274
3275 if (!file->GetAutoLoad()) return;
3276
3277 LoadDimensionRegions(rgnList);
3278
3279 RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
3280 if (_3lnk) {
3281 _3lnk->SetPos(0);
3282
3283 DimensionRegions = _3lnk->ReadUint32();
3284 for (int i = 0; i < dimensionBits; i++) {
3285 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
3286 uint8_t bits = _3lnk->ReadUint8();
3287 _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
3288 _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
3289 uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
3290 if (dimension == dimension_none) { // inactive dimension
3291 pDimensionDefinitions[i].dimension = dimension_none;
3292 pDimensionDefinitions[i].bits = 0;
3293 pDimensionDefinitions[i].zones = 0;
3294 pDimensionDefinitions[i].split_type = split_type_bit;
3295 pDimensionDefinitions[i].zone_size = 0;
3296 }
3297 else { // active dimension
3298 pDimensionDefinitions[i].dimension = dimension;
3299 pDimensionDefinitions[i].bits = bits;
3300 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
3301 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
3302 pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
3303 Dimensions++;
3304
3305 // if this is a layer dimension, remember the amount of layers
3306 if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
3307 }
3308 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
3309 }
3310 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
3311
3312 // if there's a velocity dimension and custom velocity zone splits are used,
3313 // update the VelocityTables in the dimension regions
3314 UpdateVelocityTable();
3315
3316 // jump to start of the wave pool indices (if not already there)
3317 if (file->pVersion && file->pVersion->major > 2)
3318 _3lnk->SetPos(68); // version 3 has a different 3lnk structure
3319 else
3320 _3lnk->SetPos(44);
3321
3322 // load sample references (if auto loading is enabled)
3323 if (file->GetAutoLoad()) {
3324 for (uint i = 0; i < DimensionRegions; i++) {
3325 uint32_t wavepoolindex = _3lnk->ReadUint32();
3326 if (file->pWavePoolTable && pDimensionRegions[i])
3327 pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3328 }
3329 GetSample(); // load global region sample reference
3330 }
3331 } else {
3332 DimensionRegions = 0;
3333 for (int i = 0 ; i < 8 ; i++) {
3334 pDimensionDefinitions[i].dimension = dimension_none;
3335 pDimensionDefinitions[i].bits = 0;
3336 pDimensionDefinitions[i].zones = 0;
3337 }
3338 }
3339
3340 // make sure there is at least one dimension region
3341 if (!DimensionRegions) {
3342 RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3343 if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3344 RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3345 pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3346 DimensionRegions = 1;
3347 }
3348 }
3349
3360 void Region::UpdateChunks(progress_t* pProgress) {
3361 // in the gig format we don't care about the Region's sample reference
3362 // but we still have to provide some existing one to not corrupt the
3363 // file, so to avoid the latter we simply always assign the sample of
3364 // the first dimension region of this region
3365 pSample = pDimensionRegions[0]->pSample;
3366
3367 // first update base class's chunks
3368 DLS::Region::UpdateChunks(pProgress);
3369
3370 // update dimension region's chunks
3371 for (int i = 0; i < DimensionRegions; i++) {
3372 pDimensionRegions[i]->UpdateChunks(pProgress);
3373 }
3374
3375 File* pFile = (File*) GetParent()->GetParent();
3376 const bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;
3377 const int iMaxDimensions = versiongt2 ? 8 : 5;
3378 const int iMaxDimensionRegions = versiongt2 ? 256 : 32;
3379
3380 // make sure '3lnk' chunk exists
3381 RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3382 if (!_3lnk) {
3383 const int _3lnkChunkSize = versiongt2 ? 1092 : 172;
3384 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3385 memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3386
3387 // move 3prg to last position
3388 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3389 }
3390
3391 // update dimension definitions in '3lnk' chunk
3392 uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3393 store32(&pData[0], DimensionRegions);
3394 int shift = 0;
3395 for (int i = 0; i < iMaxDimensions; i++) {
3396 pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3397 pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3398 pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3399 pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3400 pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3401 // next 3 bytes unknown, always zero?
3402
3403 shift += pDimensionDefinitions[i].bits;
3404 }
3405
3406 // update wave pool table in '3lnk' chunk
3407 const int iWavePoolOffset = versiongt2 ? 68 : 44;
3408 for (uint i = 0; i < iMaxDimensionRegions; i++) {
3409 int iWaveIndex = -1;
3410 if (i < DimensionRegions) {
3411 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3412 File::SampleList::iterator iter = pFile->pSamples->begin();
3413 File::SampleList::iterator end = pFile->pSamples->end();
3414 for (int index = 0; iter != end; ++iter, ++index) {
3415 if (*iter == pDimensionRegions[i]->pSample) {
3416 iWaveIndex = index;
3417 break;
3418 }
3419 }
3420 }
3421 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3422 }
3423
3424 // The following chunks are just added for compatibility with the
3425 // GigaStudio software, which would show a warning if these were
3426 // missing. However currently these chunks don't cover any useful
3427 // data. So if this gig file uses any of our own gig format
3428 // extensions which would cause this gig file to be unloadable
3429 // with GSt software anyway, then just skip these GSt compatibility
3430 // chunks here as well.
3431 if (versiongt2 && !UsesAnyGigFormatExtension()) {
3432 // add 3dnm list which always seems to be empty
3433 RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM);
3434 if (!_3dnm) _3dnm = pCkRegion->AddSubList(LIST_TYPE_3DNM);
3435
3436 // add 3ddp chunk which always seems to have 16 bytes of 0xFF
3437 RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3438 if (!_3ddp) _3ddp = pCkRegion->AddSubChunk(CHUNK_ID_3DDP, 16);
3439 uint8_t* pData = (uint8_t*) _3ddp->LoadChunkData();
3440 for (int i = 0; i < 16; i += 4) {
3441 store32(&pData[i], 0xFFFFFFFF);
3442 }
3443
3444 // move 3dnm and 3ddp to the end of the region list
3445 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3DNM), (RIFF::Chunk*)NULL);
3446 pCkRegion->MoveSubChunk(pCkRegion->GetSubChunk(CHUNK_ID_3DDP), (RIFF::Chunk*)NULL);
3447 } else {
3448 // this is intended for the user switching from GSt >= 3 version
3449 // back to an older format version, delete GSt3 chunks ...
3450 RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM);
3451 if (_3dnm) pCkRegion->DeleteSubChunk(_3dnm);
3452
3453 RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3454 if (_3ddp) pCkRegion->DeleteSubChunk(_3ddp);
3455 }
3456 }
3457
3458 void Region::LoadDimensionRegions(RIFF::List* rgn) {
3459 RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3460 if (_3prg) {
3461 int dimensionRegionNr = 0;
3462 size_t i = 0;
3463 for (RIFF::List* _3ewl = _3prg->GetSubListAt(i); _3ewl;
3464 _3ewl = _3prg->GetSubListAt(++i))
3465 {
3466 if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3467 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3468 dimensionRegionNr++;
3469 }
3470 }
3471 if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3472 }
3473 }
3474
3475 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3476 // update KeyRange struct and make sure regions are in correct order
3477 DLS::Region::SetKeyRange(Low, High);
3478 // update Region key table for fast lookup
3479 ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3480 }
3481
3482 void Region::UpdateVelocityTable() {
3483 // get velocity dimension's index
3484 int veldim = -1;
3485 for (int i = 0 ; i < Dimensions ; i++) {
3486 if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3487 veldim = i;
3488 break;
3489 }
3490 }
3491 if (veldim == -1) return;
3492
3493 int step = 1;
3494 for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3495 int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3496
3497 // loop through all dimension regions for all dimensions except the velocity dimension
3498 int dim[8] = { 0 };
3499 for (int i = 0 ; i < DimensionRegions ; i++) {
3500 const int end = i + step * pDimensionDefinitions[veldim].zones;
3501
3502 // create a velocity table for all cases where the velocity zone is zero
3503 if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3504 pDimensionRegions[i]->VelocityUpperLimit) {
3505 // create the velocity table
3506 uint8_t* table = pDimensionRegions[i]->VelocityTable;
3507 if (!table) {
3508 table = new uint8_t[128];
3509 pDimensionRegions[i]->VelocityTable = table;
3510 }
3511 int tableidx = 0;
3512 int velocityZone = 0;
3513 if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3514 for (int k = i ; k < end ; k += step) {
3515 DimensionRegion *d = pDimensionRegions[k];
3516 for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3517 velocityZone++;
3518 }
3519 } else { // gig2
3520 for (int k = i ; k < end ; k += step) {
3521 DimensionRegion *d = pDimensionRegions[k];
3522 for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3523 velocityZone++;
3524 }
3525 }
3526 } else {
3527 if (pDimensionRegions[i]->VelocityTable) {
3528 delete[] pDimensionRegions[i]->VelocityTable;
3530 }
3531 }
3532
3533 // jump to the next case where the velocity zone is zero
3534 int j;
3535 int shift = 0;
3536 for (j = 0 ; j < Dimensions ; j++) {
3537 if (j == veldim) i += skipveldim; // skip velocity dimension
3538 else {
3539 dim[j]++;
3540 if (dim[j] < pDimensionDefinitions[j].zones) break;
3541 else {
3542 // skip unused dimension regions
3543 dim[j] = 0;
3544 i += ((1 << pDimensionDefinitions[j].bits) -
3545 pDimensionDefinitions[j].zones) << shift;
3546 }
3547 }
3548 shift += pDimensionDefinitions[j].bits;
3549 }
3550 if (j == Dimensions) break;
3551 }
3552 }
3553
3570 // some initial sanity checks of the given dimension definition
3571 if (pDimDef->zones < 2)
3572 throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3573 if (pDimDef->bits < 1)
3574 throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3575 if (pDimDef->dimension == dimension_samplechannel) {
3576 if (pDimDef->zones != 2)
3577 throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3578 if (pDimDef->bits != 1)
3579 throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3580 }
3581
3582 // check if max. amount of dimensions reached
3583 File* file = (File*) GetParent()->GetParent();
3584 const int iMaxDimensions = (file->pVersion && file->pVersion->major > 2) ? 8 : 5;
3585 if (Dimensions >= iMaxDimensions)
3586 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3587 // check if max. amount of dimension bits reached
3588 int iCurrentBits = 0;
3589 for (int i = 0; i < Dimensions; i++)
3590 iCurrentBits += pDimensionDefinitions[i].bits;
3591 if (iCurrentBits >= iMaxDimensions)
3592 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3593 const int iNewBits = iCurrentBits + pDimDef->bits;
3594 if (iNewBits > iMaxDimensions)
3595 throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3596 // check if there's already a dimensions of the same type
3597 for (int i = 0; i < Dimensions; i++)
3598 if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3599 throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3600
3601 // pos is where the new dimension should be placed, normally
3602 // last in list, except for the samplechannel dimension which
3603 // has to be first in list
3604 int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3605 int bitpos = 0;
3606 for (int i = 0 ; i < pos ; i++)
3607 bitpos += pDimensionDefinitions[i].bits;
3608
3609 // make room for the new dimension
3610 for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3611 for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3612 for (int j = Dimensions ; j > pos ; j--) {
3615 }
3616 }
3617
3618 // assign definition of new dimension
3619 pDimensionDefinitions[pos] = *pDimDef;
3620
3621 // auto correct certain dimension definition fields (where possible)
3623 __resolveSplitType(pDimensionDefinitions[pos].dimension);
3625 __resolveZoneSize(pDimensionDefinitions[pos]);
3626
3627 // create new dimension region(s) for this new dimension, and make
3628 // sure that the dimension regions are placed correctly in both the
3629 // RIFF list and the pDimensionRegions array
3630 RIFF::Chunk* moveTo = NULL;
3631 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3632 for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3633 for (int k = 0 ; k < (1 << bitpos) ; k++) {
3634 pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3635 }
3636 for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3637 for (int k = 0 ; k < (1 << bitpos) ; k++) {
3638 RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3639 if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3640 // create a new dimension region and copy all parameter values from
3641 // an existing dimension region
3642 pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3643 new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3644
3646 }
3647 }
3648 moveTo = pDimensionRegions[i]->pParentList;
3649 }
3650
3651 // initialize the upper limits for this dimension
3652 int mask = (1 << bitpos) - 1;
3653 for (int z = 0 ; z < pDimDef->zones ; z++) {
3654 uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3655 for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3656 pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3657 (z << bitpos) |
3658 (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3659 }
3660 }
3661
3662 Dimensions++;
3663
3664 // if this is a layer dimension, update 'Layers' attribute
3665 if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3666
3667 UpdateVelocityTable();
3668 }
3669
3682 // get dimension's index
3683 int iDimensionNr = -1;
3684 for (int i = 0; i < Dimensions; i++) {
3685 if (&pDimensionDefinitions[i] == pDimDef) {
3686 iDimensionNr = i;
3687 break;
3688 }
3689 }
3690 if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3691
3692 // get amount of bits below the dimension to delete
3693 int iLowerBits = 0;
3694 for (int i = 0; i < iDimensionNr; i++)
3695 iLowerBits += pDimensionDefinitions[i].bits;
3696
3697 // get amount ot bits above the dimension to delete
3698 int iUpperBits = 0;
3699 for (int i = iDimensionNr + 1; i < Dimensions; i++)
3700 iUpperBits += pDimensionDefinitions[i].bits;
3701
3702 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3703
3704 // delete dimension regions which belong to the given dimension
3705 // (that is where the dimension's bit > 0)
3706 for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3707 for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3708 for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3709 int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3710 iObsoleteBit << iLowerBits |
3711 iLowerBit;
3712
3713 _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3714 delete pDimensionRegions[iToDelete];
3715 pDimensionRegions[iToDelete] = NULL;
3717 }
3718 }
3719 }
3720
3721 // defrag pDimensionRegions array
3722 // (that is remove the NULL spaces within the pDimensionRegions array)
3723 for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3724 if (!pDimensionRegions[iTo]) {
3725 if (iFrom <= iTo) iFrom = iTo + 1;
3726 while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3727 if (iFrom < 256 && pDimensionRegions[iFrom]) {
3729 pDimensionRegions[iFrom] = NULL;
3730 }
3731 }
3732 }
3733
3734 // remove the this dimension from the upper limits arrays
3735 for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3737 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3739 }
3740 d->DimensionUpperLimits[Dimensions - 1] = 127;
3741 }
3742
3743 // 'remove' dimension definition
3744 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3746 }
3750
3751 Dimensions--;
3752
3753 // if this was a layer dimension, update 'Layers' attribute
3754 if (pDimDef->dimension == dimension_layer) Layers = 1;
3755 }
3756
3772 if (!Dimensions)
3773 throw gig::Exception("Could not delete dimension zone, because there is no dimension at all.");
3775 if (!oldDef)
3776 throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3777 if (oldDef->zones <= 2)
3778 throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3779 if (zone < 0 || zone >= oldDef->zones)
3780 throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3781
3782 const int newZoneSize = oldDef->zones - 1;
3783
3784 // create a temporary Region which just acts as a temporary copy
3785 // container and will be deleted at the end of this function and will
3786 // also not be visible through the API during this process
3787 gig::Region* tempRgn = NULL;
3788 {
3789 // adding these temporary chunks is probably not even necessary
3790 Instrument* instr = static_cast<Instrument*>(GetParent());
3791 RIFF::List* pCkInstrument = instr->pCkInstrument;
3792 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3793 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3794 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3795 tempRgn = new Region(instr, rgn);
3796 }
3797
3798 // copy this region's dimensions (with already the dimension split size
3799 // requested by the arguments of this method call) to the temporary
3800 // region, and don't use Region::CopyAssign() here for this task, since
3801 // it would also alter fast lookup helper variables here and there
3802 dimension_def_t newDef = {};
3803 for (int i = 0; i < Dimensions; ++i) {
3804 dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3805 // is this the dimension requested by the method arguments? ...
3806 if (def.dimension == type) { // ... if yes, decrement zone amount by one
3807 def.zones = newZoneSize;
3808 if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3809 newDef = def;
3810 }
3811 tempRgn->AddDimension(&def);
3812 }
3813 // silence clang sanitizer warning
3814 if (newDef.dimension == dimension_none)
3815 throw gig::Exception("Unexpected internal failure resolving dimension in DeleteDimensionZone() [this is a bug].");
3816
3817 // find the dimension index in the tempRegion which is the dimension
3818 // type passed to this method (paranoidly expecting different order)
3819 int tempReducedDimensionIndex = -1;
3820 for (int d = 0; d < tempRgn->Dimensions; ++d) {
3821 if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3822 tempReducedDimensionIndex = d;
3823 break;
3824 }
3825 }
3826
3827 // copy dimension regions from this region to the temporary region
3828 for (int iDst = 0; iDst < 256; ++iDst) {
3829 DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3830 if (!dstDimRgn) continue;
3831 std::map<dimension_t,int> dimCase;
3832 bool isValidZone = true;
3833 for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3834 const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3835 dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3836 (iDst >> baseBits) & ((1 << dstBits) - 1);
3837 baseBits += dstBits;
3838 // there are also DimensionRegion objects of unused zones, skip them
3839 if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3840 isValidZone = false;
3841 break;
3842 }
3843 }
3844 if (!isValidZone) continue;
3845 // a bit paranoid: cope with the chance that the dimensions would
3846 // have different order in source and destination regions
3847 const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3848 if (dimCase[type] >= zone) dimCase[type]++;
3849 DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3850 dstDimRgn->CopyAssign(srcDimRgn);
3851 // if this is the upper most zone of the dimension passed to this
3852 // method, then correct (raise) its upper limit to 127
3853 if (newDef.split_type == split_type_normal && isLastZone)
3854 dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3855 }
3856
3857 // now tempRegion's dimensions and DimensionRegions basically reflect
3858 // what we wanted to get for this actual Region here, so we now just
3859 // delete and recreate the dimension in question with the new amount
3860 // zones and then copy back from tempRegion. we're actually deleting and
3861 // recreating all dimensions here, to avoid altering the precise order
3862 // of the dimensions (which would not be an error per se, but it would
3863 // cause usability issues with instrument editors)
3864 {
3865 std::vector<dimension_def_t> oldDefs;
3866 for (int i = 0; i < Dimensions; ++i)
3867 oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference
3868 for (int i = Dimensions - 1; i >= 0; --i)
3870 for (int i = 0; i < oldDefs.size(); ++i) {
3871 dimension_def_t& def = oldDefs[i];
3873 (def.dimension == newDef.dimension) ? &newDef : &def
3874 );
3875 }
3876 }
3877 for (int iSrc = 0; iSrc < 256; ++iSrc) {
3878 DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3879 if (!srcDimRgn) continue;
3880 std::map<dimension_t,int> dimCase;
3881 for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3882 const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3883 dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3884 (iSrc >> baseBits) & ((1 << srcBits) - 1);
3885 baseBits += srcBits;
3886 }
3887 // a bit paranoid: cope with the chance that the dimensions would
3888 // have different order in source and destination regions
3889 DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3890 if (!dstDimRgn) continue;
3891 dstDimRgn->CopyAssign(srcDimRgn);
3892 }
3893
3894 // delete temporary region
3895 tempRgn->DeleteChunks();
3896 delete tempRgn;
3897
3898 UpdateVelocityTable();
3899 }
3900
3916 if (!Dimensions)
3917 throw gig::Exception("Could not split dimension zone, because there is no dimension at all.");
3919 if (!oldDef)
3920 throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3921 if (zone < 0 || zone >= oldDef->zones)
3922 throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3923
3924 const int newZoneSize = oldDef->zones + 1;
3925
3926 // create a temporary Region which just acts as a temporary copy
3927 // container and will be deleted at the end of this function and will
3928 // also not be visible through the API during this process
3929 gig::Region* tempRgn = NULL;
3930 {
3931 // adding these temporary chunks is probably not even necessary
3932 Instrument* instr = static_cast<Instrument*>(GetParent());
3933 RIFF::List* pCkInstrument = instr->pCkInstrument;
3934 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3935 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3936 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3937 tempRgn = new Region(instr, rgn);
3938 }
3939
3940 // copy this region's dimensions (with already the dimension split size
3941 // requested by the arguments of this method call) to the temporary
3942 // region, and don't use Region::CopyAssign() here for this task, since
3943 // it would also alter fast lookup helper variables here and there
3944 dimension_def_t newDef = {};
3945 for (int i = 0; i < Dimensions; ++i) {
3946 dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3947 // is this the dimension requested by the method arguments? ...
3948 if (def.dimension == type) { // ... if yes, increment zone amount by one
3949 def.zones = newZoneSize;
3950 if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3951 newDef = def;
3952 }
3953 tempRgn->AddDimension(&def);
3954 }
3955 // silence clang sanitizer warning
3956 if (newDef.dimension == dimension_none)
3957 throw gig::Exception("Unexpected internal failure resolving dimension in SplitDimensionZone() [this is a bug].");
3958
3959 // find the dimension index in the tempRegion which is the dimension
3960 // type passed to this method (paranoidly expecting different order)
3961 int tempIncreasedDimensionIndex = -1;
3962 for (int d = 0; d < tempRgn->Dimensions; ++d) {
3963 if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3964 tempIncreasedDimensionIndex = d;
3965 break;
3966 }
3967 }
3968
3969 // copy dimension regions from this region to the temporary region
3970 for (int iSrc = 0; iSrc < 256; ++iSrc) {
3971 DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3972 if (!srcDimRgn) continue;
3973 std::map<dimension_t,int> dimCase;
3974 bool isValidZone = true;
3975 for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3976 const int srcBits = pDimensionDefinitions[d].bits;
3977 dimCase[pDimensionDefinitions[d].dimension] =
3978 (iSrc >> baseBits) & ((1 << srcBits) - 1);
3979 // there are also DimensionRegion objects for unused zones, skip them
3980 if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3981 isValidZone = false;
3982 break;
3983 }
3984 baseBits += srcBits;
3985 }
3986 if (!isValidZone) continue;
3987 // a bit paranoid: cope with the chance that the dimensions would
3988 // have different order in source and destination regions
3989 if (dimCase[type] > zone) dimCase[type]++;
3990 DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3991 dstDimRgn->CopyAssign(srcDimRgn);
3992 // if this is the requested zone to be splitted, then also copy
3993 // the source DimensionRegion to the newly created target zone
3994 // and set the old zones upper limit lower
3995 if (dimCase[type] == zone) {
3996 // lower old zones upper limit
3997 if (newDef.split_type == split_type_normal) {
3998 const int high =
3999 dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
4000 int low = 0;
4001 if (zone > 0) {
4002 std::map<dimension_t,int> lowerCase = dimCase;
4003 lowerCase[type]--;
4004 DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
4005 low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
4006 }
4007 dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
4008 }
4009 // fill the newly created zone of the divided zone as well
4010 dimCase[type]++;
4011 dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
4012 dstDimRgn->CopyAssign(srcDimRgn);
4013 }
4014 }
4015
4016 // now tempRegion's dimensions and DimensionRegions basically reflect
4017 // what we wanted to get for this actual Region here, so we now just
4018 // delete and recreate the dimension in question with the new amount
4019 // zones and then copy back from tempRegion. we're actually deleting and
4020 // recreating all dimensions here, to avoid altering the precise order
4021 // of the dimensions (which would not be an error per se, but it would
4022 // cause usability issues with instrument editors)
4023 {
4024 std::vector<dimension_def_t> oldDefs;
4025 for (int i = 0; i < Dimensions; ++i)
4026 oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference
4027 for (int i = Dimensions - 1; i >= 0; --i)
4029 for (int i = 0; i < oldDefs.size(); ++i) {
4030 dimension_def_t& def = oldDefs[i];
4032 (def.dimension == newDef.dimension) ? &newDef : &def
4033 );
4034 }
4035 }
4036 for (int iSrc = 0; iSrc < 256; ++iSrc) {
4037 DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
4038 if (!srcDimRgn) continue;
4039 std::map<dimension_t,int> dimCase;
4040 for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
4041 const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
4042 dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
4043 (iSrc >> baseBits) & ((1 << srcBits) - 1);
4044 baseBits += srcBits;
4045 }
4046 // a bit paranoid: cope with the chance that the dimensions would
4047 // have different order in source and destination regions
4048 DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
4049 if (!dstDimRgn) continue;
4050 dstDimRgn->CopyAssign(srcDimRgn);
4051 }
4052
4053 // delete temporary region
4054 tempRgn->DeleteChunks();
4055 delete tempRgn;
4056
4057 UpdateVelocityTable();
4058 }
4059
4075 if (oldType == newType) return;
4077 if (!def)
4078 throw gig::Exception("No dimension with provided old dimension type exists on this region");
4079 if (newType == dimension_samplechannel && def->zones != 2)
4080 throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
4081 if (GetDimensionDefinition(newType))
4082 throw gig::Exception("There is already a dimension with requested new dimension type on this region");
4083 def->dimension = newType;
4084 def->split_type = __resolveSplitType(newType);
4085 }
4086
4087 DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
4088 uint8_t bits[8] = {};
4089 for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
4090 it != DimCase.end(); ++it)
4091 {
4092 for (int d = 0; d < Dimensions; ++d) {
4093 if (pDimensionDefinitions[d].dimension == it->first) {
4094 bits[d] = it->second;
4095 goto nextDimCaseSlice;
4096 }
4097 }
4098 assert(false); // do crash ... too harsh maybe ? ignore it instead ?
4099 nextDimCaseSlice:
4100 ; // noop
4101 }
4102 return GetDimensionRegionByBit(bits);
4103 }
4104
4115 for (int i = 0; i < Dimensions; ++i)
4116 if (pDimensionDefinitions[i].dimension == type)
4117 return &pDimensionDefinitions[i];
4118 return NULL;
4119 }
4120
4122 for (int i = 0; i < 256; i++) {
4123 if (pDimensionRegions[i]) delete pDimensionRegions[i];
4124 }
4125 }
4126
4146 uint8_t bits;
4147 int veldim = -1;
4148 int velbitpos = 0;
4149 int bitpos = 0;
4150 int dimregidx = 0;
4151 for (uint i = 0; i < Dimensions; i++) {
4152 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
4153 // the velocity dimension must be handled after the other dimensions
4154 veldim = i;
4155 velbitpos = bitpos;
4156 } else {
4157 switch (pDimensionDefinitions[i].split_type) {
4158 case split_type_normal:
4159 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
4160 // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
4161 for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
4162 if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
4163 }
4164 } else {
4165 // gig2: evenly sized zones
4166 bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
4167 }
4168 break;
4169 case split_type_bit: // the value is already the sought dimension bit number
4170 const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
4171 bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
4172 break;
4173 }
4174 dimregidx |= bits << bitpos;
4175 }
4176 bitpos += pDimensionDefinitions[i].bits;
4177 }
4178 DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
4179 if (!dimreg) return NULL;
4180 if (veldim != -1) {
4181 // (dimreg is now the dimension region for the lowest velocity)
4182 if (dimreg->VelocityTable) // custom defined zone ranges
4183 bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4184 else // normal split type
4185 bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
4186
4187 const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4188 dimregidx |= (bits & limiter_mask) << velbitpos;
4189 dimreg = pDimensionRegions[dimregidx & 255];
4190 }
4191 return dimreg;
4192 }
4193
4194 int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
4195 uint8_t bits;
4196 int veldim = -1;
4197 int velbitpos = 0;
4198 int bitpos = 0;
4199 int dimregidx = 0;
4200 for (uint i = 0; i < Dimensions; i++) {
4201 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
4202 // the velocity dimension must be handled after the other dimensions
4203 veldim = i;
4204 velbitpos = bitpos;
4205 } else {
4206 switch (pDimensionDefinitions[i].split_type) {
4207 case split_type_normal:
4208 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
4209 // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
4210 for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
4211 if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
4212 }
4213 } else {
4214 // gig2: evenly sized zones
4215 bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
4216 }
4217 break;
4218 case split_type_bit: // the value is already the sought dimension bit number
4219 const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
4220 bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
4221 break;
4222 }
4223 dimregidx |= bits << bitpos;
4224 }
4225 bitpos += pDimensionDefinitions[i].bits;
4226 }
4227 dimregidx &= 255;
4228 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
4229 if (!dimreg) return -1;
4230 if (veldim != -1) {
4231 // (dimreg is now the dimension region for the lowest velocity)
4232 if (dimreg->VelocityTable) // custom defined zone ranges
4233 bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4234 else // normal split type
4235 bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
4236
4237 const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4238 dimregidx |= (bits & limiter_mask) << velbitpos;
4239 dimregidx &= 255;
4240 }
4241 return dimregidx;
4242 }
4243
4255 return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
4256 << pDimensionDefinitions[5].bits | DimBits[5])
4257 << pDimensionDefinitions[4].bits | DimBits[4])
4258 << pDimensionDefinitions[3].bits | DimBits[3])
4259 << pDimensionDefinitions[2].bits | DimBits[2])
4260 << pDimensionDefinitions[1].bits | DimBits[1])
4261 << pDimensionDefinitions[0].bits | DimBits[0]];
4262 }
4263
4274 if (pSample) return static_cast<gig::Sample*>(pSample);
4275 else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
4276 }
4277
4278 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
4279 if ((int32_t)WavePoolTableIndex == -1) return NULL;
4280 File* file = (File*) GetParent()->GetParent();
4281 if (!file->pWavePoolTable) return NULL;
4282 if (WavePoolTableIndex + 1 > file->WavePoolCount) return NULL;
4283 // for new files or files >= 2 GB use 64 bit wave pool offsets
4284 if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4285 // use 64 bit wave pool offsets (treating this as large file)
4286 uint64_t soughtoffset =
4287 uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4288 uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4289 size_t i = 0;
4290 for (Sample* sample = file->GetSample(i, pProgress); sample;
4291 sample = file->GetSample(++i))
4292 {
4293 if (sample->ullWavePoolOffset == soughtoffset)
4294 return sample;
4295 }
4296 } else {
4297 // use extension files and 32 bit wave pool offsets
4298 file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4299 file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4300 size_t i = 0;
4301 for (Sample* sample = file->GetSample(i, pProgress); sample;
4302 sample = file->GetSample(++i))
4303 {
4304 if (sample->ullWavePoolOffset == soughtoffset &&
4305 sample->FileNo == soughtfileno) return sample;
4306 }
4307 }
4308 return NULL;
4309 }
4310
4320 void Region::CopyAssign(const Region* orig) {
4321 CopyAssign(orig, NULL);
4322 }
4323
4331 void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4332 // handle base classes
4334
4335 if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4336 pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4337 }
4338
4339 // handle own member variables
4340 for (int i = Dimensions - 1; i >= 0; --i) {
4342 }
4343 Layers = 0; // just to be sure
4344 for (int i = 0; i < orig->Dimensions; i++) {
4345 // we need to copy the dim definition here, to avoid the compiler
4346 // complaining about const-ness issue
4348 AddDimension(&def);
4349 }
4350 for (int i = 0; i < 256; i++) {
4351 if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4353 orig->pDimensionRegions[i],
4354 mSamples
4355 );
4356 }
4357 }
4358 Layers = orig->Layers;
4359 }
4360
4374 bool Region::UsesAnyGigFormatExtension() const {
4375 for (int i = 0; i < 256; i++) {
4376 if (pDimensionRegions[i]) {
4377 if (pDimensionRegions[i]->UsesAnyGigFormatExtension())
4378 return true;
4379 }
4380 }
4381 return false;
4382 }
4383
4384
4385// *************** MidiRule ***************
4386// *
4387
4388 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4389 _3ewg->SetPos(36);
4390 Triggers = _3ewg->ReadUint8();
4391 _3ewg->SetPos(40);
4392 ControllerNumber = _3ewg->ReadUint8();
4393 _3ewg->SetPos(46);
4394 for (int i = 0 ; i < Triggers ; i++) {
4395 pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4396 pTriggers[i].Descending = _3ewg->ReadUint8();
4397 pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4398 pTriggers[i].Key = _3ewg->ReadUint8();
4399 pTriggers[i].NoteOff = _3ewg->ReadUint8();
4400 pTriggers[i].Velocity = _3ewg->ReadUint8();
4401 pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4402 _3ewg->ReadUint8();
4403 }
4404 }
4405
4406 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4407 ControllerNumber(0),
4408 Triggers(0) {
4409 }
4410
4411 void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4412 pData[32] = 4;
4413 pData[33] = 16;
4414 pData[36] = Triggers;
4415 pData[40] = ControllerNumber;
4416 for (int i = 0 ; i < Triggers ; i++) {
4417 pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4418 pData[47 + i * 8] = pTriggers[i].Descending;
4419 pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4420 pData[49 + i * 8] = pTriggers[i].Key;
4421 pData[50 + i * 8] = pTriggers[i].NoteOff;
4422 pData[51 + i * 8] = pTriggers[i].Velocity;
4423 pData[52 + i * 8] = pTriggers[i].OverridePedal;
4424 }
4425 }
4426
4427 MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4428 _3ewg->SetPos(36);
4429 LegatoSamples = _3ewg->ReadUint8(); // always 12
4430 _3ewg->SetPos(40);
4431 BypassUseController = _3ewg->ReadUint8();
4432 BypassKey = _3ewg->ReadUint8();
4433 BypassController = _3ewg->ReadUint8();
4434 ThresholdTime = _3ewg->ReadUint16();
4435 _3ewg->ReadInt16();
4436 ReleaseTime = _3ewg->ReadUint16();
4437 _3ewg->ReadInt16();
4438 KeyRange.low = _3ewg->ReadUint8();
4439 KeyRange.high = _3ewg->ReadUint8();
4440 _3ewg->SetPos(64);
4441 ReleaseTriggerKey = _3ewg->ReadUint8();
4442 AltSustain1Key = _3ewg->ReadUint8();
4443 AltSustain2Key = _3ewg->ReadUint8();
4444 }
4445
4446 MidiRuleLegato::MidiRuleLegato() :
4447 LegatoSamples(12),
4448 BypassUseController(false),
4449 BypassKey(0),
4450 BypassController(1),
4451 ThresholdTime(20),
4452 ReleaseTime(20),
4453 ReleaseTriggerKey(0),
4454 AltSustain1Key(0),
4455 AltSustain2Key(0)
4456 {
4457 KeyRange.low = KeyRange.high = 0;
4458 }
4459
4460 void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4461 pData[32] = 0;
4462 pData[33] = 16;
4463 pData[36] = LegatoSamples;
4464 pData[40] = BypassUseController;
4465 pData[41] = BypassKey;
4466 pData[42] = BypassController;
4467 store16(&pData[43], ThresholdTime);
4468 store16(&pData[47], ReleaseTime);
4469 pData[51] = KeyRange.low;
4470 pData[52] = KeyRange.high;
4471 pData[64] = ReleaseTriggerKey;
4472 pData[65] = AltSustain1Key;
4473 pData[66] = AltSustain2Key;
4474 }
4475
4476 MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4477 _3ewg->SetPos(36);
4478 Articulations = _3ewg->ReadUint8();
4479 int flags = _3ewg->ReadUint8();
4480 Polyphonic = flags & 8;
4481 Chained = flags & 4;
4482 Selector = (flags & 2) ? selector_controller :
4483 (flags & 1) ? selector_key_switch : selector_none;
4484 Patterns = _3ewg->ReadUint8();
4485 _3ewg->ReadUint8(); // chosen row
4486 _3ewg->ReadUint8(); // unknown
4487 _3ewg->ReadUint8(); // unknown
4488 _3ewg->ReadUint8(); // unknown
4489 KeySwitchRange.low = _3ewg->ReadUint8();
4490 KeySwitchRange.high = _3ewg->ReadUint8();
4491 Controller = _3ewg->ReadUint8();
4492 PlayRange.low = _3ewg->ReadUint8();
4493 PlayRange.high = _3ewg->ReadUint8();
4494
4495 int n = std::min(int(Articulations), 32);
4496 for (int i = 0 ; i < n ; i++) {
4497 _3ewg->ReadString(pArticulations[i], 32);
4498 }
4499 _3ewg->SetPos(1072);
4500 n = std::min(int(Patterns), 32);
4501 for (int i = 0 ; i < n ; i++) {
4502 _3ewg->ReadString(pPatterns[i].Name, 16);
4503 pPatterns[i].Size = _3ewg->ReadUint8();
4504 _3ewg->Read(&pPatterns[i][0], 1, 32);
4505 }
4506 }
4507
4508 MidiRuleAlternator::MidiRuleAlternator() :
4509 Articulations(0),
4510 Patterns(0),
4511 Selector(selector_none),
4512 Controller(0),
4513 Polyphonic(false),
4514 Chained(false)
4515 {
4516 PlayRange.low = PlayRange.high = 0;
4517 KeySwitchRange.low = KeySwitchRange.high = 0;
4518 }
4519
4520 void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4521 pData[32] = 3;
4522 pData[33] = 16;
4523 pData[36] = Articulations;
4524 pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4525 (Selector == selector_controller ? 2 :
4526 (Selector == selector_key_switch ? 1 : 0));
4527 pData[38] = Patterns;
4528
4529 pData[43] = KeySwitchRange.low;
4530 pData[44] = KeySwitchRange.high;
4531 pData[45] = Controller;
4532 pData[46] = PlayRange.low;
4533 pData[47] = PlayRange.high;
4534
4535 char* str = reinterpret_cast<char*>(pData);
4536 int pos = 48;
4537 int n = std::min(int(Articulations), 32);
4538 for (int i = 0 ; i < n ; i++, pos += 32) {
4539 strncpy(&str[pos], pArticulations[i].c_str(), 32);
4540 }
4541
4542 pos = 1072;
4543 n = std::min(int(Patterns), 32);
4544 for (int i = 0 ; i < n ; i++, pos += 49) {
4545 strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4546 pData[pos + 16] = pPatterns[i].Size;
4547 memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4548 }
4549 }
4550
4551// *************** Script ***************
4552// *
4553
4554 Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4555 pGroup = group;
4556 pChunk = ckScri;
4557 if (ckScri) { // object is loaded from file ...
4558 ckScri->SetPos(0);
4559
4560 // read header
4561 uint32_t headerSize = ckScri->ReadUint32();
4562 Compression = (Compression_t) ckScri->ReadUint32();
4563 Encoding = (Encoding_t) ckScri->ReadUint32();
4564 Language = (Language_t) ckScri->ReadUint32();
4565 Bypass = ckScri->ReadUint32() & 1;
4566 crc = ckScri->ReadUint32();
4567 uint32_t nameSize = ckScri->ReadUint32();
4568 Name.resize(nameSize, ' ');
4569 for (int i = 0; i < nameSize; ++i)
4570 Name[i] = ckScri->ReadUint8();
4571 // check if an uuid was already stored along with this script
4572 if (headerSize >= 6*sizeof(int32_t) + nameSize + 16) { // yes ...
4573 for (uint i = 0; i < 16; ++i) {
4574 Uuid[i] = ckScri->ReadUint8();
4575 }
4576 } else { // no uuid yet, generate one now ...
4577 GenerateUuid();
4578 }
4579 // to handle potential future extensions of the header
4580 ckScri->SetPos(sizeof(int32_t) + headerSize);
4581 // read actual script data
4582 uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4583 data.resize(scriptSize);
4584 for (int i = 0; i < scriptSize; ++i)
4585 data[i] = ckScri->ReadUint8();
4586 } else { // this is a new script object, so just initialize it as such ...
4590 Bypass = false;
4591 crc = 0;
4592 Name = "Unnamed Script";
4593 GenerateUuid();
4594 }
4595 }
4596
4597 Script::~Script() {
4598 }
4599
4604 String s;
4605 if (data.empty()) return s;
4606 s.resize(data.size(), ' ');
4607 memcpy(&s[0], &data[0], data.size());
4608 return s;
4609 }
4610
4617 void Script::SetScriptAsText(const String& text) {
4618 data.resize(text.size());
4619 if (text.empty()) return;
4620 memcpy(&data[0], &text[0], text.size());
4621 }
4622
4633 }
4634
4644 void Script::UpdateChunks(progress_t* /*pProgress*/) {
4645 // recalculate CRC32 check sum
4646 __resetCRC(crc);
4647 __calculateCRC(&data[0], data.size(), crc);
4648 __finalizeCRC(crc);
4649 // make sure chunk exists and has the required size
4650 const file_offset_t chunkSize =
4651 (file_offset_t) 7*sizeof(int32_t) + Name.size() + 16 + data.size();
4652 if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4653 else pChunk->Resize(chunkSize);
4654 // fill the chunk data to be written to disk
4655 uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4656 int pos = 0;
4657 store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size() + 16)); // total header size
4658 pos += sizeof(int32_t);
4659 store32(&pData[pos], Compression);
4660 pos += sizeof(int32_t);
4661 store32(&pData[pos], Encoding);
4662 pos += sizeof(int32_t);
4663 store32(&pData[pos], Language);
4664 pos += sizeof(int32_t);
4665 store32(&pData[pos], Bypass ? 1 : 0);
4666 pos += sizeof(int32_t);
4667 store32(&pData[pos], crc);
4668 pos += sizeof(int32_t);
4669 store32(&pData[pos], (uint32_t) Name.size());
4670 pos += sizeof(int32_t);
4671 for (int i = 0; i < Name.size(); ++i, ++pos)
4672 pData[pos] = Name[i];
4673 for (int i = 0; i < 16; ++i, ++pos)
4674 pData[pos] = Uuid[i];
4675 for (int i = 0; i < data.size(); ++i, ++pos)
4676 pData[pos] = data[i];
4677 }
4678
4683 DLS::dlsid_t dlsid;
4685 Uuid[0] = dlsid.ulData1 & 0xff;
4686 Uuid[1] = dlsid.ulData1 >> 8 & 0xff;
4687 Uuid[2] = dlsid.ulData1 >> 16 & 0xff;
4688 Uuid[3] = dlsid.ulData1 >> 24 & 0xff;
4689 Uuid[4] = dlsid.usData2 & 0xff;
4690 Uuid[5] = dlsid.usData2 >> 8 & 0xff;
4691 Uuid[6] = dlsid.usData3 & 0xff;
4692 Uuid[7] = dlsid.usData3 >> 8 & 0xff;
4693 Uuid[8] = dlsid.abData[0];
4694 Uuid[9] = dlsid.abData[1];
4695 Uuid[10] = dlsid.abData[2];
4696 Uuid[11] = dlsid.abData[3];
4697 Uuid[12] = dlsid.abData[4];
4698 Uuid[13] = dlsid.abData[5];
4699 Uuid[14] = dlsid.abData[6];
4700 Uuid[15] = dlsid.abData[7];
4701 }
4702
4709 void Script::SetGroup(ScriptGroup* pGroup) {
4710 if (this->pGroup == pGroup) return;
4711 if (pChunk)
4712 pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4713 this->pGroup = pGroup;
4714 }
4715
4722 ScriptGroup* Script::GetGroup() const {
4723 return pGroup;
4724 }
4725
4733 void Script::CopyAssign(const Script* orig) {
4734 Name = orig->Name;
4735 Compression = orig->Compression;
4736 Encoding = orig->Encoding;
4737 Language = orig->Language;
4738 Bypass = orig->Bypass;
4739 data = orig->data;
4740 }
4741
4742 void Script::RemoveAllScriptReferences() {
4743 File* pFile = pGroup->pFile;
4744 for (int i = 0; pFile->GetInstrument(i); ++i) {
4745 Instrument* instr = pFile->GetInstrument(i);
4746 instr->RemoveScript(this);
4747 }
4748 }
4749
4750// *************** ScriptGroup ***************
4751// *
4752
4753 ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4754 pFile = file;
4755 pList = lstRTIS;
4756 pScripts = NULL;
4757 if (lstRTIS) {
4758 RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4759 ::LoadString(ckName, Name);
4760 } else {
4761 Name = "Default Group";
4762 }
4763 }
4764
4765 ScriptGroup::~ScriptGroup() {
4766 if (pScripts) {
4767 std::vector<Script*>::iterator iter = pScripts->begin();
4768 std::vector<Script*>::iterator end = pScripts->end();
4769 while (iter != end) {
4770 delete *iter;
4771 ++iter;
4772 }
4773 delete pScripts;
4774 }
4775 }
4776
4788
4798 void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4799 if (pScripts) {
4800 if (!pList)
4801 pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4802
4803 // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4804 ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4805
4806 for (std::vector<Script*>::iterator it = pScripts->begin();
4807 it != pScripts->end(); ++it)
4808 {
4809 (*it)->UpdateChunks(pProgress);
4810 }
4811 }
4812 }
4813
4821 Script* ScriptGroup::GetScript(size_t index) {
4822 if (!pScripts) LoadScripts();
4823 if (index >= pScripts->size()) return NULL;
4824 return (*pScripts)[index];
4825 }
4826
4839 if (!pScripts) LoadScripts();
4840 Script* pScript = new Script(this, NULL);
4841 pScripts->push_back(pScript);
4842 return pScript;
4843 }
4844
4855 void ScriptGroup::DeleteScript(Script* pScript) {
4856 if (!pScripts) LoadScripts();
4857 std::vector<Script*>::iterator iter =
4858 find(pScripts->begin(), pScripts->end(), pScript);
4859 if (iter == pScripts->end())
4860 throw gig::Exception("Could not delete script, could not find given script");
4861 pScripts->erase(iter);
4862 pScript->RemoveAllScriptReferences();
4863 if (pScript->pChunk)
4864 pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4865 delete pScript;
4866 }
4867
4868 void ScriptGroup::LoadScripts() {
4869 if (pScripts) return;
4870 pScripts = new std::vector<Script*>;
4871 if (!pList) return;
4872
4873 size_t i = 0;
4874 for (RIFF::Chunk* ck = pList->GetSubChunkAt(i); ck;
4875 ck = pList->GetSubChunkAt(++i))
4876 {
4877 if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4878 pScripts->push_back(new Script(this, ck));
4879 }
4880 }
4881 }
4882
4883// *************** Instrument ***************
4884// *
4885
4886 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4887 static const DLS::Info::string_length_t fixedStringLengths[] = {
4888 { CHUNK_ID_INAM, 64 },
4889 { CHUNK_ID_ISFT, 12 },
4890 { 0, 0 }
4891 };
4892 pInfo->SetFixedStringLengths(fixedStringLengths);
4893
4894 // Initialization
4895 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4896 EffectSend = 0;
4897 Attenuation = 0;
4898 FineTune = 0;
4899 PitchbendRange = 2;
4900 PianoReleaseMode = false;
4901 DimensionKeyRange.low = 0;
4902 DimensionKeyRange.high = 0;
4903 pMidiRules = new MidiRule*[3];
4904 pMidiRules[0] = NULL;
4905 pScriptRefs = NULL;
4906
4907 // Loading
4908 RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
4909 if (lart) {
4910 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4911 if (_3ewg) {
4912 _3ewg->SetPos(0);
4913
4914 EffectSend = _3ewg->ReadUint16();
4915 Attenuation = _3ewg->ReadInt32();
4916 FineTune = _3ewg->ReadInt16();
4917 PitchbendRange = _3ewg->ReadInt16();
4918 uint8_t dimkeystart = _3ewg->ReadUint8();
4919 PianoReleaseMode = dimkeystart & 0x01;
4920 DimensionKeyRange.low = dimkeystart >> 1;
4921 DimensionKeyRange.high = _3ewg->ReadUint8();
4922
4923 if (_3ewg->GetSize() > 32) {
4924 // read MIDI rules
4925 int i = 0;
4926 _3ewg->SetPos(32);
4927 uint8_t id1 = _3ewg->ReadUint8();
4928 uint8_t id2 = _3ewg->ReadUint8();
4929
4930 if (id2 == 16) {
4931 if (id1 == 4) {
4932 pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4933 } else if (id1 == 0) {
4934 pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4935 } else if (id1 == 3) {
4936 pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4937 } else {
4938 pMidiRules[i++] = new MidiRuleUnknown;
4939 }
4940 }
4941 else if (id1 != 0 || id2 != 0) {
4942 pMidiRules[i++] = new MidiRuleUnknown;
4943 }
4944 //TODO: all the other types of rules
4945
4946 pMidiRules[i] = NULL;
4947 }
4948 }
4949 }
4950
4951 if (pFile->GetAutoLoad()) {
4952 if (!pRegions) pRegions = new RegionList;
4953 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4954 if (lrgn) {
4955 size_t i = 0;
4956 for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn;
4957 rgn = lrgn->GetSubListAt(++i))
4958 {
4959 if (rgn->GetListType() == LIST_TYPE_RGN) {
4960 if (pProgress)
4961 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4962 pRegions->push_back(new Region(this, rgn));
4963 }
4964 }
4965 // Creating Region Key Table for fast lookup
4966 UpdateRegionKeyTable();
4967 }
4968 }
4969
4970 // own gig format extensions
4971 RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4972 if (lst3LS) {
4973 // script slots (that is references to instrument scripts)
4974 RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4975 if (ckSCSL) {
4976 ckSCSL->SetPos(0);
4977
4978 int headerSize = ckSCSL->ReadUint32();
4979 int slotCount = ckSCSL->ReadUint32();
4980 if (slotCount) {
4981 int slotSize = ckSCSL->ReadUint32();
4982 ckSCSL->SetPos(headerSize); // in case of future header extensions
4983 int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4984 for (int i = 0; i < slotCount; ++i) {
4985 _ScriptPooolEntry e;
4986 e.fileOffset = ckSCSL->ReadUint32();
4987 e.bypass = ckSCSL->ReadUint32() & 1;
4988 if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4989 scriptPoolFileOffsets.push_back(e);
4990 }
4991 }
4992 }
4993
4994 // overridden script 'patch' variables
4995 RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
4996 if (ckSCPV) {
4997 ckSCPV->SetPos(0);
4998
4999 int nScripts = ckSCPV->ReadUint32();
5000 for (int iScript = 0; iScript < nScripts; ++iScript) {
5001 _UUID uuid;
5002 for (int i = 0; i < 16; ++i)
5003 uuid[i] = ckSCPV->ReadUint8();
5004 uint slot = ckSCPV->ReadUint32();
5005 ckSCPV->ReadUint32(); // unused, reserved 32 bit
5006 int nVars = ckSCPV->ReadUint32();
5007 for (int iVar = 0; iVar < nVars; ++iVar) {
5008 uint8_t type = ckSCPV->ReadUint8();
5009 ckSCPV->ReadUint8(); // unused, reserved byte
5010 int blobSize = ckSCPV->ReadUint16();
5011 RIFF::file_offset_t pos = ckSCPV->GetPos();
5012 // assuming 1st bit is set in 'type', otherwise blob not
5013 // supported for decoding
5014 if (type & 1) {
5015 String name, value;
5016 int len = ckSCPV->ReadUint16();
5017 for (int i = 0; i < len; ++i)
5018 name += (char) ckSCPV->ReadUint8();
5019 len = ckSCPV->ReadUint16();
5020 for (int i = 0; i < len; ++i)
5021 value += (char) ckSCPV->ReadUint8();
5022 if (!name.empty()) // 'name' should never be empty, but just to be sure
5023 scriptVars[uuid][slot][name] = value;
5024 }
5025 // also for potential future extensions: seek forward
5026 // according to blob size
5027 ckSCPV->SetPos(pos + blobSize);
5028 }
5029 }
5030 }
5031 }
5032
5033 if (pProgress)
5034 __notify_progress(pProgress, 1.0f); // notify done
5035 }
5036
5037 void Instrument::UpdateRegionKeyTable() {
5038 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
5039 RegionList::iterator iter = pRegions->begin();
5040 RegionList::iterator end = pRegions->end();
5041 for (; iter != end; ++iter) {
5042 gig::Region* pRegion = static_cast<gig::Region*>(*iter);
5043 const int low = std::max(int(pRegion->KeyRange.low), 0);
5044 const int high = std::min(int(pRegion->KeyRange.high), 127);
5045 for (int iKey = low; iKey <= high; iKey++) {
5046 RegionKeyTable[iKey] = pRegion;
5047 }
5048 }
5049 }
5050
5052 for (int i = 0 ; pMidiRules[i] ; i++) {
5053 delete pMidiRules[i];
5054 }
5055 delete[] pMidiRules;
5056 if (pScriptRefs) delete pScriptRefs;
5057 }
5058
5069 void Instrument::UpdateChunks(progress_t* pProgress) {
5070 // first update base classes' chunks
5072
5073 // update Regions' chunks
5074 {
5075 RegionList::iterator iter = pRegions->begin();
5076 RegionList::iterator end = pRegions->end();
5077 for (; iter != end; ++iter)
5078 (*iter)->UpdateChunks(pProgress);
5079 }
5080
5081 // make sure 'lart' RIFF list chunk exists
5082 RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
5083 if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
5084 // make sure '3ewg' RIFF chunk exists
5085 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
5086 if (!_3ewg) {
5087 File* pFile = (File*) GetParent();
5088
5089 // 3ewg is bigger in gig3, as it includes the iMIDI rules
5090 int size = (pFile->pVersion && pFile->pVersion->major > 2) ? 16416 : 12;
5091 _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
5092 memset(_3ewg->LoadChunkData(), 0, size);
5093 }
5094 // update '3ewg' RIFF chunk
5095 uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
5096 store16(&pData[0], EffectSend);
5097 store32(&pData[2], Attenuation);
5098 store16(&pData[6], FineTune);
5099 store16(&pData[8], PitchbendRange);
5100 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
5101 DimensionKeyRange.low << 1;
5102 pData[10] = dimkeystart;
5103 pData[11] = DimensionKeyRange.high;
5104
5105 if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
5106 pData[32] = 0;
5107 pData[33] = 0;
5108 } else {
5109 for (int i = 0 ; pMidiRules[i] ; i++) {
5110 pMidiRules[i]->UpdateChunks(pData);
5111 }
5112 }
5113
5114 // own gig format extensions
5115 if (ScriptSlotCount()) {
5116 // make sure we have converted the original loaded script file
5117 // offsets into valid Script object pointers
5118 LoadScripts();
5119
5120 RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
5121 if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
5122
5123 // save script slots (that is references to instrument scripts)
5124 const int slotCount = (int) pScriptRefs->size();
5125 const int headerSize = 3 * sizeof(uint32_t);
5126 const int slotSize = 2 * sizeof(uint32_t);
5127 const int totalChunkSize = headerSize + slotCount * slotSize;
5128 RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
5129 if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
5130 else ckSCSL->Resize(totalChunkSize);
5131 uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
5132 int pos = 0;
5133 store32(&pData[pos], headerSize);
5134 pos += sizeof(uint32_t);
5135 store32(&pData[pos], slotCount);
5136 pos += sizeof(uint32_t);
5137 store32(&pData[pos], slotSize);
5138 pos += sizeof(uint32_t);
5139 for (int i = 0; i < slotCount; ++i) {
5140 // arbitrary value, the actual file offset will be updated in
5141 // UpdateScriptFileOffsets() after the file has been resized
5142 int bogusFileOffset = 0;
5143 store32(&pData[pos], bogusFileOffset);
5144 pos += sizeof(uint32_t);
5145 store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
5146 pos += sizeof(uint32_t);
5147 }
5148
5149 // save overridden script 'patch' variables ...
5150
5151 // the actual 'scriptVars' member variable might contain variables of
5152 // scripts which are currently no longer assigned to any script slot
5153 // of this instrument, we need to get rid of these variables here to
5154 // prevent saving those persistently, however instead of touching the
5155 // member variable 'scriptVars' directly, rather strip a separate
5156 // copy such that the overridden values are not lost during an
5157 // instrument editor session (i.e. if script might be re-assigned)
5158 _VarsByScript vars = stripScriptVars();
5159 if (!vars.empty()) {
5160 // determine total size required for 'SCPV' RIFF chunk, and the
5161 // total amount of scripts being overridden (the latter is
5162 // required because a script might be used on several script
5163 // slots, hence vars.size() could then not be used here instead)
5164 size_t totalChunkSize = 4;
5165 size_t totalScriptsOverridden = 0;
5166 for (const auto& script : vars) {
5167 for (const auto& slot : script.second) {
5168 totalScriptsOverridden++;
5169 totalChunkSize += 16 + 4 + 4 + 4;
5170 for (const auto& var : slot.second) {
5171 totalChunkSize += 4 + 2 + var.first.length() +
5172 2 + var.second.length();
5173 }
5174 }
5175 }
5176
5177 // ensure 'SCPV' RIFF chunk exists (with required size)
5178 RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
5179 if (!ckSCPV) ckSCPV = lst3LS->AddSubChunk(CHUNK_ID_SCPV, totalChunkSize);
5180 else ckSCPV->Resize(totalChunkSize);
5181
5182 // store the actual data to 'SCPV' RIFF chunk
5183 uint8_t* pData = (uint8_t*) ckSCPV->LoadChunkData();
5184 int pos = 0;
5185 store32(&pData[pos], (uint32_t) totalScriptsOverridden); // scripts count
5186 pos += 4;
5187 for (const auto& script : vars) {
5188 for (const auto& slot : script.second) {
5189 for (int i = 0; i < 16; ++i)
5190 pData[pos+i] = script.first[i]; // uuid
5191 pos += 16;
5192 store32(&pData[pos], (uint32_t) slot.first); // slot index
5193 pos += 4;
5194 store32(&pData[pos], (uint32_t) 0); // unused, reserved 32 bit
5195 pos += 4;
5196 store32(&pData[pos], (uint32_t) slot.second.size()); // variables count
5197 pos += 4;
5198 for (const auto& var : slot.second) {
5199 pData[pos++] = 1; // type
5200 pData[pos++] = 0; // reserved byte
5201 store16(&pData[pos], 2 + var.first.size() + 2 + var.second.size()); // blob size
5202 pos += 2;
5203 store16(&pData[pos], var.first.size()); // variable name length
5204 pos += 2;
5205 for (int i = 0; i < var.first.size(); ++i)
5206 pData[pos++] = var.first[i];
5207 store16(&pData[pos], var.second.size()); // variable value length
5208 pos += 2;
5209 for (int i = 0; i < var.second.size(); ++i)
5210 pData[pos++] = var.second[i];
5211 }
5212 }
5213 }
5214 } else {
5215 // no script variable overridden by this instrument, so get rid
5216 // of 'SCPV' RIFF chunk (if any)
5217 RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
5218 if (ckSCPV) lst3LS->DeleteSubChunk(ckSCPV);
5219 }
5220 } else {
5221 // no script slots, so get rid of any LS custom RIFF chunks (if any)
5222 RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
5223 if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
5224 }
5225 }
5226
5227 void Instrument::UpdateScriptFileOffsets() {
5228 // own gig format extensions
5229 if (pScriptRefs && pScriptRefs->size() > 0) {
5230 RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
5231 RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
5232 const int slotCount = (int) pScriptRefs->size();
5233 const int headerSize = 3 * sizeof(uint32_t);
5234 ckSCSL->SetPos(headerSize);
5235 for (int i = 0; i < slotCount; ++i) {
5236 uint32_t fileOffset = uint32_t(
5237 (*pScriptRefs)[i].script->pChunk->GetFilePos() -
5238 (*pScriptRefs)[i].script->pChunk->GetPos() -
5239 CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
5240 );
5241 ckSCSL->WriteUint32(&fileOffset);
5242 // jump over flags entry (containing the bypass flag)
5243 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
5244 }
5245 }
5246 }
5247
5255 Region* Instrument::GetRegion(unsigned int Key) {
5256 if (!pRegions || pRegions->empty() || Key > 127) return NULL;
5257 return RegionKeyTable[Key];
5258
5259 /*for (int i = 0; i < Regions; i++) {
5260 if (Key <= pRegions[i]->KeyRange.high &&
5261 Key >= pRegions[i]->KeyRange.low) return pRegions[i];
5262 }
5263 return NULL;*/
5264 }
5265
5276 Region* Instrument::GetRegionAt(size_t pos) {
5277 if (!pRegions) return NULL;
5278 if (pos >= pRegions->size()) return NULL;
5279 return static_cast<gig::Region*>( (*pRegions)[pos] );
5280 }
5281
5292 if (!pRegions) return NULL;
5293 RegionsIterator = pRegions->begin();
5294 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
5295 }
5296
5308 if (!pRegions) return NULL;
5309 RegionsIterator++;
5310 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
5311 }
5312
5313 Region* Instrument::AddRegion() {
5314 // create new Region object (and its RIFF chunks)
5315 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
5316 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
5317 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
5318 Region* pNewRegion = new Region(this, rgn);
5319 const size_t idxIt = RegionsIterator - pRegions->begin();
5320 pRegions->push_back(pNewRegion);
5321 RegionsIterator = pRegions->begin() + std::min(idxIt, pRegions->size()); // avoid iterator invalidation
5322 Regions = (uint32_t) pRegions->size();
5323 // update Region key table for fast lookup
5324 UpdateRegionKeyTable();
5325 // done
5326 return pNewRegion;
5327 }
5328
5329 void Instrument::DeleteRegion(Region* pRegion) {
5330 if (!pRegions) return;
5331 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
5332 // update Region key table for fast lookup
5333 UpdateRegionKeyTable();
5334 }
5335
5364 void Instrument::MoveTo(Instrument* dst) {
5365 if (dst && GetParent() != dst->GetParent())
5366 throw Exception(
5367 "gig::Instrument::MoveTo() can only be used for moving within "
5368 "the same gig file."
5369 );
5370
5371 File* pFile = (File*) GetParent();
5372
5373 // move this instrument within the instrument list
5374 {
5375 File::InstrumentList& list = *pFile->pInstruments;
5376
5377 File::InstrumentList::iterator itFrom =
5378 std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
5379 if (itFrom == list.end())
5380 throw Exception(
5381 "gig::Instrument::MoveTo(): unexpected missing membership "
5382 "of this instrument."
5383 );
5384 list.erase(itFrom);
5385
5386 File::InstrumentList::iterator itTo =
5387 std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
5388
5389 list.insert(itTo, this);
5390 }
5391
5392 // move the instrument's actual list RIFF chunk appropriately
5393 RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
5394 lstCkInstruments->MoveSubChunk(
5395 this->pCkInstrument,
5396 (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
5397 );
5398 }
5399
5411 return pMidiRules[i];
5412 }
5413
5420 delete pMidiRules[0];
5422 pMidiRules[0] = r;
5423 pMidiRules[1] = 0;
5424 return r;
5425 }
5426
5433 delete pMidiRules[0];
5435 pMidiRules[0] = r;
5436 pMidiRules[1] = 0;
5437 return r;
5438 }
5439
5446 delete pMidiRules[0];
5448 pMidiRules[0] = r;
5449 pMidiRules[1] = 0;
5450 return r;
5451 }
5452
5459 delete pMidiRules[i];
5460 pMidiRules[i] = 0;
5461 }
5462
5463 void Instrument::LoadScripts() {
5464 if (pScriptRefs) return;
5465 pScriptRefs = new std::vector<_ScriptPooolRef>;
5466 if (scriptPoolFileOffsets.empty()) return;
5467 File* pFile = (File*) GetParent();
5468 for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
5469 uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
5470 for (size_t i = 0; pFile->GetScriptGroup(i); ++i) {
5471 ScriptGroup* group = pFile->GetScriptGroup(i);
5472 for (uint s = 0; group->GetScript(s); ++s) {
5473 Script* script = group->GetScript(s);
5474 if (script->pChunk) {
5475 uint32_t offset = uint32_t(
5476 script->pChunk->GetFilePos() -
5477 script->pChunk->GetPos() -
5478 CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5479 );
5480 if (offset == soughtOffset)
5481 {
5482 _ScriptPooolRef ref;
5483 ref.script = script;
5484 ref.bypass = scriptPoolFileOffsets[k].bypass;
5485 pScriptRefs->push_back(ref);
5486 break;
5487 }
5488 }
5489 }
5490 }
5491 }
5492 // we don't need that anymore
5493 scriptPoolFileOffsets.clear();
5494 }
5495
5509 LoadScripts();
5510 if (index >= pScriptRefs->size()) return NULL;
5511 return pScriptRefs->at(index).script;
5512 }
5513
5549 void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5550 LoadScripts();
5551 _ScriptPooolRef ref = { pScript, bypass };
5552 pScriptRefs->push_back(ref);
5553 }
5554
5569 void Instrument::SwapScriptSlots(size_t index1, size_t index2) {
5570 LoadScripts();
5571 if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5572 return;
5573 _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5574 (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5575 (*pScriptRefs)[index2] = tmp;
5576 }
5577
5584 void Instrument::RemoveScriptSlot(size_t index) {
5585 LoadScripts();
5586 if (index >= pScriptRefs->size()) return;
5587 pScriptRefs->erase( pScriptRefs->begin() + index );
5588 }
5589
5603 LoadScripts();
5604 for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5605 if ((*pScriptRefs)[i].script == pScript) {
5606 pScriptRefs->erase( pScriptRefs->begin() + i );
5607 }
5608 }
5609 }
5610
5626 return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
5627 }
5628
5646 if (index >= ScriptSlotCount()) return false;
5647 return pScriptRefs ? pScriptRefs->at(index).bypass
5648 : scriptPoolFileOffsets.at(index).bypass;
5649
5650 }
5651
5665 void Instrument::SetScriptSlotBypassed(size_t index, bool bBypass) {
5666 if (index >= ScriptSlotCount()) return;
5667 if (pScriptRefs)
5668 pScriptRefs->at(index).bypass = bBypass;
5669 else
5670 scriptPoolFileOffsets.at(index).bypass = bBypass;
5671 }
5672
5674 inline std::array<uint8_t,16> _UUIDFromCArray(const uint8_t* pData) {
5675 std::array<uint8_t,16> uuid;
5676 memcpy(&uuid[0], pData, 16);
5677 return uuid;
5678 }
5679
5684 bool Instrument::ReferencesScriptWithUuid(const _UUID& uuid) {
5685 const size_t nSlots = ScriptSlotCount();
5686 for (size_t iSlot = 0; iSlot < nSlots; ++iSlot)
5687 if (_UUIDFromCArray(&GetScriptOfSlot(iSlot)->Uuid[0]) == uuid)
5688 return true;
5689 return false;
5690 }
5691
5711 bool Instrument::IsScriptPatchVariableSet(size_t slot, String variable) {
5712 if (variable.empty()) return false;
5713 Script* script = GetScriptOfSlot(slot);
5714 if (!script) return false;
5715 const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5716 if (!scriptVars.count(uuid)) return false;
5717 const _VarsBySlot& slots = scriptVars.find(uuid)->second;
5718 if (slots.empty()) return false;
5719 if (slots.count(slot))
5720 return slots.find(slot)->second.count(variable);
5721 else
5722 return slots.begin()->second.count(variable);
5723 }
5724
5745 std::map<String,String> Instrument::GetScriptPatchVariables(size_t slot) {
5746 Script* script = GetScriptOfSlot(slot);
5747 if (!script) return std::map<String,String>();
5748 const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5749 if (!scriptVars.count(uuid)) return std::map<String,String>();
5750 const _VarsBySlot& slots = scriptVars.find(uuid)->second;
5751 if (slots.empty()) return std::map<String,String>();
5752 const _PatchVars& vars =
5753 (slots.count(slot)) ?
5754 slots.find(slot)->second : slots.begin()->second;
5755 return vars;
5756 }
5757
5777 String Instrument::GetScriptPatchVariable(size_t slot, String variable) {
5778 std::map<String,String> vars = GetScriptPatchVariables(slot);
5779 return (vars.count(variable)) ? vars.find(variable)->second : "";
5780 }
5781
5804 void Instrument::SetScriptPatchVariable(size_t slot, String variable, String value) {
5805 if (variable.empty())
5806 throw Exception("Variable name must not be empty");
5807 Script* script = GetScriptOfSlot(slot);
5808 if (!script)
5809 throw Exception("No script slot with index " + ToString(slot));
5810 const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5811 scriptVars[uuid][slot][variable] = value;
5812 }
5813
5845 void Instrument::UnsetScriptPatchVariable(ssize_t slot, String variable) {
5846 Script* script = GetScriptOfSlot(slot);
5847
5848 // option 1: unset a particular variable of one particular script slot
5849 if (slot != -1 && !variable.empty()) {
5850 if (!script) return;
5851 const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5852 if (!scriptVars.count(uuid)) return;
5853 if (!scriptVars[uuid].count(slot)) return;
5854 if (scriptVars[uuid][slot].count(variable))
5855 scriptVars[uuid][slot].erase(
5856 scriptVars[uuid][slot].find(variable)
5857 );
5858 if (scriptVars[uuid][slot].empty())
5859 scriptVars[uuid].erase( scriptVars[uuid].find(slot) );
5860 if (scriptVars[uuid].empty())
5861 scriptVars.erase( scriptVars.find(uuid) );
5862 return;
5863 }
5864
5865 // option 2: unset all variables of all script slots
5866 if (slot == -1 && variable.empty()) {
5867 scriptVars.clear();
5868 return;
5869 }
5870
5871 // option 3: unset all variables of one particular script slot only
5872 if (slot != -1) {
5873 if (!script) return;
5874 const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5875 if (scriptVars.count(uuid))
5876 scriptVars.erase( scriptVars.find(uuid) );
5877 return;
5878 }
5879
5880 // option 4: unset a particular variable of all script slots
5881 _VarsByScript::iterator itScript = scriptVars.begin();
5882 _VarsByScript::iterator endScript = scriptVars.end();
5883 while (itScript != endScript) {
5884 _VarsBySlot& slots = itScript->second;
5885 _VarsBySlot::iterator itSlot = slots.begin();
5886 _VarsBySlot::iterator endSlot = slots.end();
5887 while (itSlot != endSlot) {
5888 _PatchVars& vars = itSlot->second;
5889 if (vars.count(variable))
5890 vars.erase( vars.find(variable) );
5891 if (vars.empty())
5892 slots.erase(itSlot++); // postfix increment to avoid iterator invalidation
5893 else
5894 ++itSlot;
5895 }
5896 if (slots.empty())
5897 scriptVars.erase(itScript++); // postfix increment to avoid iterator invalidation
5898 else
5899 ++itScript;
5900 }
5901 }
5902
5910 Instrument::_VarsByScript Instrument::stripScriptVars() {
5911 _VarsByScript vars;
5912 _VarsByScript::const_iterator itScript = scriptVars.begin();
5913 _VarsByScript::const_iterator endScript = scriptVars.end();
5914 for (; itScript != endScript; ++itScript) {
5915 const _UUID& uuid = itScript->first;
5916 if (!ReferencesScriptWithUuid(uuid))
5917 continue;
5918 const _VarsBySlot& slots = itScript->second;
5919 _VarsBySlot::const_iterator itSlot = slots.begin();
5920 _VarsBySlot::const_iterator endSlot = slots.end();
5921 for (; itSlot != endSlot; ++itSlot) {
5922 Script* script = GetScriptOfSlot(itSlot->first);
5923 if (!script) continue;
5924 if (_UUIDFromCArray(&script->Uuid[0]) != uuid) continue;
5925 if (itSlot->second.empty()) continue;
5926 vars[uuid][itSlot->first] = itSlot->second;
5927 }
5928 }
5929 return vars;
5930 }
5931
5941 void Instrument::CopyAssign(const Instrument* orig) {
5942 CopyAssign(orig, NULL);
5943 }
5944
5953 void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5954 // handle base class
5955 // (without copying DLS region stuff)
5956 DLS::Instrument::CopyAssignCore(orig);
5957
5958 // handle own member variables
5959 Attenuation = orig->Attenuation;
5960 EffectSend = orig->EffectSend;
5961 FineTune = orig->FineTune;
5963 PianoReleaseMode = orig->PianoReleaseMode;
5965 scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5966 // deep copy of pScriptRefs required (to avoid undefined behaviour)
5967 if (pScriptRefs) delete pScriptRefs;
5968 pScriptRefs = new std::vector<_ScriptPooolRef>;
5969 if (orig->pScriptRefs)
5970 *pScriptRefs = *orig->pScriptRefs;
5971 scriptVars = orig->scriptVars;
5972
5973 // free old midi rules
5974 for (int i = 0 ; pMidiRules[i] ; i++) {
5975 delete pMidiRules[i];
5976 }
5977 //TODO: MIDI rule copying
5978 pMidiRules[0] = NULL;
5979
5980 // delete all old regions
5981 while (Regions) DeleteRegion(GetRegionAt(0));
5982 // create new regions and copy them from original
5983 {
5984 RegionList::const_iterator it = orig->pRegions->begin();
5985 for (int i = 0; i < orig->Regions; ++i, ++it) {
5986 Region* dstRgn = AddRegion();
5987 //NOTE: Region does semi-deep copy !
5988 dstRgn->CopyAssign(
5989 static_cast<gig::Region*>(*it),
5990 mSamples
5991 );
5992 }
5993 }
5994
5995 UpdateRegionKeyTable();
5996 }
5997
6011 bool Instrument::UsesAnyGigFormatExtension() const {
6012 if (!pRegions) return false;
6013 if (!scriptVars.empty()) return true;
6014 RegionList::const_iterator iter = pRegions->begin();
6015 RegionList::const_iterator end = pRegions->end();
6016 for (; iter != end; ++iter) {
6017 gig::Region* rgn = static_cast<gig::Region*>(*iter);
6018 if (rgn->UsesAnyGigFormatExtension())
6019 return true;
6020 }
6021 return false;
6022 }
6023
6024
6025// *************** Group ***************
6026// *
6027
6034 Group::Group(File* file, RIFF::Chunk* ck3gnm) {
6035 pFile = file;
6036 pNameChunk = ck3gnm;
6037 SamplesIterator = 0;
6038 ::LoadString(pNameChunk, Name);
6039 }
6040
6046 }
6047
6053 // handle own RIFF chunks
6054 if (pNameChunk) {
6055 pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
6056 pNameChunk = NULL;
6057 }
6058 }
6059
6070 void Group::UpdateChunks(progress_t* /*pProgress*/) {
6071 // make sure <3gri> and <3gnl> list chunks exist
6072 RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
6073 if (!_3gri) {
6074 _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
6075 pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6076 }
6077 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6078 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6079
6080 if (!pNameChunk && pFile->pVersion && pFile->pVersion->major > 2) {
6081 // v3 has a fixed list of 128 strings, find a free one
6082 size_t i = 0;
6083 for (RIFF::Chunk* ck = _3gnl->GetSubChunkAt(i); ck; ck = _3gnl->GetSubChunkAt(++i)) {
6084 if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
6085 pNameChunk = ck;
6086 break;
6087 }
6088 }
6089 }
6090
6091 // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
6092 ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
6093 }
6094
6102 Sample* Group::GetSample(size_t index) {
6103 if (pFile->pSamples && index >= pFile->pSamples->size()) return NULL;
6104 size_t indexInFile = 0;
6105 size_t indexInGroup = 0;
6106 for (Sample* pSample = pFile->GetSample(indexInFile); pSample;
6107 pSample = pFile->GetSample(++indexInFile))
6108 {
6109 if (pSample->GetGroup() != this) continue;
6110 if (indexInGroup++ == index) return pSample;
6111 }
6112 return NULL;
6113 }
6114
6129 size_t& i = this->SamplesIterator;
6130 i = 0;
6131 for (Sample* pSample = pFile->GetSample(i); pSample;
6132 pSample = pFile->GetSample(++i))
6133 {
6134 if (pSample->GetGroup() == this)
6135 return pSample;
6136 }
6137 return NULL;
6138 }
6139
6153 size_t& i = this->SamplesIterator;
6154 for (Sample* pSample = pFile->GetSample(++i); pSample;
6155 pSample = pFile->GetSample(++i))
6156 {
6157 if (pSample->GetGroup() == this)
6158 return pSample;
6159 }
6160 return NULL;
6161 }
6162
6166 void Group::AddSample(Sample* pSample) {
6167 pSample->pGroup = this;
6168 }
6169
6177 // get "that" other group first
6178 size_t i = 0;
6179 Group* pOtherGroup = NULL;
6180 for (pOtherGroup = pFile->GetGroup(i); pOtherGroup;
6181 pOtherGroup = pFile->GetGroup(++i))
6182 {
6183 if (pOtherGroup != this) break;
6184 }
6185 if (!pOtherGroup) throw Exception(
6186 "Could not move samples to another group, since there is no "
6187 "other Group. This is a bug, report it!"
6188 );
6189 // now move all samples of this group to the other group
6190 Sample* pSample;
6191 while ((pSample = GetSample(0))) {
6192 pOtherGroup->AddSample(pSample);
6193 }
6194 }
6195
6196
6197
6198// *************** File ***************
6199// *
6200
6203 0, 2, 19980628 & 0xffff, 19980628 >> 16
6204 };
6205
6207 const DLS::version_t File::VERSION_3 = {
6208 0, 3, 20030331 & 0xffff, 20030331 >> 16
6209 };
6210
6212 const DLS::version_t File::VERSION_4 = {
6213 0, 4, 20071012 & 0xffff, 20071012 >> 16
6214 };
6215
6216 static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
6217 { CHUNK_ID_IARL, 256 },
6218 { CHUNK_ID_IART, 128 },
6219 { CHUNK_ID_ICMS, 128 },
6220 { CHUNK_ID_ICMT, 1024 },
6221 { CHUNK_ID_ICOP, 128 },
6222 { CHUNK_ID_ICRD, 128 },
6223 { CHUNK_ID_IENG, 128 },
6224 { CHUNK_ID_IGNR, 128 },
6225 { CHUNK_ID_IKEY, 128 },
6226 { CHUNK_ID_IMED, 128 },
6227 { CHUNK_ID_INAM, 128 },
6228 { CHUNK_ID_IPRD, 128 },
6229 { CHUNK_ID_ISBJ, 128 },
6230 { CHUNK_ID_ISFT, 128 },
6231 { CHUNK_ID_ISRC, 128 },
6232 { CHUNK_ID_ISRF, 128 },
6233 { CHUNK_ID_ITCH, 128 },
6234 { 0, 0 }
6235 };
6236
6237 File::File() : DLS::File() {
6238 bAutoLoad = true;
6239 *pVersion = VERSION_3;
6240 pGroups = NULL;
6241 pScriptGroups = NULL;
6242 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
6243 pInfo->ArchivalLocation = String(256, ' ');
6244
6245 // add some mandatory chunks to get the file chunks in right
6246 // order (INFO chunk will be moved to first position later)
6247 pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
6248 pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
6249 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
6250
6251 GenerateDLSID();
6252 }
6253
6254 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
6255 bAutoLoad = true;
6256 pGroups = NULL;
6257 pScriptGroups = NULL;
6258 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
6259 }
6260
6261 File::~File() {
6262 if (pGroups) {
6263 std::vector<Group*>::iterator iter = pGroups->begin();
6264 std::vector<Group*>::iterator end = pGroups->end();
6265 while (iter != end) {
6266 delete *iter;
6267 ++iter;
6268 }
6269 delete pGroups;
6270 }
6271 if (pScriptGroups) {
6272 std::vector<ScriptGroup*>::iterator iter = pScriptGroups->begin();
6273 std::vector<ScriptGroup*>::iterator end = pScriptGroups->end();
6274 while (iter != end) {
6275 delete *iter;
6276 ++iter;
6277 }
6278 delete pScriptGroups;
6279 }
6280 }
6281
6290 Sample* File::GetFirstSample(progress_t* pProgress) {
6291 if (!pSamples) LoadSamples(pProgress);
6292 if (!pSamples) return NULL;
6293 SamplesIterator = pSamples->begin();
6294 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
6295 }
6296
6305 if (!pSamples) return NULL;
6306 SamplesIterator++;
6307 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
6308 }
6309
6317 Sample* File::GetSample(size_t index, progress_t* pProgress) {
6318 if (!pSamples) LoadSamples(pProgress);
6319 if (!pSamples) return NULL;
6320 if (index >= pSamples->size()) return NULL;
6321 return static_cast<gig::Sample*>( (*pSamples)[index] );
6322 }
6323
6333 if (!pSamples) LoadSamples();
6334 if (!pSamples) return 0;
6335 return pSamples->size();
6336 }
6337
6346 if (!pSamples) LoadSamples();
6348 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
6349 // create new Sample object and its respective 'wave' list chunk
6350 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
6351 Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
6352
6353 // add mandatory chunks to get the chunks in right order
6354 wave->AddSubChunk(CHUNK_ID_FMT, 16);
6355 wave->AddSubList(LIST_TYPE_INFO);
6356
6357 const size_t idxIt = SamplesIterator - pSamples->begin();
6358 pSamples->push_back(pSample);
6359 SamplesIterator = pSamples->begin() + std::min(idxIt, pSamples->size()); // avoid iterator invalidation
6360 return pSample;
6361 }
6362
6372 void File::DeleteSample(Sample* pSample) {
6373 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
6374 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
6375 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
6376 const size_t idxIt = SamplesIterator - pSamples->begin();
6377 pSamples->erase(iter);
6378 SamplesIterator = pSamples->begin() + std::min(idxIt, pSamples->size()); // avoid iterator invalidation
6379 pSample->DeleteChunks();
6380 delete pSample;
6381
6382 // remove all references to the sample
6383 size_t iIns = 0;
6384 for (Instrument* instrument = GetInstrument(iIns); instrument;
6385 instrument = GetInstrument(++iIns))
6386 {
6387 size_t iRgn = 0;
6388 for (Region* region = instrument->GetRegionAt(iRgn); region;
6389 region = instrument->GetRegionAt(++iRgn))
6390 {
6391 if (region->GetSample() == pSample) region->SetSample(NULL);
6392
6393 for (int i = 0 ; i < region->DimensionRegions ; i++) {
6394 gig::DimensionRegion *d = region->pDimensionRegions[i];
6395 if (d->pSample == pSample) d->pSample = NULL;
6396 }
6397 }
6398 }
6399 }
6400
6401 void File::LoadSamples() {
6402 LoadSamples(NULL);
6403 }
6404
6405 void File::LoadSamples(progress_t* pProgress) {
6406 // Groups must be loaded before samples, because samples will try
6407 // to resolve the group they belong to
6408 if (!pGroups) LoadGroups();
6409
6410 if (!pSamples) pSamples = new SampleList;
6411
6412 // just for progress calculation
6413 int iSampleIndex = 0;
6414 int iTotalSamples = WavePoolCount;
6415
6416 // just for assembling path of optional extension files to be read
6417 const std::string folder = parentPath(pRIFF->GetFileName());
6418 const std::string baseName = pathWithoutExtension(pRIFF->GetFileName());
6419
6420 // the main gig file and the extension files (.gx01, ... , .gx98) may
6421 // contain wave data (wave pool)
6422 std::vector<RIFF::File*> poolFiles;
6423 poolFiles.push_back(pRIFF);
6424
6425 // get info about all extension files
6426 RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
6427 if (ckXfil) { // there are extension files (.gx01, ... , .gx98) ...
6428 const uint32_t n = ckXfil->ReadInt32();
6429 for (int i = 0; i < n; i++) {
6430 // read the filename and load the extension file
6431 std::string name;
6432 ckXfil->ReadString(name, 128);
6433 std::string path = concatPath(folder, name);
6434 RIFF::File* pExtFile = new RIFF::File(path);
6435 // check that the dlsids match
6436 RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID);
6437 if (ckDLSID) {
6438 ::DLS::dlsid_t idExpected;
6439 idExpected.ulData1 = ckXfil->ReadInt32();
6440 idExpected.usData2 = ckXfil->ReadInt16();
6441 idExpected.usData3 = ckXfil->ReadInt16();
6442 ckXfil->Read(idExpected.abData, 8, 1);
6443 ::DLS::dlsid_t idFound;
6444 ckDLSID->Read(&idFound.ulData1, 1, 4);
6445 ckDLSID->Read(&idFound.usData2, 1, 2);
6446 ckDLSID->Read(&idFound.usData3, 1, 2);
6447 ckDLSID->Read(idFound.abData, 8, 1);
6448 if (memcmp(&idExpected, &idFound, 16) != 0)
6449 throw gig::Exception("dlsid mismatch for extension file: %s", path.c_str());
6450 }
6451 poolFiles.push_back(pExtFile);
6452 ExtensionFiles.push_back(pExtFile);
6453 }
6454 }
6455
6456 // check if a .gx99 (GigaPulse) file exists
6457 RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
6458 if (ckDoxf) { // there is a .gx99 (GigaPulse) file ...
6459 std::string path = baseName + ".gx99";
6460 RIFF::File* pExtFile = new RIFF::File(path);
6461
6462 // skip unused int and filename
6463 ckDoxf->SetPos(132, RIFF::stream_curpos);
6464
6465 // check that the dlsids match
6466 RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID);
6467 if (ckDLSID) {
6468 ::DLS::dlsid_t idExpected;
6469 idExpected.ulData1 = ckDoxf->ReadInt32();
6470 idExpected.usData2 = ckDoxf->ReadInt16();
6471 idExpected.usData3 = ckDoxf->ReadInt16();
6472 ckDoxf->Read(idExpected.abData, 8, 1);
6473 ::DLS::dlsid_t idFound;
6474 ckDLSID->Read(&idFound.ulData1, 1, 4);
6475 ckDLSID->Read(&idFound.usData2, 1, 2);
6476 ckDLSID->Read(&idFound.usData3, 1, 2);
6477 ckDLSID->Read(idFound.abData, 8, 1);
6478 if (memcmp(&idExpected, &idFound, 16) != 0)
6479 throw gig::Exception("dlsid mismatch for GigaPulse file: %s", path.c_str());
6480 }
6481 poolFiles.push_back(pExtFile);
6482 ExtensionFiles.push_back(pExtFile);
6483 }
6484
6485 // load all samples (both from this/main .gig file as well as from
6486 // extension files if required)
6487 for (int i = 0; i < poolFiles.size(); i++) {
6488 RIFF::File* file = poolFiles[i];
6489 RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
6490 if (wvpl) {
6491 file_offset_t wvplFileOffset = wvpl->GetFilePos() -
6492 wvpl->GetPos(); // should be zero, but just to be sure
6493 size_t iWaveCk = 0;
6494 for (RIFF::List* wave = wvpl->GetSubListAt(iWaveCk); wave;
6495 wave = wvpl->GetSubListAt(++iWaveCk))
6496 {
6497 if (wave->GetListType() == LIST_TYPE_WAVE) {
6498 // notify current progress
6499 if (pProgress) {
6500 const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
6501 __notify_progress(pProgress, subprogress);
6502 }
6503
6504 file_offset_t waveFileOffset = wave->GetFilePos();
6505 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex));
6506
6507 iSampleIndex++;
6508 }
6509 }
6510 }
6511 }
6512
6513 if (pProgress)
6514 __notify_progress(pProgress, 1.0); // notify done
6515 }
6516
6525 if (!pInstruments) LoadInstruments();
6526 if (!pInstruments) return NULL;
6527 InstrumentsIterator = pInstruments->begin();
6528 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
6529 }
6530
6539 if (!pInstruments) return NULL;
6540 InstrumentsIterator++;
6541 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
6542 }
6543
6553 if (!pInstruments) LoadInstruments();
6554 if (!pInstruments) return 0;
6555 return pInstruments->size();
6556 }
6557
6565 Instrument* File::GetInstrument(size_t index, progress_t* pProgress) {
6566 if (!pInstruments) {
6567 // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
6568
6569 if (pProgress) {
6570 // sample loading subtask
6571 progress_t subprogress;
6572 __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
6573 __notify_progress(&subprogress, 0.0f);
6574 if (GetAutoLoad())
6575 GetSample(0, &subprogress); // now force all samples to be loaded
6576 __notify_progress(&subprogress, 1.0f);
6577
6578 // instrument loading subtask
6579 if (pProgress->callback) {
6580 subprogress.__range_min = subprogress.__range_max;
6581 subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
6582 }
6583 __notify_progress(&subprogress, 0.0f);
6584 LoadInstruments(&subprogress);
6585 __notify_progress(&subprogress, 1.0f);
6586 } else {
6587 // sample loading subtask
6588 if (GetAutoLoad())
6589 GetSample(0); // now force all samples to be loaded
6590
6591 // instrument loading subtask
6592 LoadInstruments();
6593 }
6594 }
6595 if (!pInstruments) return NULL;
6596 if (index >= pInstruments->size()) return NULL;
6597 return static_cast<gig::Instrument*>( (*pInstruments)[index] );
6598 }
6599
6607 Instrument* File::AddInstrument() {
6608 if (!pInstruments) LoadInstruments();
6610 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
6611 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
6612
6613 // add mandatory chunks to get the chunks in right order
6614 lstInstr->AddSubList(LIST_TYPE_INFO);
6615 lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
6616
6617 Instrument* pInstrument = new Instrument(this, lstInstr);
6618 pInstrument->GenerateDLSID();
6619
6620 lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
6621
6622 // this string is needed for the gig to be loadable in GSt:
6623 pInstrument->pInfo->Software = "Endless Wave";
6624
6625 const size_t idxIt = InstrumentsIterator - pInstruments->begin();
6626 pInstruments->push_back(pInstrument);
6627 InstrumentsIterator = pInstruments->begin() + std::min(idxIt, pInstruments->size()); // avoid iterator invalidation
6628 return pInstrument;
6629 }
6630
6646 Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
6647 Instrument* instr = AddInstrument();
6648 instr->CopyAssign(orig);
6649 return instr;
6650 }
6651
6663 void File::AddContentOf(File* pFile) {
6664 static int iCallCount = -1;
6665 iCallCount++;
6666 std::map<Group*,Group*> mGroups;
6667 std::map<Sample*,Sample*> mSamples;
6668
6669 // clone sample groups
6670 for (int i = 0; pFile->GetGroup(i); ++i) {
6671 Group* g = AddGroup();
6672 g->Name =
6673 "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
6674 mGroups[pFile->GetGroup(i)] = g;
6675 }
6676
6677 // clone samples (not waveform data here yet)
6678 for (int i = 0; pFile->GetSample(i); ++i) {
6679 Sample* s = AddSample();
6680 s->CopyAssignMeta(pFile->GetSample(i));
6681 mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
6682 mSamples[pFile->GetSample(i)] = s;
6683 }
6684
6685 // clone script groups and their scripts
6686 for (size_t iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
6687 ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
6688 ScriptGroup* dg = AddScriptGroup();
6689 dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
6690 for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
6691 Script* ss = sg->GetScript(iScript);
6692 Script* ds = dg->AddScript();
6693 ds->CopyAssign(ss);
6694 }
6695 }
6696
6697 //BUG: For some reason this method only works with this additional
6698 // Save() call in between here.
6699 //
6700 // Important: The correct one of the 2 Save() methods has to be called
6701 // here, depending on whether the file is completely new or has been
6702 // saved to disk already, otherwise it will result in data corruption.
6703 if (pRIFF->IsNew())
6704 Save(GetFileName());
6705 else
6706 Save();
6707
6708 // clone instruments
6709 // (passing the crosslink table here for the cloned samples)
6710 for (int i = 0; pFile->GetInstrument(i); ++i) {
6711 Instrument* instr = AddInstrument();
6712 instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
6713 }
6714
6715 // Mandatory: file needs to be saved to disk at this point, so this
6716 // file has the correct size and data layout for writing the samples'
6717 // waveform data to disk.
6718 Save();
6719
6720 // clone samples' waveform data
6721 // (using direct read & write disk streaming)
6722 for (int i = 0; pFile->GetSample(i); ++i) {
6723 mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
6724 }
6725 }
6726
6735 void File::DeleteInstrument(Instrument* pInstrument) {
6736 if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
6737 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
6738 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
6739 const size_t idxIt = InstrumentsIterator - pInstruments->begin();
6740 pInstruments->erase(iter);
6741 InstrumentsIterator = pInstruments->begin() + std::min(idxIt, pInstruments->size()); // avoid iterator invalidation
6742 pInstrument->DeleteChunks();
6743 delete pInstrument;
6744 }
6745
6746 void File::LoadInstruments() {
6747 LoadInstruments(NULL);
6748 }
6749
6750 void File::LoadInstruments(progress_t* pProgress) {
6751 if (!pInstruments) pInstruments = new InstrumentList;
6752 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
6753 if (lstInstruments) {
6754 int iInstrumentIndex = 0;
6755 size_t i = 0;
6756 for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i);
6757 lstInstr; lstInstr = lstInstruments->GetSubListAt(++i))
6758 {
6759 if (lstInstr->GetListType() == LIST_TYPE_INS) {
6760 if (pProgress) {
6761 // notify current progress
6762 const float localProgress = (float) iInstrumentIndex / (float) Instruments;
6763 __notify_progress(pProgress, localProgress);
6764
6765 // divide local progress into subprogress for loading current Instrument
6766 progress_t subprogress;
6767 __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
6768
6769 pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
6770 } else {
6771 pInstruments->push_back(new Instrument(this, lstInstr));
6772 }
6773
6774 iInstrumentIndex++;
6775 }
6776 }
6777 if (pProgress)
6778 __notify_progress(pProgress, 1.0); // notify done
6779 }
6780 }
6781
6785 void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
6786 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6787 if (!_3crc) return;
6788
6789 // get the index of the sample
6790 int iWaveIndex = GetWaveTableIndexOf(pSample);
6791 if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
6792
6793 // write the CRC-32 checksum to disk
6794 _3crc->SetPos(iWaveIndex * 8);
6795 uint32_t one = 1;
6796 _3crc->WriteUint32(&one); // always 1
6797 _3crc->WriteUint32(&crc);
6798 }
6799
6800 uint32_t File::GetSampleChecksum(Sample* pSample) {
6801 // get the index of the sample
6802 int iWaveIndex = GetWaveTableIndexOf(pSample);
6803 if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
6804
6805 return GetSampleChecksumByIndex(iWaveIndex);
6806 }
6807
6808 uint32_t File::GetSampleChecksumByIndex(int index) {
6809 if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
6810
6811 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6812 if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
6813 uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
6814 if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
6815
6816 // read the CRC-32 checksum directly from disk
6817 size_t pos = index * 8;
6818 if (pos + 8 > _3crc->GetNewSize())
6819 throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
6820
6821 uint32_t one = load32(&pData[pos]); // always 1
6822 if (one != 1)
6823 throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
6824
6825 return load32(&pData[pos+4]);
6826 }
6827
6828 int File::GetWaveTableIndexOf(gig::Sample* pSample) {
6829 if (!pSamples) GetSample(0); // make sure sample chunks were scanned
6830 File::SampleList::iterator iter = pSamples->begin();
6831 File::SampleList::iterator end = pSamples->end();
6832 for (int index = 0; iter != end; ++iter, ++index)
6833 if (*iter == pSample)
6834 return index;
6835 return -1;
6836 }
6837
6845 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6846 if (!_3crc) return false;
6847 if (_3crc->GetNewSize() <= 0) return false;
6848 if (_3crc->GetNewSize() % 8) return false;
6849 if (!pSamples) GetSample(0); // make sure sample chunks were scanned
6850 if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
6851
6852 const file_offset_t n = _3crc->GetNewSize() / 8;
6853
6854 uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
6855 if (!pData) return false;
6856
6857 for (file_offset_t i = 0; i < n; ++i) {
6858 uint32_t one = load32(&pData[i*8]);
6859 if (one != 1) return false;
6860 }
6861
6862 return true;
6863 }
6864
6882 // make sure sample chunks were scanned
6883 if (!pSamples) GetSample(0);
6884
6885 bool bRequiresSave = false;
6886
6887 // make sure "3CRC" chunk exists with required size
6888 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6889 if (!_3crc) {
6890 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6891 // the order of einf and 3crc is not the same in v2 and v3
6892 RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6893 if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf);
6894 bRequiresSave = true;
6895 } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
6896 _3crc->Resize(pSamples->size() * 8);
6897 bRequiresSave = true;
6898 }
6899
6900 if (bRequiresSave) { // refill CRC table for all samples in RAM ...
6901 uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
6902 {
6903 File::SampleList::iterator iter = pSamples->begin();
6904 File::SampleList::iterator end = pSamples->end();
6905 for (; iter != end; ++iter) {
6906 gig::Sample* pSample = (gig::Sample*) *iter;
6907 int index = GetWaveTableIndexOf(pSample);
6908 if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6909 store32(&pData[index*8], 1); // always 1
6910 store32(&pData[index*8 + 4], pSample->CalculateWaveDataChecksum());
6911 }
6912 }
6913 } else { // no file structure changes necessary, so directly write to disk and we are done ...
6914 // make sure file is in write mode
6915 pRIFF->SetMode(RIFF::stream_mode_read_write);
6916 {
6917 File::SampleList::iterator iter = pSamples->begin();
6918 File::SampleList::iterator end = pSamples->end();
6919 for (; iter != end; ++iter) {
6920 gig::Sample* pSample = (gig::Sample*) *iter;
6921 int index = GetWaveTableIndexOf(pSample);
6922 if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6923 pSample->crc = pSample->CalculateWaveDataChecksum();
6924 SetSampleChecksum(pSample, pSample->crc);
6925 }
6926 }
6927 }
6928
6929 return bRequiresSave;
6930 }
6931
6939 if (!pGroups) LoadGroups();
6940 // there must always be at least one group
6941 GroupsIterator = pGroups->begin();
6942 return *GroupsIterator;
6943 }
6944
6952 if (!pGroups) return NULL;
6953 ++GroupsIterator;
6954 return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
6955 }
6956
6963 Group* File::GetGroup(size_t index) {
6964 if (!pGroups) LoadGroups();
6965 if (index >= pGroups->size()) return NULL;
6966 return (*pGroups)[index];
6967 }
6968
6979 Group* File::GetGroup(String name) {
6980 if (!pGroups) LoadGroups();
6981 size_t i = 0;
6982 for (Group* pGroup = GetGroup(i); pGroup; pGroup = GetGroup(++i))
6983 if (pGroup->Name == name) return pGroup;
6984 return NULL;
6985 }
6986
6987 Group* File::AddGroup() {
6988 if (!pGroups) LoadGroups();
6989 // there must always be at least one group
6991 Group* pGroup = new Group(this, NULL);
6992 pGroups->push_back(pGroup);
6993 return pGroup;
6994 }
6995
7005 void File::DeleteGroup(Group* pGroup) {
7006 if (!pGroups) LoadGroups();
7007 std::vector<Group*>::iterator iter =
7008 find(pGroups->begin(), pGroups->end(), pGroup);
7009 if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
7010 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
7011 // delete all members of this group
7012 Sample* pSample;
7013 while ((pSample = pGroup->GetSample(0))) {
7014 DeleteSample(pSample);
7015 }
7016 // now delete this group object
7017 pGroups->erase(iter);
7018 pGroup->DeleteChunks();
7019 delete pGroup;
7020 }
7021
7032 void File::DeleteGroupOnly(Group* pGroup) {
7033 if (!pGroups) LoadGroups();
7034 std::vector<Group*>::iterator iter =
7035 find(pGroups->begin(), pGroups->end(), pGroup);
7036 if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
7037 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
7038 // move all members of this group to another group
7039 pGroup->MoveAll();
7040 pGroups->erase(iter);
7041 pGroup->DeleteChunks();
7042 delete pGroup;
7043 }
7044
7045 void File::LoadGroups() {
7046 if (!pGroups) pGroups = new std::vector<Group*>;
7047 // try to read defined groups from file
7048 RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
7049 if (lst3gri) {
7050 RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
7051 if (lst3gnl) {
7052 size_t i = 0;
7053 for (RIFF::Chunk* ck = lst3gnl->GetSubChunkAt(i); ck;
7054 ck = lst3gnl->GetSubChunkAt(++i))
7055 {
7056 if (ck->GetChunkID() == CHUNK_ID_3GNM) {
7057 if (pVersion && pVersion->major > 2 &&
7058 strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
7059
7060 pGroups->push_back(new Group(this, ck));
7061 }
7062 }
7063 }
7064 }
7065 // if there were no group(s), create at least the mandatory default group
7066 if (!pGroups->size()) {
7067 Group* pGroup = new Group(this, NULL);
7068 pGroup->Name = "Default Group";
7069 pGroups->push_back(pGroup);
7070 }
7071 }
7072
7080 ScriptGroup* File::GetScriptGroup(size_t index) {
7081 if (!pScriptGroups) LoadScriptGroups();
7082 if (index >= pScriptGroups->size()) return NULL;
7083 return (*pScriptGroups)[index];
7084 }
7085
7094 ScriptGroup* File::GetScriptGroup(const String& name) {
7095 if (!pScriptGroups) LoadScriptGroups();
7096 for (size_t i = 0; i < pScriptGroups->size(); ++i) {
7097 ScriptGroup* pGroup = (*pScriptGroups)[i];
7098 if (pGroup->Name == name) return pGroup;
7099 }
7100 return NULL;
7101 }
7102
7111 ScriptGroup* File::AddScriptGroup() {
7112 if (!pScriptGroups) LoadScriptGroups();
7113 ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
7114 pScriptGroups->push_back(pScriptGroup);
7115 return pScriptGroup;
7116 }
7117
7130 void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
7131 if (!pScriptGroups) LoadScriptGroups();
7132 std::vector<ScriptGroup*>::iterator iter =
7133 find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
7134 if (iter == pScriptGroups->end())
7135 throw gig::Exception("Could not delete script group, could not find given script group");
7136 pScriptGroups->erase(iter);
7137 for (int i = 0; pScriptGroup->GetScript(i); ++i)
7138 pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
7139 if (pScriptGroup->pList)
7140 pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
7141 pScriptGroup->DeleteChunks();
7142 delete pScriptGroup;
7143 }
7144
7145 void File::LoadScriptGroups() {
7146 if (pScriptGroups) return;
7147 pScriptGroups = new std::vector<ScriptGroup*>;
7148 RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
7149 if (lstLS) {
7150 size_t i = 0;
7151 for (RIFF::List* lst = lstLS->GetSubListAt(i); lst;
7152 lst = lstLS->GetSubListAt(++i))
7153 {
7154 if (lst->GetListType() == LIST_TYPE_RTIS) {
7155 pScriptGroups->push_back(new ScriptGroup(this, lst));
7156 }
7157 }
7158 }
7159 }
7160
7172 void File::UpdateChunks(progress_t* pProgress) {
7173 bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
7174
7175 // update own gig format extension chunks
7176 // (not part of the GigaStudio 4 format)
7177 RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
7178 if (!lst3LS) {
7179 lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
7180 }
7181 // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
7182 // location of <3LS > is irrelevant, however it should be located
7183 // before the actual wave data
7184 RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
7185 pRIFF->MoveSubChunk(lst3LS, ckPTBL);
7186
7187 // This must be performed before writing the chunks for instruments,
7188 // because the instruments' script slots will write the file offsets
7189 // of the respective instrument script chunk as reference.
7190 if (pScriptGroups) {
7191 // Update instrument script (group) chunks.
7192 for (std::vector<ScriptGroup*>::iterator it = pScriptGroups->begin();
7193 it != pScriptGroups->end(); ++it)
7194 {
7195 (*it)->UpdateChunks(pProgress);
7196 }
7197 }
7198
7199 // in case no libgig custom format data was added, then remove the
7200 // custom "3LS " chunk again
7201 if (!lst3LS->CountSubChunks()) {
7202 pRIFF->DeleteSubChunk(lst3LS);
7203 lst3LS = NULL;
7204 }
7205
7206 // first update base class's chunks
7207 DLS::File::UpdateChunks(pProgress);
7208
7209 if (newFile) {
7210 // INFO was added by Resource::UpdateChunks - make sure it
7211 // is placed first in file
7212 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
7213 RIFF::Chunk* first = pRIFF->GetSubChunkAt(0);
7214 if (first != info) {
7215 pRIFF->MoveSubChunk(info, first);
7216 }
7217 }
7218
7219 // update group's chunks
7220 if (pGroups) {
7221 // make sure '3gri' and '3gnl' list chunks exist
7222 // (before updating the Group chunks)
7223 RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
7224 if (!_3gri) {
7225 _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
7226 pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
7227 }
7228 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
7229 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
7230
7231 // v3: make sure the file has 128 3gnm chunks
7232 // (before updating the Group chunks)
7233 if (pVersion && pVersion->major > 2) {
7234 size_t i = 0;
7235 for (RIFF::Chunk* _3gnm = _3gnl->GetSubChunkAt(i); i < 128;
7236 _3gnm = _3gnl->GetSubChunkAt(++i))
7237 {
7238 // create 128 empty placeholder strings which will either
7239 // be filled by Group::UpdateChunks below or left empty.
7240 ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
7241 }
7242 }
7243
7244 std::vector<Group*>::iterator iter = pGroups->begin();
7245 std::vector<Group*>::iterator end = pGroups->end();
7246 for (; iter != end; ++iter) {
7247 (*iter)->UpdateChunks(pProgress);
7248 }
7249 }
7250
7251 // update einf chunk
7252
7253 // The einf chunk contains statistics about the gig file, such
7254 // as the number of regions and samples used by each
7255 // instrument. It is divided in equally sized parts, where the
7256 // first part contains information about the whole gig file,
7257 // and the rest of the parts map to each instrument in the
7258 // file.
7259 //
7260 // At the end of each part there is a bit map of each sample
7261 // in the file, where a set bit means that the sample is used
7262 // by the file/instrument.
7263 //
7264 // Note that there are several fields with unknown use. These
7265 // are set to zero.
7266
7267 int sublen = int(pSamples->size() / 8 + 49);
7268 int einfSize = (Instruments + 1) * sublen;
7269
7270 RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
7271 if (einf) {
7272 if (einf->GetSize() != einfSize) {
7273 einf->Resize(einfSize);
7274 memset(einf->LoadChunkData(), 0, einfSize);
7275 }
7276 } else if (newFile) {
7277 einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
7278 }
7279 if (einf) {
7280 uint8_t* pData = (uint8_t*) einf->LoadChunkData();
7281
7282 std::map<gig::Sample*,int> sampleMap;
7283 size_t sampleIdx = 0;
7284 for (Sample* pSample = GetSample(0); pSample;
7285 pSample = GetSample(++sampleIdx))
7286 {
7287 sampleMap[pSample] = sampleIdx;
7288 }
7289
7290 int totnbusedsamples = 0;
7291 int totnbusedchannels = 0;
7292 int totnbregions = 0;
7293 int totnbdimregions = 0;
7294 int totnbloops = 0;
7295 int instrumentIdx = 0;
7296
7297 memset(&pData[48], 0, sublen - 48);
7298
7299 size_t iIns = 0;
7300 for (Instrument* instrument = GetInstrument(iIns); instrument;
7301 instrument = GetInstrument(++iIns))
7302 {
7303 int nbusedsamples = 0;
7304 int nbusedchannels = 0;
7305 int nbdimregions = 0;
7306 int nbloops = 0;
7307
7308 memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
7309
7310 size_t iRgn = 0;
7311 for (Region* region = instrument->GetRegionAt(iRgn); region;
7312 region = instrument->GetRegionAt(++iRgn))
7313 {
7314 for (int i = 0 ; i < region->DimensionRegions ; i++) {
7315 gig::DimensionRegion *d = region->pDimensionRegions[i];
7316 if (d->pSample) {
7317 int sampleIdx = sampleMap[d->pSample];
7318 int byte = 48 + sampleIdx / 8;
7319 int bit = 1 << (sampleIdx & 7);
7320 if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
7321 pData[(instrumentIdx + 1) * sublen + byte] |= bit;
7322 nbusedsamples++;
7323 nbusedchannels += d->pSample->Channels;
7324
7325 if ((pData[byte] & bit) == 0) {
7326 pData[byte] |= bit;
7327 totnbusedsamples++;
7328 totnbusedchannels += d->pSample->Channels;
7329 }
7330 }
7331 }
7332 if (d->SampleLoops) nbloops++;
7333 }
7334 nbdimregions += region->DimensionRegions;
7335 }
7336 // first 4 bytes unknown - sometimes 0, sometimes length of einf part
7337 // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
7338 store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
7339 store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
7340 store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
7341 store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
7342 store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
7343 store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
7344 // next 8 bytes unknown
7345 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
7346 store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
7347 // next 4 bytes unknown
7348
7349 totnbregions += instrument->Regions;
7350 totnbdimregions += nbdimregions;
7351 totnbloops += nbloops;
7352 instrumentIdx++;
7353 }
7354 // first 4 bytes unknown - sometimes 0, sometimes length of einf part
7355 // store32(&pData[0], sublen);
7356 store32(&pData[4], totnbusedchannels);
7357 store32(&pData[8], totnbusedsamples);
7358 store32(&pData[12], Instruments);
7359 store32(&pData[16], totnbregions);
7360 store32(&pData[20], totnbdimregions);
7361 store32(&pData[24], totnbloops);
7362 // next 8 bytes unknown
7363 // next 4 bytes unknown, not always 0
7364 store32(&pData[40], (uint32_t) pSamples->size());
7365 // next 4 bytes unknown
7366 }
7367
7368 // update 3crc chunk
7369
7370 // The 3crc chunk contains CRC-32 checksums for the
7371 // samples. When saving a gig file to disk, we first update the 3CRC
7372 // chunk here (in RAM) with the old crc values which we read from the
7373 // 3CRC chunk when we opened the file (available with gig::Sample::crc
7374 // member variable). This step is required, because samples might have
7375 // been deleted by the user since the file was opened, which in turn
7376 // changes the order of the (i.e. old) checksums within the 3crc chunk.
7377 // If a sample was conciously modified by the user (that is if
7378 // Sample::Write() was called later on) then Sample::Write() will just
7379 // update the respective individual checksum(s) directly on disk and
7380 // leaves all other sample checksums untouched.
7381
7382 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
7383 if (_3crc) {
7384 _3crc->Resize(pSamples->size() * 8);
7385 } else /*if (newFile)*/ {
7386 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
7387 // the order of einf and 3crc is not the same in v2 and v3
7388 if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf);
7389 }
7390 { // must be performed in RAM here ...
7391 uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
7392 if (pData) {
7393 File::SampleList::iterator iter = pSamples->begin();
7394 File::SampleList::iterator end = pSamples->end();
7395 for (int index = 0; iter != end; ++iter, ++index) {
7396 gig::Sample* pSample = (gig::Sample*) *iter;
7397 store32(&pData[index*8], 1); // always 1
7398 store32(&pData[index*8 + 4], pSample->crc);
7399 }
7400 }
7401 }
7402 }
7403
7406
7407 size_t i = 0;
7408 for (Instrument* instrument = GetInstrument(i); instrument;
7409 instrument = GetInstrument(++i))
7410 {
7411 instrument->UpdateScriptFileOffsets();
7412 }
7413 }
7414
7430 void File::SetAutoLoad(bool b) {
7431 bAutoLoad = b;
7432 }
7433
7439 return bAutoLoad;
7440 }
7441
7455 bool File::UsesAnyGigFormatExtension() const {
7456 if (!pInstruments) return false;
7457 InstrumentList::iterator iter = pInstruments->begin();
7458 InstrumentList::iterator end = pInstruments->end();
7459 for (; iter != end; ++iter) {
7460 Instrument* pInstrument = static_cast<gig::Instrument*>(*iter);
7461 if (pInstrument->UsesAnyGigFormatExtension())
7462 return true;
7463 }
7464 return false;
7465 }
7466
7467
7468// *************** Exception ***************
7469// *
7470
7471 Exception::Exception() : DLS::Exception() {
7472 }
7473
7474 Exception::Exception(String format, ...) : DLS::Exception() {
7475 va_list arg;
7476 va_start(arg, format);
7477 Message = assemble(format, arg);
7478 va_end(arg);
7479 }
7480
7481 Exception::Exception(String format, va_list arg) : DLS::Exception() {
7482 Message = assemble(format, arg);
7483 }
7484
7485 void Exception::PrintMessage() const {
7486 std::cout << "gig::Exception: " << Message << std::endl;
7487 }
7488
7489
7490// *************** functions ***************
7491// *
7492
7498 String libraryName() {
7499 return PACKAGE;
7500 }
7501
7507 return VERSION;
7508 }
7509
7510} // namespace gig
virtual void UpdateChunks(progress_t *pProgress)
Apply all the DLS file's current instruments, samples and settings to the respective RIFF chunks.
Definition DLS.cpp:2052
void __ensureMandatoryChunksExist()
Checks if all (for DLS) mandatory chunks exist, if not they will be created.
Definition DLS.cpp:2471
File()
Constructor.
Definition DLS.cpp:1660
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition DLS.cpp:2462
Sample * GetFirstSample()
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition DLS.cpp:1794
void SetFixedStringLengths(const string_length_t *lengths)
Forces specific Info fields to be of a fixed length when being saved to a file.
Definition DLS.cpp:379
Provides all neccessary information for the synthesis of a DLS Instrument.
Definition DLS.h:524
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Instrument object.
Definition DLS.cpp:1592
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition DLS.cpp:1536
Defines Region information of an Instrument.
Definition DLS.h:493
virtual void CopyAssign(const Region *orig)
Make a (semi) deep copy of the Region object given by orig and assign it to this object.
Definition DLS.cpp:1342
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings to the respective RIFF chunks.
Definition DLS.cpp:1280
range_t KeyRange
Definition DLS.h:495
virtual void SetKeyRange(uint16_t Low, uint16_t High)
Modifies the key range of this Region and makes sure the respective chunks are in correct order.
Definition DLS.cpp:1245
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Region object.
Definition DLS.cpp:1201
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
Definition DLS.h:406
void GenerateDLSID()
Generates a new DLSID for the resource.
Definition DLS.cpp:604
Encapsulates sample waves used for playback.
Definition DLS.h:457
void CopyAssignCore(const Sample *orig)
Make a deep copy of the Sample object given by orig (without the actual sample waveform data however)...
Definition DLS.cpp:914
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
Definition DLS.cpp:1115
void Resize(file_offset_t NewSize)
Resize sample.
Definition DLS.cpp:1036
uint16_t BitDepth
Size of each sample per channel (only if known sample data format is used, 0 otherwise).
Definition DLS.h:464
uint16_t Channels
Number of channels represented in the waveform data, e.g. 1 for mono, 2 for stereo (defaults to 1=mon...
Definition DLS.h:460
file_offset_t GetSize() const
Returns sample size.
Definition DLS.cpp:1003
uint32_t SamplesPerSecond
Sampling rate at which each channel should be played (defaults to 44100 if Sample was created with In...
Definition DLS.h:461
file_offset_t SamplesTotal
Reflects total number of sample points (only if known sample data format is used, 0 otherwise),...
Definition DLS.h:465
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Sample object.
Definition DLS.cpp:891
uint FrameSize
Reflects the size (in bytes) of one single sample point (only if known sample data format is used,...
Definition DLS.h:466
virtual void UpdateChunks(progress_t *pProgress)
Apply all sample player options to the respective RIFF chunk.
Definition DLS.cpp:710
Ordinary RIFF Chunk.
Definition RIFF.h:186
File * GetFile() const
Returns pointer to the chunk's File object.
Definition RIFF.h:191
List * GetParent() const
Returns pointer to the chunk's parent list chunk.
Definition RIFF.h:192
file_offset_t ReadInt8(int8_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 8 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:595
void Resize(file_offset_t NewSize)
Resize chunk.
Definition RIFF.cpp:1036
file_offset_t SetPos(file_offset_t Where, stream_whence_t Whence=stream_start)
Sets the position within the chunk body, thus within the data portion of the chunk (in bytes).
Definition RIFF.cpp:375
file_offset_t GetFilePos() const
Current, actual offset in file of current chunk data body read/write position.
Definition RIFF.cpp:358
file_offset_t RemainingBytes() const
Returns the number of bytes left to read in the chunk body.
Definition RIFF.cpp:410
file_offset_t ReadUint32(uint32_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 32 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition RIFF.cpp:790
file_offset_t GetPos() const
Current read/write position within the chunk data body (starting with 0).
Definition RIFF.cpp:345
file_offset_t ReadUint16(uint16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition RIFF.cpp:712
file_offset_t Read(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Reads WordCount number of data words with given WordSize and copies it into a buffer pointed by pData...
Definition RIFF.cpp:475
file_offset_t ReadInt16(int16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:673
void * LoadChunkData()
Load chunk body into RAM.
Definition RIFF.cpp:962
file_offset_t ReadInt32(int32_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 32 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:751
file_offset_t ReadUint8(uint8_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 8 Bit unsigned integer words and copies it into the buffer pointed by pData...
Definition RIFF.cpp:634
file_offset_t WriteUint32(uint32_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 32 Bit unsigned integer words from the buffer pointed by pData to the chun...
Definition RIFF.cpp:830
void ReadString(String &s, int size)
Reads a null-padded string of size characters and copies it into the string s.
Definition RIFF.cpp:808
file_offset_t GetSize() const
Chunk size in bytes (without header, thus the chunk data body).
Definition RIFF.h:193
file_offset_t GetNewSize() const
New chunk size if it was modified with Resize(), otherwise value returned will be equal to GetSize().
Definition RIFF.h:194
RIFF File.
Definition RIFF.h:314
int GetFileOffsetSize() const
Returns the current size (in bytes) of file offsets stored in the headers of all chunks of this file.
Definition RIFF.cpp:2571
file_offset_t GetCurrentFileSize() const
Returns the current size of this file (in bytes) as it is currently yet stored on disk.
Definition RIFF.cpp:2477
bool IsNew() const
Returns true if this file has been created new from scratch and has not been stored to disk yet.
Definition RIFF.cpp:2455
RIFF List Chunk.
Definition RIFF.h:262
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition RIFF.cpp:1251
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
Definition RIFF.cpp:1489
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
Definition RIFF.cpp:1546
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
Definition RIFF.cpp:1569
List * GetSubListAt(size_t pos)
Returns sublist chunk with list type ListType at supplied pos position among all subchunks of type Li...
Definition RIFF.cpp:1269
size_t CountSubChunks()
Returns number of subchunks within the list (including list chunks).
Definition RIFF.cpp:1401
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
Definition RIFF.cpp:1292
uint32_t GetListType() const
Returns unsigned integer representation of the list's ID.
Definition RIFF.h:266
Chunk * AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize)
Creates a new sub chunk.
Definition RIFF.cpp:1463
Chunk * GetSubChunkAt(size_t pos)
Returns subchunk at supplied pos position within this chunk list.
Definition RIFF.cpp:1234
Destination container for serialization, and source container for deserialization.
Encapsulates articulation informations of a dimension region.
Definition gig.h:535
uint8_t VelocityResponseCurveScaling
0 - 127 (usually you don't have to interpret this parameter, use GetVelocityAttenuation() instead).
Definition gig.h:610
vcf_cutoff_ctrl_t VCFCutoffController
Specifies which external controller has influence on the filter cutoff frequency.
Definition gig.h:596
void SetReleaseVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3151
uint8_t VelocityResponseDepth
Dynamic range of velocity affecting amplitude (0 - 4) (usually you don't have to interpret this param...
Definition gig.h:609
bool EG2InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released.
Definition gig.h:566
void SetVCFCutoffController(vcf_cutoff_ctrl_t controller)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3160
eg2_ctrl_t EG2Controller
MIDI Controller which has influence on filter cutoff EG parameters (attack, decay,...
Definition gig.h:569
double EG2Release
Release time of the filter cutoff EG (0.000 - 60.000s).
Definition gig.h:568
eg1_ctrl_t EG1Controller
MIDI Controller which has influence on sample amplitude EG parameters (attack, decay,...
Definition gig.h:548
vcf_type_t VCFType
Defines the general filter characteristic (lowpass, highpass, bandpass, etc.).
Definition gig.h:595
double LFO3Phase
[gig extension]: Phase displacement of the pitch LFO's wave form (0.0° - 360.0°).
Definition gig.h:587
bool LFO3Sync
If set to true only one LFO should be used for all voices.
Definition gig.h:592
uint8_t VCFVelocityDynamicRange
0x04 = lowest, 0x00 = highest .
Definition gig.h:601
lfo3_ctrl_t LFO3Controller
MIDI Controller which controls the sample pitch LFO.
Definition gig.h:590
double EG1Decay1
Decay time of the sample amplitude EG (0.000 - 60.000s).
Definition gig.h:542
bool PitchTrack
If true: sample will be pitched according to the key position (this will be disabled for drums for ex...
Definition gig.h:616
double SampleAttenuation
Sample volume (calculated from DLS::Sampler::Gain).
Definition gig.h:627
uint8_t VCFVelocityScale
(0-127) Amount velocity controls VCF cutoff frequency (only if no other VCF cutoff controller is defi...
Definition gig.h:600
virtual void CopyAssign(const DimensionRegion *orig)
Make a (semi) deep copy of the DimensionRegion object given by orig and assign it to this object.
Definition gig.cpp:1803
uint8_t EG1ControllerDecayInfluence
Amount EG1 Controller has influence on the EG1 Decay time (0 - 3, where 0 means off).
Definition gig.h:551
eg_opt_t EG1Options
[gig extension]: Behavior options which should be used for envelope generator 1 (volume amplitude EG)...
Definition gig.h:629
uint8_t EG2ControllerDecayInfluence
Amount EG2 Controller has influence on the EG2 Decay time (0 - 3, where 0 means off).
Definition gig.h:572
bool EG1InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released.
Definition gig.h:544
double EG2Decay1
Decay time of the filter cutoff EG (0.000 - 60.000s).
Definition gig.h:564
bool LFO1FlipPhase
Inverts the polarity of the sample amplitude LFO wave, so it flips the wave form vertically.
Definition gig.h:559
int16_t EG3Depth
Depth of the sample pitch EG (-1200 - +1200).
Definition gig.h:584
uint8_t ChannelOffset
Audio output where the audio signal of the dimension region should be routed to (0 - 9).
Definition gig.h:623
Sample * pSample
Points to the Sample which is assigned to the dimension region.
Definition gig.h:538
lfo_wave_t LFO1WaveForm
[gig extension]: The fundamental wave form to be used by the amplitude LFO, e.g. sine,...
Definition gig.h:553
uint8_t EG2ControllerAttackInfluence
Amount EG2 Controller has influence on the EG2 Attack time (0 - 3, where 0 means off).
Definition gig.h:571
void SetVCFVelocityScale(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3187
lfo_wave_t LFO3WaveForm
[gig extension]: The fundamental wave form to be used by the pitch LFO, e.g. sine,...
Definition gig.h:585
int16_t LFO3ControlDepth
Controller depth of the sample pitch LFO (-1200 - +1200 cents).
Definition gig.h:589
uint8_t EG2ControllerReleaseInfluence
Amount EG2 Controller has influence on the EG2 Release time (0 - 3, where 0 means off).
Definition gig.h:573
uint8_t EG1ControllerAttackInfluence
Amount EG1 Controller has influence on the EG1 Attack time (0 - 3, where 0 means off).
Definition gig.h:550
void SetReleaseVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3142
lfo2_ctrl_t LFO2Controller
MIDI Controlle which controls the filter cutoff LFO.
Definition gig.h:579
uint8_t VCFKeyboardTrackingBreakpoint
See VCFKeyboardTracking (0 - 127).
Definition gig.h:606
bool VCFResonanceDynamic
If true: Increases the resonance Q according to changes of controllers that actually control the VCF ...
Definition gig.h:603
double LFO2Phase
[gig extension]: Phase displacement of the filter cutoff LFO's wave form (0.0° - 360....
Definition gig.h:576
uint8_t DimensionUpperLimits[8]
gig3: defines the upper limit of the dimension values for this dimension region. In case you wondered...
Definition gig.h:628
uint8_t EG1ControllerReleaseInfluence
Amount EG1 Controller has influence on the EG1 Release time (0 - 3, where 0 means off).
Definition gig.h:552
uint8_t VCFResonance
Firm internal filter resonance weight.
Definition gig.h:602
uint16_t EG1Sustain
Sustain value of the sample amplitude EG (0 - 1000 permille).
Definition gig.h:545
dim_bypass_ctrl_t DimensionBypass
If defined, the MIDI controller can switch on/off the dimension in realtime.
Definition gig.h:617
bool EG2ControllerInvert
Invert values coming from defined EG2 controller.
Definition gig.h:570
void SetVCFVelocityDynamicRange(uint8_t range)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3178
uint8_t * VelocityTable
For velocity dimensions with custom defined zone ranges only: used for fast converting from velocity ...
Definition gig.h:663
bool LFO1Sync
If set to true only one LFO should be used for all voices.
Definition gig.h:560
double EG1Attack
Attack time of the sample amplitude EG (0.000 - 60.000s).
Definition gig.h:541
uint32_t SampleLoops
Reflects the number of sample loops.
Definition DLS.h:432
void SetVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3106
attenuation_ctrl_t AttenuationController
MIDI Controller which has influence on the volume level of the sample (or entire sample group).
Definition gig.h:620
double LFO1Phase
[gig extension]: Phase displacement of the amplitude LFO's wave form (0.0° - 360.0°).
Definition gig.h:555
virtual void UpdateChunks(progress_t *pProgress)
Apply dimension region settings to the respective RIFF chunks.
Definition gig.cpp:1975
double GetVelocityAttenuation(uint8_t MIDIKeyVelocity)
Returns the correct amplitude factor for the given MIDIKeyVelocity.
Definition gig.cpp:3090
double LFO1Frequency
Frequency of the sample amplitude LFO (0.10 - 10.00 Hz).
Definition gig.h:554
curve_type_t VelocityResponseCurve
Defines a transformation curve to the incoming velocity values affecting amplitude (usually you don't...
Definition gig.h:608
uint16_t EG2Sustain
Sustain value of the filter cutoff EG (0 - 1000 permille).
Definition gig.h:567
uint16_t LFO2ControlDepth
Controller depth influencing filter cutoff LFO pitch (0 - 1200).
Definition gig.h:578
lfo_wave_t LFO2WaveForm
[gig extension]: The fundamental wave form to be used by the filter cutoff LFO, e....
Definition gig.h:574
bool VCFKeyboardTracking
If true: VCF cutoff frequence will be dependend to the note key position relative to the defined brea...
Definition gig.h:605
uint8_t AttenuationControllerThreshold
0-127
Definition gig.h:622
double EG1Release
Release time of the sample amplitude EG (0.000 - 60.000s).
Definition gig.h:546
bool NoNoteOffReleaseTrigger
[gig extension]: If true then don't play a release trigger sample on MIDI note-off events.
Definition gig.h:632
void SetVelocityResponseCurveScaling(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3130
uint8_t VelocityUpperLimit
Defines the upper velocity value limit of a velocity split (only if an user defined limit was set,...
Definition gig.h:537
bool EG1Hold
If true, Decay1 stage should be postponed until the sample reached the sample loop start.
Definition gig.h:547
uint8_t ReleaseVelocityResponseDepth
Dynamic range of release velocity affecting envelope time (0 - 4).
Definition gig.h:612
curve_type_t ReleaseVelocityResponseCurve
Defines a transformation curve to the incoming release veloctiy values affecting envelope times.
Definition gig.h:611
void SetVCFVelocityCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3169
double EG1Decay2
Only if EG1InfiniteSustain == false: 2nd decay stage time of the sample amplitude EG (0....
Definition gig.h:543
bool InvertAttenuationController
Inverts the values coming from the defined Attenuation Controller.
Definition gig.h:621
uint16_t SampleStartOffset
Number of samples the sample start should be moved (0 - 2000).
Definition gig.h:626
double EG2Decay2
Only if EG2InfiniteSustain == false: 2nd stage decay time of the filter cutoff EG (0....
Definition gig.h:565
uint16_t LFO1InternalDepth
Firm pitch of the sample amplitude LFO (0 - 1200 cents).
Definition gig.h:556
bool EG1ControllerInvert
Invert values coming from defined EG1 controller.
Definition gig.h:549
lfo1_ctrl_t LFO1Controller
MIDI Controller which controls sample amplitude LFO.
Definition gig.h:558
bool VCFCutoffControllerInvert
Inverts values coming from the defined cutoff controller.
Definition gig.h:597
double LFO3Frequency
Frequency of the sample pitch LFO (0.10 - 10.00 Hz).
Definition gig.h:586
uint8_t ReleaseTriggerDecay
0 - 8
Definition gig.h:613
double EG3Attack
Attack time of the sample pitch EG (0.000 - 10.000s).
Definition gig.h:583
virtual void SetGain(int32_t gain)
Updates the respective member variable and updates SampleAttenuation which depends on this value.
Definition gig.cpp:1961
double LFO2Frequency
Frequency of the filter cutoff LFO (0.10 - 10.00 Hz).
Definition gig.h:575
bool SustainDefeat
If true: Sustain pedal will not hold a note.
Definition gig.h:624
eg_opt_t EG2Options
[gig extension]: Behavior options which should be used for envelope generator 2 (filter cutoff EG).
Definition gig.h:630
bool LFO2FlipPhase
Inverts the polarity of the filter cutoff LFO wave, so it flips the wave form vertically.
Definition gig.h:580
sust_rel_trg_t SustainReleaseTrigger
[gig extension]: Whether a sustain pedal up event shall play release trigger sample.
Definition gig.h:631
sample_loop_t * pSampleLoops
Points to the beginning of a sample loop array, or is NULL if there are no loops defined.
Definition DLS.h:433
bool MSDecode
Gigastudio flag: defines if Mid Side Recordings should be decoded.
Definition gig.h:625
bool VCFEnabled
If filter should be used.
Definition gig.h:594
uint16_t LFO1ControlDepth
Controller depth influencing sample amplitude LFO pitch (0 - 1200 cents).
Definition gig.h:557
int8_t Pan
Panorama / Balance (-64..0..63 <-> left..middle..right).
Definition gig.h:618
void SetVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value.
Definition gig.cpp:3118
bool LFO2Sync
If set to true only one LFO should be used for all voices.
Definition gig.h:581
uint16_t EG1PreAttack
Preattack value of the sample amplitude EG (0 - 1000 permille).
Definition gig.h:540
bool SelfMask
If true: high velocity notes will stop low velocity notes at the same note, with that you can save vo...
Definition gig.h:619
uint8_t VCFCutoff
Max. cutoff frequency.
Definition gig.h:598
curve_type_t VCFVelocityCurve
Defines a transformation curve for the incoming velocity values, affecting the VCF.
Definition gig.h:599
double EG2Attack
Attack time of the filter cutoff EG (0.000 - 60.000s).
Definition gig.h:563
uint16_t EG2PreAttack
Preattack value of the filter cutoff EG (0 - 1000 permille).
Definition gig.h:562
uint16_t LFO2InternalDepth
Firm pitch of the filter cutoff LFO (0 - 1200 cents).
Definition gig.h:577
vcf_res_ctrl_t VCFResonanceController
Specifies which external controller has influence on the filter resonance Q.
Definition gig.h:604
int16_t LFO3InternalDepth
Firm depth of the sample pitch LFO (-1200 - +1200 cents).
Definition gig.h:588
bool LFO3FlipPhase
[gig extension]: Inverts the polarity of the pitch LFO wave, so it flips the wave form vertically (NO...
Definition gig.h:591
Will be thrown whenever a gig specific error occurs while trying to access a Gigasampler File.
Definition gig.h:1512
Provides convenient access to Gigasampler/GigaStudio .gig files.
Definition gig.h:1422
version_t * pVersion
Points to a version_t structure if the file provided a version number else is set to NULL.
Definition DLS.h:566
virtual void UpdateChunks(progress_t *pProgress)
Apply all the gig file's current instruments, samples, groups and settings to the respective RIFF chu...
Definition gig.cpp:7172
Sample * GetNextSample()
Returns a pointer to the next Sample object of the file, NULL otherwise.
Definition gig.cpp:6304
size_t CountInstruments()
Returns the total amount of instruments of this gig file.
Definition gig.cpp:6552
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition gig.cpp:7404
ScriptGroup * AddScriptGroup()
Add new instrument script group.
Definition gig.cpp:7111
void SetSampleChecksum(Sample *pSample, uint32_t crc)
Updates the 3crc chunk with the checksum of a sample.
Definition gig.cpp:6785
void DeleteScriptGroup(ScriptGroup *pGroup)
Delete an instrument script group.
Definition gig.cpp:7130
Instrument * GetInstrument(size_t index, progress_t *pProgress=NULL)
Returns the instrument with the given index.
Definition gig.cpp:6565
size_t CountSamples()
Returns the total amount of samples of this gig file.
Definition gig.cpp:6332
Instrument * AddInstrument()
Add a new instrument definition.
Definition gig.cpp:6607
Instrument * GetNextInstrument()
Returns a pointer to the next Instrument object of the file, NULL otherwise.
Definition gig.cpp:6538
static const DLS::version_t VERSION_2
Reflects Gigasampler file format version 2.0 (1998-06-28).
Definition gig.h:1424
Group * GetNextGroup()
Returns a pointer to the next Group object of the file, NULL otherwise.
Definition gig.cpp:6951
bool GetAutoLoad()
Returns whether automatic loading is enabled.
Definition gig.cpp:7438
uint32_t Instruments
Reflects the number of available Instrument objects.
Definition DLS.h:567
void DeleteInstrument(Instrument *pInstrument)
Delete an instrument.
Definition gig.cpp:6735
virtual void Save(const String &Path, progress_t *pProgress=NULL)
Save changes to another file.
Definition DLS.cpp:2294
Sample * GetSample(size_t index, progress_t *pProgress=NULL)
Returns Sample object of index.
Definition gig.cpp:6317
bool RebuildSampleChecksumTable()
Recalculates CRC32 checksums for all samples and rebuilds this gig file's checksum table with those n...
Definition gig.cpp:6881
void DeleteSample(Sample *pSample)
Delete a sample.
Definition gig.cpp:6372
Instrument * AddDuplicateInstrument(const Instrument *orig)
Add a duplicate of an existing instrument.
Definition gig.cpp:6646
ScriptGroup * GetScriptGroup(size_t index)
Get instrument script group (by index).
Definition gig.cpp:7080
Group * GetFirstGroup()
Returns a pointer to the first Group object of the file, NULL otherwise.
Definition gig.cpp:6938
Instrument * GetFirstInstrument()
Returns a pointer to the first Instrument object of the file, NULL otherwise.
Definition gig.cpp:6524
void AddContentOf(File *pFile)
Add content of another existing file.
Definition gig.cpp:6663
Group * GetGroup(size_t index)
Returns the group with the given index.
Definition gig.cpp:6963
Sample * AddSample()
Add a new sample.
Definition gig.cpp:6345
void DeleteGroup(Group *pGroup)
Delete a group and its samples.
Definition gig.cpp:7005
String GetFileName()
File name of this DLS file.
Definition DLS.cpp:2032
void DeleteGroupOnly(Group *pGroup)
Delete a group.
Definition gig.cpp:7032
void SetAutoLoad(bool b)
Enable / disable automatic loading.
Definition gig.cpp:7430
bool VerifySampleChecksumTable()
Checks whether the file's "3CRC" chunk was damaged.
Definition gig.cpp:6844
Group of Gigasampler samples.
Definition gig.h:1365
Group(File *file, RIFF::Chunk *ck3gnm)
Constructor.
Definition gig.cpp:6034
Sample * GetSample(size_t index)
Returns Sample object at index of this sample group.
Definition gig.cpp:6102
Sample * GetFirstSample()
Returns the first Sample of this Group.
Definition gig.cpp:6128
Sample * GetNextSample()
Returns the next Sample of the Group.
Definition gig.cpp:6152
void MoveAll()
Move all members of this group to another group (preferably the 1st one except this).
Definition gig.cpp:6176
virtual void UpdateChunks(progress_t *pProgress)
Update chunks with current group settings.
Definition gig.cpp:6070
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Group object.
Definition gig.cpp:6052
virtual ~Group()
Destructor.
Definition gig.cpp:6045
void AddSample(Sample *pSample)
Move Sample given by pSample from another Group to this Group.
Definition gig.cpp:6166
String Name
Stores the name of this Group.
Definition gig.h:1367
Provides access to a Gigasampler/GigaStudio instrument.
Definition gig.h:1266
void UnsetScriptPatchVariable(ssize_t slot=-1, String variable="")
Drop overridden initial value(s) for 'patch' variable(s).
Definition gig.cpp:5845
MidiRule * GetMidiRule(int i)
Returns a MIDI rule of the instrument.
Definition gig.cpp:5410
void DeleteMidiRule(int i)
Deletes a MIDI rule from the instrument.
Definition gig.cpp:5458
void SetScriptSlotBypassed(size_t index, bool bBypass)
Defines whether execution shall be skipped.
Definition gig.cpp:5665
bool IsScriptPatchVariableSet(size_t slot, String variable)
Checks whether a certain script 'patch' variable value is set.
Definition gig.cpp:5711
virtual void CopyAssign(const Instrument *orig)
Make a (semi) deep copy of the Instrument object given by orig and assign it to this object.
Definition gig.cpp:5941
void SwapScriptSlots(size_t index1, size_t index2)
Flip two script slots with each other (gig format extension).
Definition gig.cpp:5569
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
Definition DLS.h:406
size_t ScriptSlotCount() const
Instrument's amount of script slots.
Definition gig.cpp:5625
int16_t FineTune
in cents
Definition gig.h:1281
Region * GetNextRegion()
Returns the next Region of the instrument.
Definition gig.cpp:5307
int32_t Attenuation
in dB
Definition gig.h:1279
MidiRuleCtrlTrigger * AddMidiRuleCtrlTrigger()
Adds the "controller trigger" MIDI rule to the instrument.
Definition gig.cpp:5419
std::map< String, String > GetScriptPatchVariables(size_t slot)
Get all overridden script 'patch' variables.
Definition gig.cpp:5745
MidiRuleAlternator * AddMidiRuleAlternator()
Adds the alternator MIDI rule to the instrument.
Definition gig.cpp:5445
void MoveTo(Instrument *dst)
Move this instrument at the position before.
Definition gig.cpp:5364
uint32_t Regions
Reflects the number of Region defintions this Instrument has.
Definition DLS.h:531
~Instrument()
Destructor.
Definition gig.cpp:5051
Script * GetScriptOfSlot(size_t index)
Get instrument script (gig format extension).
Definition gig.cpp:5508
MidiRuleLegato * AddMidiRuleLegato()
Adds the legato MIDI rule to the instrument.
Definition gig.cpp:5432
String GetScriptPatchVariable(size_t slot, String variable)
Get overridden initial value for 'patch' variable.
Definition gig.cpp:5777
uint16_t PitchbendRange
Number of semitones pitchbend controller can pitch (default is 2).
Definition gig.h:1282
range_t DimensionKeyRange
0-127 (where 0 means C1 and 127 means G9)
Definition gig.h:1284
Region * GetRegion(unsigned int Key)
Returns the appropriate Region for a triggered note.
Definition gig.cpp:5255
void AddScriptSlot(Script *pScript, bool bypass=false)
Add new instrument script slot (gig format extension).
Definition gig.cpp:5549
Region * RegionKeyTable[128]
fast lookup for the corresponding Region of a MIDI key
Definition gig.h:1321
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition gig.cpp:5069
void RemoveScript(Script *pScript)
Remove reference to given Script (gig format extension).
Definition gig.cpp:5602
void SetScriptPatchVariable(size_t slot, String variable, String value)
Override initial value for 'patch' variable.
Definition gig.cpp:5804
Region * GetFirstRegion()
Returns the first Region of the instrument.
Definition gig.cpp:5291
bool IsScriptSlotBypassed(size_t index)
Whether script execution shall be skipped.
Definition gig.cpp:5645
void RemoveScriptSlot(size_t index)
Remove script slot.
Definition gig.cpp:5584
Region * GetRegionAt(size_t pos)
Returns Region at supplied pos position within the region list of this instrument.
Definition gig.cpp:5276
MIDI rule to automatically cycle through specified sequences of different articulations.
Definition gig.h:1099
uint8_t Controller
CC number for controller selector.
Definition gig.h:1127
struct gig::MidiRuleAlternator::pattern_t pPatterns[32]
A pattern is a sequence of articulation numbers.
range_t KeySwitchRange
Key range for key switch selector.
Definition gig.h:1126
bool Polyphonic
If alternator should step forward only when all notes are off.
Definition gig.h:1129
selector_t Selector
Method by which pattern is chosen.
Definition gig.h:1125
uint8_t Patterns
Number of alternator patterns.
Definition gig.h:1106
range_t PlayRange
Key range of the playable keys in the instrument.
Definition gig.h:1104
uint8_t Articulations
Number of articulations in the instrument.
Definition gig.h:1101
String pArticulations[32]
Names of the articulations.
Definition gig.h:1102
bool Chained
If all patterns should be chained together.
Definition gig.h:1130
MIDI rule for triggering notes by control change events.
Definition gig.h:1026
uint8_t ControllerNumber
MIDI controller number.
Definition gig.h:1028
uint8_t Triggers
Number of triggers.
Definition gig.h:1029
MIDI rule for instruments with legato samples.
Definition gig.h:1067
uint16_t ThresholdTime
Maximum time (ms) between two notes that should be played legato.
Definition gig.h:1073
uint8_t LegatoSamples
Number of legato samples per key in each direction (always 12).
Definition gig.h:1069
uint8_t BypassKey
Key to be used to bypass the sustain note.
Definition gig.h:1071
uint8_t AltSustain1Key
Key triggering alternate sustain samples.
Definition gig.h:1077
bool BypassUseController
If a controller should be used to bypass the sustain note.
Definition gig.h:1070
uint8_t AltSustain2Key
Key triggering a second set of alternate sustain samples.
Definition gig.h:1078
uint16_t ReleaseTime
Release time.
Definition gig.h:1074
range_t KeyRange
Key range for legato notes.
Definition gig.h:1075
uint8_t ReleaseTriggerKey
Key triggering release samples.
Definition gig.h:1076
uint8_t BypassController
Controller to be used to bypass the sustain note.
Definition gig.h:1072
Abstract base class for all MIDI rules.
Definition gig.h:1005
Defines Region information of a Gigasampler/GigaStudio instrument.
Definition gig.h:927
DimensionRegion * pDimensionRegions[256]
Pointer array to the 32 (gig2) or 256 (gig3) possible dimension regions (reflects NULL for dimension ...
Definition gig.h:932
unsigned int Dimensions
Number of defined dimensions, do not alter!
Definition gig.h:929
dimension_def_t pDimensionDefinitions[8]
Defines the five (gig2) or eight (gig3) possible dimensions (the dimension's controller and number of...
Definition gig.h:930
virtual void CopyAssign(const Region *orig)
Make a (semi) deep copy of the Region object given by orig and assign it to this object.
Definition gig.cpp:4320
void SetDimensionType(dimension_t oldType, dimension_t newType)
Change type of an existing dimension.
Definition gig.cpp:4074
dimension_def_t * GetDimensionDefinition(dimension_t type)
Searches in the current Region for a dimension of the given dimension type and returns the precise co...
Definition gig.cpp:4114
void SplitDimensionZone(dimension_t type, int zone)
Divide split zone of a dimension in two (increment zone amount).
Definition gig.cpp:3915
DimensionRegion * GetDimensionRegionByValue(const uint DimValues[8])
Use this method in your audio engine to get the appropriate dimension region with it's articulation d...
Definition gig.cpp:4145
void DeleteDimensionZone(dimension_t type, int zone)
Delete one split zone of a dimension (decrement zone amount).
Definition gig.cpp:3771
void AddDimension(dimension_def_t *pDimDef)
Einstein would have dreamed of it - create a new dimension.
Definition gig.cpp:3569
unsigned int Layers
Amount of defined layers (1 - 32). A value of 1 actually means no layering, a value > 1 means there i...
Definition gig.h:933
~Region()
Destructor.
Definition gig.cpp:4121
Sample * GetSample()
Returns pointer address to the Sample referenced with this region.
Definition gig.cpp:4273
virtual void SetKeyRange(uint16_t Low, uint16_t High)
Modifies the key range of this Region and makes sure the respective chunks are in correct order.
Definition gig.cpp:3475
DimensionRegion * GetDimensionRegionByBit(const uint8_t DimBits[8])
Returns the appropriate DimensionRegion for the given dimension bit numbers (zone index).
Definition gig.cpp:4254
void DeleteDimension(dimension_def_t *pDimDef)
Delete an existing dimension.
Definition gig.cpp:3681
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings and all its DimensionRegions to the respective RIFF chunks.
Definition gig.cpp:3360
uint32_t DimensionRegions
Total number of DimensionRegions this Region contains, do not alter!
Definition gig.h:931
Encapsulates sample waves of Gigasampler/GigaStudio files used for playback.
Definition gig.h:814
static void DestroyDecompressionBuffer(buffer_t &DecompressionBuffer)
Free decompression buffer, previously created with CreateDecompressionBuffer().
Definition gig.cpp:1339
file_offset_t SamplesInLastFrame
For compressed samples only: length of the last sample frame.
Definition gig.h:865
loop_type_t LoopType
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition gig.h:825
uint32_t Loops
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: Numb...
Definition gig.h:823
bool VerifyWaveData(uint32_t *pActually=NULL)
Checks the integrity of this sample's raw audio wave data.
Definition gig.cpp:1401
uint32_t LoopFraction
The fractional value specifies a fraction of a sample at which to loop. This allows a loop to be fine...
Definition gig.h:829
unsigned long FileNo
File number (> 0 when sample is stored in an extension file, 0 when it's in the gig).
Definition gig.h:869
void CopyAssignMeta(const Sample *orig)
Make a (semi) deep copy of the Sample object given by orig (without the actual waveform data) and ass...
Definition gig.cpp:447
uint32_t LoopStart
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition gig.h:826
uint32_t SMPTEOffset
The SMPTE Offset value specifies the time offset to be used for the synchronization / calibration to ...
Definition gig.h:822
buffer_t RAMCache
Buffers samples (already uncompressed) in RAM.
Definition gig.h:868
file_offset_t * FrameTable
For positioning within compressed samples only: stores the offset values for each frame.
Definition gig.h:863
uint32_t Product
Specifies the MIDI model ID defined by the manufacturer corresponding to the Manufacturer field....
Definition gig.h:817
~Sample()
Destructor.
Definition gig.cpp:1438
uint32_t LoopEnd
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition gig.h:827
Group * pGroup
pointer to the Group this sample belongs to (always not-NULL)
Definition gig.h:861
file_offset_t WorstCaseFrameSize
For compressed samples only: size (in bytes) of the largest possible sample frame.
Definition gig.h:866
static buffer_t CreateDecompressionBuffer(file_offset_t MaxReadSize)
Allocates a decompression buffer for streaming (compressed) samples with Sample::Read().
Definition gig.cpp:1322
Sample(File *pFile, RIFF::List *waveList, file_offset_t WavePoolOffset, unsigned long fileNo=0, int index=-1)
Constructor.
Definition gig.cpp:327
void Resize(file_offset_t NewSize)
Resize sample.
Definition gig.cpp:803
file_offset_t SamplePos
For compressed samples only: stores the current position (in sample points).
Definition gig.h:864
file_offset_t FrameOffset
Current offset (sample points) in current sample frame (for decompression only).
Definition gig.h:862
bool Compressed
If the sample wave is compressed (probably just interesting for instrument and sample editors,...
Definition gig.h:831
Group * GetGroup() const
Returns pointer to the Group this Sample belongs to.
Definition gig.cpp:1356
uint32_t MIDIUnityNote
Specifies the musical note at which the sample will be played at it's original sample rate.
Definition gig.h:819
uint32_t crc
Reflects CRC-32 checksum of the raw sample data at the last time when the sample's raw wave form data...
Definition gig.h:872
buffer_t LoadSampleData()
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition gig.cpp:643
void CopyAssignWave(const Sample *orig)
Should be called after CopyAssignMeta() and File::Save() sequence.
Definition gig.cpp:483
smpte_format_t SMPTEFormat
Specifies the Society of Motion Pictures and Television E time format used in the following SMPTEOffs...
Definition gig.h:821
file_offset_t GetPos() const
Returns the current position in the sample (in sample points).
Definition gig.cpp:863
static size_t Instances
Number of instances of class Sample.
Definition gig.h:859
file_offset_t SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence=RIFF::stream_start)
Sets the position within the sample (in sample points, not in bytes).
Definition gig.cpp:829
uint32_t GetWaveDataCRC32Checksum()
Returns the CRC-32 checksum of the sample's raw wave form data at the time when this sample's wave fo...
Definition gig.cpp:1372
file_offset_t ReadAndLoop(void *pBuffer, file_offset_t SampleCount, playback_state_t *pPlaybackState, DimensionRegion *pDimRgn, buffer_t *pExternalDecompressionBuffer=NULL)
Reads SampleCount number of sample points from the position stored in pPlaybackState into the buffer ...
Definition gig.cpp:902
bool Dithered
For 24-bit compressed samples only: if dithering was used during compression with bit reduction.
Definition gig.h:833
file_offset_t Read(void *pBuffer, file_offset_t SampleCount, buffer_t *pExternalDecompressionBuffer=NULL)
Reads SampleCount number of sample points from the current position into the buffer pointed by pBuffe...
Definition gig.cpp:1077
uint32_t LoopID
Specifies the unique ID that corresponds to one of the defined cue points in the cue point list (only...
Definition gig.h:824
static buffer_t InternalDecompressionBuffer
Buffer used for decompression of samples, and only if no external decompression buffer was supplied.
Definition gig.h:860
uint32_t SamplePeriod
Specifies the duration of time that passes during the playback of one sample in nanoseconds (normally...
Definition gig.h:818
uint32_t LoopPlayCount
Number of times the loop should be played (a value of 0 = infinite).
Definition gig.h:830
buffer_t LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount)
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition gig.cpp:692
void ReleaseSampleData()
Frees the cached sample from RAM if loaded with LoadSampleData() previously.
Definition gig.cpp:766
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
Definition gig.cpp:511
file_offset_t Write(void *pBuffer, file_offset_t SampleCount)
Write sample wave data.
Definition gig.cpp:1266
uint32_t Manufacturer
Specifies the MIDI Manufacturer's Association (MMA) Manufacturer code for the sampler intended to rec...
Definition gig.h:816
uint32_t TruncatedBits
For 24-bit compressed samples only: number of bits truncated during compression (0,...
Definition gig.h:832
buffer_t GetCache()
Returns current cached sample points.
Definition gig.cpp:751
uint32_t FineTune
Specifies the fraction of a semitone up from the specified MIDI unity note field. A value of 0x800000...
Definition gig.h:820
file_offset_t SamplesPerFrame
For compressed samples only: number of samples in a full sample frame.
Definition gig.h:867
uint32_t LoopSize
Caution: Use the respective fields in the DimensionRegion instead of this one! (Intended purpose: Len...
Definition gig.h:828
Group of instrument scripts (gig format extension).
Definition gig.h:1230
virtual void UpdateChunks(progress_t *pProgress)
Apply this script group to the respective RIFF chunks.
Definition gig.cpp:4798
void DeleteScript(Script *pScript)
Delete an instrument script.
Definition gig.cpp:4855
Script * AddScript()
Add new instrument script.
Definition gig.cpp:4838
String Name
Name of this script group. For example to be displayed in an instrument editor.
Definition gig.h:1232
Script * GetScript(size_t index)
Get instrument script.
Definition gig.cpp:4821
virtual void DeleteChunks()
Remove all RIFF chunks associated with this ScriptGroup object.
Definition gig.cpp:4786
Real-time instrument script (gig format extension).
Definition gig.h:1179
Compression_t Compression
Whether the script was/should be compressed, and if so, which compression algorithm shall be used.
Definition gig.h:1192
Compression_t
Definition gig.h:1184
@ COMPRESSION_NONE
Is not compressed at all (default).
Definition gig.h:1185
void SetGroup(ScriptGroup *pGroup)
Move this script from its current ScriptGroup to another ScriptGroup given by pGroup.
Definition gig.cpp:4709
Language_t Language
Programming language and dialect the script is written in.
Definition gig.h:1194
Encoding_t Encoding
Format the script's source code text is encoded with.
Definition gig.h:1193
uint8_t Uuid[16]
Persistent Universally Unique Identifier of this script, which remains identical after any changes to...
Definition gig.h:1196
@ ENCODING_ASCII
Standard 8 bit US ASCII character encoding (default).
Definition gig.h:1182
void UpdateChunks(progress_t *pProgress)
Apply this script to the respective RIFF chunks.
Definition gig.cpp:4644
@ LANGUAGE_NKSP
NKSP stands for "Is Not KSP" (default). Refer to the NKSP Reference Manual for details about this scr...
Definition gig.h:1188
bool Bypass
Global bypass: if enabled, this script shall not be executed by the sampler for any instrument.
Definition gig.h:1195
String Name
Arbitrary name of the script, which may be displayed i.e. in an instrument editor.
Definition gig.h:1191
void DeleteChunks()
Remove all RIFF chunks associated with this Script object.
Definition gig.cpp:4632
void SetScriptAsText(const String &text)
Replaces the current script with the new script source code text given by text.
Definition gig.cpp:4617
String GetScriptAsText()
Returns the current script (i.e.
Definition gig.cpp:4603
void CopyAssign(const Script *orig)
Make a (semi) deep copy of the Script object given by orig and assign it to this object.
Definition gig.cpp:4733
ScriptGroup * GetGroup() const
Returns the script group this script currently belongs to.
Definition gig.cpp:4722
void GenerateUuid()
Generate a new Universally Unique Identifier (UUID) for this script.
Definition gig.cpp:4682
DLS specific classes and definitions.
Definition DLS.h:108
stream_whence_t
File stream position dependent to these relations.
Definition RIFF.h:128
uint64_t file_offset_t
Type used by libgig for handling file positioning during file I/O tasks.
Definition RIFF.h:111
Gigasampler/GigaStudio specific classes and definitions.
Definition gig.h:101
@ dim_bypass_ctrl_94
Effect 4 Depth (MIDI Controller 94).
Definition gig.h:183
@ dim_bypass_ctrl_95
Effect 5 Depth (MIDI Controller 95).
Definition gig.h:183
@ dim_bypass_ctrl_none
No controller bypass.
Definition gig.h:183
vcf_res_ctrl_t
Defines how the filter resonance is controlled by.
Definition gig.h:250
@ vcf_res_ctrl_none
No MIDI controller assigned for filter resonance.
Definition gig.h:250
String libraryName()
Returns the name of this C++ library.
Definition gig.cpp:7498
@ smpte_format_no_offset
no SMPTE offset
Definition gig.h:145
curve_type_t
Defines the shape of a function graph.
Definition gig.h:156
@ curve_type_nonlinear
Non-linear curve type.
Definition gig.h:156
@ curve_type_unknown
Unknown curve type.
Definition gig.h:156
@ curve_type_linear
Linear curve type.
Definition gig.h:156
@ curve_type_special
Special curve type.
Definition gig.h:156
lfo1_ctrl_t
Defines how LFO1 is controlled by.
Definition gig.h:219
@ lfo1_ctrl_internal
Only internally controlled.
Definition gig.h:219
sust_rel_trg_t
Defines behaviour of release triggered sample(s) on sustain pedal up event.
Definition gig.h:482
@ sust_rel_trg_none
No release triggered sample(s) are played on sustain pedal up (default).
Definition gig.h:482
vcf_cutoff_ctrl_t
Defines how the filter cutoff frequency is controlled by.
Definition gig.h:238
@ vcf_cutoff_ctrl_none2
The difference between none and none2 is unknown.
Definition gig.h:238
@ vcf_cutoff_ctrl_none
No MIDI controller assigned for filter cutoff frequency.
Definition gig.h:238
lfo_wave_t
Defines the wave form type used by an LFO (gig format extension).
Definition gig.h:173
@ lfo_wave_sine
Sine (sinus) wave form (this is the default wave form).
Definition gig.h:173
split_type_t
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition gig.h:354
@ split_type_bit
dimension values are already the sought bit number
Definition gig.h:354
@ split_type_normal
dimension value between 0-127
Definition gig.h:354
std::array< uint8_t, 16 > _UUIDFromCArray(const uint8_t *pData)
type cast (by copy) uint8_t[16] -> std::array<uint8_t,16>
Definition gig.cpp:5674
String libraryVersion()
Returns version of this C++ library.
Definition gig.cpp:7506
@ loop_type_bidirectional
Alternating loop (forward/backward, also known as Ping Pong).
Definition gig.h:133
@ loop_type_backward
Loop backward (reverse).
Definition gig.h:133
@ loop_type_normal
Loop forward (normal).
Definition gig.h:133
lfo3_ctrl_t
Defines how LFO3 is controlled by.
Definition gig.h:195
@ lfo3_ctrl_modwheel
Only controlled by external modulation wheel.
Definition gig.h:195
lfo2_ctrl_t
Defines how LFO2 is controlled by.
Definition gig.h:207
@ lfo2_ctrl_internal
Only internally controlled.
Definition gig.h:207
dimension_t
Defines the type of dimension, that is how the dimension zones (and thus how the dimension regions ar...
Definition gig.h:343
@ dimension_keyboard
Dimension for keyswitching.
Definition gig.h:343
@ dimension_roundrobinkeyboard
Different samples triggered each time a note is played, any key advances the counter.
Definition gig.h:343
@ dimension_samplechannel
If used sample has more than one channel (thus is not mono).
Definition gig.h:343
@ dimension_smartmidi
For MIDI tools like legato and repetition mode.
Definition gig.h:343
@ dimension_releasetrigger
Special dimension for triggering samples on releasing a key.
Definition gig.h:343
@ dimension_velocity
Key Velocity (this is the only dimension in gig2 where the ranges can exactly be defined).
Definition gig.h:343
@ dimension_random
Different samples triggered each time a note is played, random order.
Definition gig.h:343
@ dimension_none
Dimension not in use.
Definition gig.h:343
@ dimension_roundrobin
Different samples triggered each time a note is played, dimension regions selected in sequence.
Definition gig.h:343
@ dimension_layer
For layering of up to 8 instruments (and eventually crossfading of 2 or 4 layers).
Definition gig.h:343
vcf_type_t
Audio filter types.
Definition gig.h:396
@ vcf_type_lowpassturbo
More poles than normal lowpass (GigaStudio).
Definition gig.h:396
@ vcf_type_lowpass
Standard lowpass filter type (GigaStudio).
Definition gig.h:396
Every subject of an DLS file and the file itself can have an unique, computer generated ID.
Definition DLS.h:123
uint16_t low
Low value of range.
Definition DLS.h:211
uint16_t high
High value of range.
Definition DLS.h:212
Defines Sample Loop Points.
Definition DLS.h:235
uint32_t LoopLength
Length of the looping area (in sample points).
Definition DLS.h:239
uint32_t LoopStart
The start value specifies the offset (in sample points) in the waveform data of the first sample poin...
Definition DLS.h:238
uint32_t LoopType
Defines how the waveform samples will be looped (appropriate loop types for the gig format are define...
Definition DLS.h:237
Quadtuple version number ("major.minor.release.build").
Definition DLS.h:115
float __range_min
Only for internal usage, do not modify!
Definition RIFF.h:172
void(*) callback(progress_t *)
Callback function pointer which has to be assigned to a function for progress notification.
Definition RIFF.h:168
float __range_max
Only for internal usage, do not modify!
Definition RIFF.h:173
Pointer address and size of a buffer.
Definition gig.h:114
file_offset_t NullExtensionSize
The buffer might be bigger than the actual data, if that's the case that unused space at the end of t...
Definition gig.h:117
void * pStart
Points to the beginning of the buffer.
Definition gig.h:115
file_offset_t Size
Size of the actual data in the buffer in bytes.
Definition gig.h:116
uint8_t in_end
End position of fade in.
Definition gig.h:413
uint8_t in_start
Start position of fade in.
Definition gig.h:412
uint8_t out_end
End postition of fade out.
Definition gig.h:415
uint8_t out_start
Start position of fade out.
Definition gig.h:414
General dimension definition.
Definition gig.h:357
dimension_t dimension
Specifies which source (usually a MIDI controller) is associated with the dimension.
Definition gig.h:358
uint8_t zones
Number of zones the dimension has.
Definition gig.h:360
uint8_t bits
Number of "bits" (1 bit = 2 splits/zones, 2 bit = 4 splits/zones, 3 bit = 8 splits/zones,...
Definition gig.h:359
float zone_size
Intended for internal usage: reflects the size of each zone (128/zones) for normal split types only,...
Definition gig.h:362
split_type_t split_type
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition gig.h:361
Defines behavior options for envelope generators (gig format extension).
Definition gig.h:451
bool AttackHoldCancel
Whether the "attack hold" stage is cancelled when receiving a note-off (default: true).
Definition gig.h:453
bool Decay1Cancel
Whether the "decay 1" stage is cancelled when receiving a note-off (default: true).
Definition gig.h:454
bool ReleaseCancel
Whether the "release" stage is cancelled when receiving a note-on (default: true).
Definition gig.h:456
bool AttackCancel
Whether the "attack" stage is cancelled when receiving a note-off (default: true).
Definition gig.h:452
bool Decay2Cancel
Whether the "decay 2" stage is cancelled when receiving a note-off (default: true).
Definition gig.h:455
Defines a controller that has a certain contrained influence on a particular synthesis parameter (use...
Definition gig.h:260
@ type_none
No controller defined.
Definition gig.h:270
@ type_velocity
Key Velocity.
Definition gig.h:270
@ type_controlchange
Ordinary MIDI control change controller, see field 'controller_number'.
Definition gig.h:270
@ type_channelaftertouch
Channel Key Pressure.
Definition gig.h:270
uint controller_number
MIDI controller number if this controller is a control change controller, 0 otherwise.
Definition gig.h:273
type_t type
Controller type.
Definition gig.h:272
Reflects the current playback state for a sample.
Definition gig.h:422
bool reverse
If playback direction is currently backwards (in case there is a pingpong or reverse loop defined).
Definition gig.h:424
file_offset_t loop_cycles_left
How many times the loop has still to be passed, this value will be decremented with each loop cycle.
Definition gig.h:425
file_offset_t position
Current position within the sample.
Definition gig.h:423
uint8_t high
High value of range.
Definition gig.h:110
uint8_t low
Low value of range.
Definition gig.h:109