27#include "Serialization.h"
36#define GIG_FILE_EXT_VERSION 2
43#define INITIAL_SAMPLE_BUFFER_SIZE 512000
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)
60 archive->serializeMember(*this, member, #member);
69 inline int get12lo(
const unsigned char* pSrc)
71 const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
72 return x & 0x800 ? x - 0x1000 : x;
75 inline int get12hi(
const unsigned char* pSrc)
77 const int x = pSrc[1] >> 4 | pSrc[2] << 4;
78 return x & 0x800 ? x - 0x1000 : x;
81 inline int16_t get16(
const unsigned char* pSrc)
83 return int16_t(pSrc[0] | pSrc[1] << 8);
86 inline int get24(
const unsigned char* pSrc)
88 const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
89 return x & 0x800000 ? x - 0x1000000 : x;
92 inline void store24(
unsigned char* pDst,
int x)
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)
105 switch (compressionmode) {
107 pSrc += currentframeoffset * srcStep;
108 while (copysamples) {
117 int y = get16(params);
118 int dy = get16(params + 2);
119 while (currentframeoffset) {
123 currentframeoffset--;
125 while (copysamples) {
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)
142 int y, dy, ddy, dddy;
144#define GET_PARAMS(params) \
146 dy = y - get24((params) + 3); \
147 ddy = get24((params) + 6); \
148 dddy = get24((params) + 9)
158 store24(pDst, y << truncatedBits); \
161 switch (compressionmode) {
163 pSrc += currentframeoffset * 3;
164 while (copysamples) {
165 store24(pDst, get24(pSrc) << truncatedBits);
174 while (currentframeoffset) {
175 SKIP_ONE(get16(pSrc));
177 currentframeoffset--;
179 while (copysamples) {
180 COPY_ONE(get16(pSrc));
188 while (currentframeoffset > 1) {
189 SKIP_ONE(get12lo(pSrc));
190 SKIP_ONE(get12hi(pSrc));
192 currentframeoffset -= 2;
194 if (currentframeoffset) {
195 SKIP_ONE(get12lo(pSrc));
196 currentframeoffset--;
198 COPY_ONE(get12hi(pSrc));
203 while (copysamples > 1) {
204 COPY_ONE(get12lo(pSrc));
205 COPY_ONE(get12hi(pSrc));
210 COPY_ONE(get12lo(pSrc));
216 while (currentframeoffset) {
217 SKIP_ONE(int8_t(*pSrc++));
218 currentframeoffset--;
220 while (copysamples) {
221 COPY_ONE(int8_t(*pSrc++));
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 };
254 ? int(128.0 / dimension_definition.zones) : 0;
262 void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
272 void crossfade_t::serialize(Serialization::Archive* archive) {
284 eg_opt_t::eg_opt_t() {
292 void eg_opt_t::serialize(Serialization::Archive* archive) {
328 :
DLS::
Sample((
DLS::File*) pFile, waveList, WavePoolOffset)
330 static const DLS::Info::string_length_t fixedStringLengths[] = {
331 { CHUNK_ID_INAM, 64 },
345 uint32_t
crc = pFile->GetSampleChecksumByIndex(index);
354 uint16_t iSampleGroup = pCk3gix->ReadInt16();
366 Product = pCkSmpl->ReadInt32();
372 Loops = pCkSmpl->ReadInt32();
373 pCkSmpl->ReadInt32();
374 LoopID = pCkSmpl->ReadInt32();
377 LoopEnd = pCkSmpl->ReadInt32();
414 if (version > 2 &&
BitDepth == 24) {
419 ScanCompressedSample();
484 const int iReadAtOnce = 32*1024;
485 char* buf =
new char[iReadAtOnce * orig->
FrameSize];
487 file_offset_t restorePos = pOrig->
GetPos();
490 for (file_offset_t n = pOrig->
Read(buf, iReadAtOnce); n;
491 n = pOrig->
Read(buf, iReadAtOnce))
495 pOrig->
SetPos(restorePos);
516 pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
518 pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
519 memset(pCkSmpl->LoadChunkData(), 0, 60);
522 uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
531 store32(&pData[28],
Loops);
535 store32(&pData[36],
LoopID);
543 pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
544 if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
546 uint16_t iSampleGroup = 0;
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++) {
559 pData = (uint8_t*) pCk3gix->LoadChunkData();
560 store16(&pData[0], iSampleGroup);
565 RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
567 pWaveList->DeleteSubChunk(ewav);
572 void Sample::ScanCompressedSample() {
575 std::list<file_offset_t> frameOffsets;
583 for (
int i = 0 ; ; i++) {
586 if (
BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->
GetPos());
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];
595 ((pCkData->
RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
596 (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
601 pCkData->
SetPos(frameSize, RIFF::stream_curpos);
605 for (
int i = 0 ; ; i++) {
606 if (
BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
608 const int mode = pCkData->ReadUint8();
609 if (mode > 5)
throw gig::Exception(
"Unknown compression mode");
612 if (pCkData->RemainingBytes() <= frameSize) {
614 ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
619 pCkData->SetPos(frameSize, RIFF::stream_curpos);
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++) {
731 file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->
FrameSize;
832 case RIFF::stream_curpos:
835 case RIFF::stream_end:
838 case RIFF::stream_backward:
841 case RIFF::stream_start:
default:
847 file_offset_t frame = this->
SamplePos / 2048;
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;
865 else return pCkData->GetPos() /
FrameSize;
904 file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
905 uint8_t* pDst = (uint8_t*) pBuffer;
914 if (
GetPos() <= loopEnd) {
922 if (!pPlaybackState->
reverse) {
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;
932 }
while (samplestoread && readsamples);
942 file_offset_t swapareastart = totalreadsamples;
944 file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
945 file_offset_t reverseplaybackend =
GetPos() - samplestoreadinloop;
947 SetPos(reverseplaybackend);
951 readsamples =
Read(&pDst[totalreadsamples * this->
FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
952 samplestoreadinloop -= readsamples;
953 samplestoread -= readsamples;
954 totalreadsamples += readsamples;
955 }
while (samplestoreadinloop && readsamples);
957 SetPos(reverseplaybackend);
959 if (reverseplaybackend == loop.
LoopStart) {
961 pPlaybackState->
reverse =
false;
965 if (totalreadsamples > swapareastart)
966 SwapMemoryArea(&pDst[swapareastart * this->
FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
968 }
while (samplestoread && readsamples);
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;
983 }
while (samplestoread && readsamples);
985 if (!samplestoread)
break;
993 file_offset_t swapareastart = totalreadsamples;
997 file_offset_t reverseplaybackend = loop.
LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.
LoopLength);
999 SetPos(reverseplaybackend);
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) {
1014 }
while (samplestoreadinloop && readsamples);
1016 SetPos(reverseplaybackend);
1019 SwapMemoryArea(&pDst[swapareastart * this->
FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
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) {
1035 }
while (samplestoread && readsamples);
1043 if (samplestoread)
do {
1044 readsamples =
Read(&pDst[totalreadsamples * this->
FrameSize], samplestoread, pExternalDecompressionBuffer);
1045 samplestoread -= readsamples;
1046 totalreadsamples += readsamples;
1047 }
while (readsamples && samplestoread);
1052 return totalreadsamples;
1078 if (SampleCount == 0)
return 0;
1085 return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1086 : pCkData->Read(pBuffer, SampleCount, 2);
1092 file_offset_t assumedsize = GuessSize(SampleCount),
1094 remainingsamples = SampleCount,
1095 copysamples, skipsamples,
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);
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);
1114 while (remainingsamples && remainingbytes) {
1116 file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1118 int mode_l = *pSrc++, mode_r = 0;
1122 framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1123 rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1124 nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1125 if (remainingbytes < framebytes) {
1127 if (mode_l == 4 && (framesamples & 1)) {
1128 rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1131 rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1136 framebytes = bytesPerFrame[mode_l] + 1;
1137 nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1138 if (remainingbytes < framebytes) {
1144 if (currentframeoffset + remainingsamples >= framesamples) {
1145 if (currentframeoffset <= framesamples) {
1146 copysamples = framesamples - currentframeoffset;
1147 skipsamples = currentframeoffset;
1151 skipsamples = framesamples;
1158 copysamples = remainingsamples;
1159 skipsamples = currentframeoffset;
1160 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1161 this->
FrameOffset = currentframeoffset + copysamples;
1163 remainingsamples -= copysamples;
1165 if (remainingbytes > framebytes) {
1166 remainingbytes -= framebytes;
1167 if (remainingsamples == 0 &&
1168 currentframeoffset + copysamples == framesamples) {
1173 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1176 else remainingbytes = 0;
1178 currentframeoffset -= skipsamples;
1180 if (copysamples == 0) {
1185 const unsigned char*
const param_l = pSrc;
1187 if (mode_l != 2) pSrc += 12;
1190 const unsigned char*
const param_r = pSrc;
1191 if (mode_r != 2) pSrc += 12;
1193 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1195 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1197 pDst24 += copysamples * 6;
1200 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1202 pDst24 += copysamples * 3;
1206 if (mode_l) pSrc += 4;
1210 const unsigned char*
const param_r = pSrc;
1211 if (mode_r) pSrc += 4;
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;
1221 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1222 pDst += copysamples;
1225 pSrc += nextFrameOffset;
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;
1238 this->
SamplePos += (SampleCount - remainingsamples);
1240 return (SampleCount - remainingsamples);
1271 if (pCkData->GetPos() == 0) {
1274 if (
GetSize() < SampleCount)
throw Exception(
"Could not write sample data, current sample size to small");
1279 res =
Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1280 : pCkData->Write(pBuffer, SampleCount, 2);
1287 swapBytesOfWords(pBuffer, res *
Channels, 2);
1289 __calculateCRC((
unsigned char *)pBuffer, SampleCount *
FrameSize,
crc);
1293 swapBytesOfWords(pBuffer, res *
Channels, 2);
1298 if (pCkData->GetPos() == std::min(pCkData->GetSize(), pCkData->GetNewSize())) {
1300 File* pFile =
static_cast<File*
>(GetParent());
1324 const double worstCaseHeaderOverhead =
1325 (256.0 + 12.0 + 2.0 ) / 256.0;
1326 result.
Size = (file_offset_t) (
double(MaxReadSize) * 3.0 * 2.0 * worstCaseHeaderOverhead);
1340 if (DecompressionBuffer.
Size && DecompressionBuffer.
pStart) {
1341 delete[] (int8_t*) DecompressionBuffer.
pStart;
1342 DecompressionBuffer.
pStart = NULL;
1343 DecompressionBuffer.
Size = 0;
1403 uint32_t
crc = CalculateWaveDataChecksum();
1404 if (pActually) *pActually =
crc;
1405 return crc == this->crc;
1408 uint32_t Sample::CalculateWaveDataChecksum() {
1409 const size_t sz = 20*1024;
1410 std::vector<uint8_t> buffer(sz);
1418 file_offset_t nRead =
Read(&buffer[0], n);
1419 if (nRead <= 0)
break;
1425 swapBytesOfWords(&buffer[0], nRead *
Channels, 2);
1431 swapBytesOfWords(&buffer[0], nRead *
Channels, 2);
1454 size_t DimensionRegion::Instances = 0;
1455 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1457 DimensionRegion::DimensionRegion(
Region* pParent,
RIFF::List* _3ewl) :
DLS::Sampler(_3ewl) {
1463 if (_3ewl->
GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1464 else memset(&Crossfade, 0, 4);
1466 if (!pVelocityTables) pVelocityTables =
new VelocityTableMap;
1473 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
1474 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
1483 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
1484 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
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());
1505 EG2Release = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
1508 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->
ReadInt32());
1512 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1513 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1517 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1518 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1521 uint8_t velocityresponse = _3ewa->
ReadUint8();
1522 if (velocityresponse < 5) {
1524 VelocityResponseDepth = velocityresponse;
1525 }
else if (velocityresponse < 10) {
1527 VelocityResponseDepth = velocityresponse - 5;
1528 }
else if (velocityresponse < 15) {
1530 VelocityResponseDepth = velocityresponse - 10;
1533 VelocityResponseDepth = 0;
1535 uint8_t releasevelocityresponse = _3ewa->
ReadUint8();
1536 if (releasevelocityresponse < 5) {
1538 ReleaseVelocityResponseDepth = releasevelocityresponse;
1539 }
else if (releasevelocityresponse < 10) {
1541 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1542 }
else if (releasevelocityresponse < 15) {
1544 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1547 ReleaseVelocityResponseDepth = 0;
1549 VelocityResponseCurveScaling = _3ewa->
ReadUint8();
1550 AttenuationControllerThreshold = _3ewa->
ReadInt8();
1552 SampleStartOffset = (uint16_t) _3ewa->
ReadInt16();
1554 uint8_t pitchTrackDimensionBypass = _3ewa->
ReadInt8();
1555 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1560 Pan = (pan < 64) ? pan : -((int)pan - 63);
1561 SelfMask = _3ewa->
ReadInt8() & 0x01;
1564 LFO3Controller =
static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07);
1565 LFO3Sync = lfo3ctrl & 0x20;
1566 InvertAttenuationController = lfo3ctrl & 0x80;
1567 AttenuationController = DecodeLeverageController(
static_cast<_lev_ctrl_t
>(_3ewa->
ReadUint8()));
1569 LFO2Controller =
static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07);
1570 LFO2FlipPhase = lfo2ctrl & 0x80;
1571 LFO2Sync = lfo2ctrl & 0x20;
1572 bool extResonanceCtrl = lfo2ctrl & 0x40;
1574 LFO1Controller =
static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07);
1575 LFO1FlipPhase = lfo1ctrl & 0x80;
1576 LFO1Sync = lfo1ctrl & 0x40;
1577 VCFResonanceController = (extResonanceCtrl) ?
static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1580 EG3Depth = (eg3depth <= 1200) ? eg3depth
1581 : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1);
1584 uint8_t regoptions = _3ewa->
ReadUint8();
1585 MSDecode = regoptions & 0x01;
1586 SustainDefeat = regoptions & 0x02;
1588 VelocityUpperLimit = _3ewa->
ReadInt8();
1591 ReleaseTriggerDecay = _3ewa->
ReadUint8();
1596 VCFEnabled = vcfcutoff & 0x80;
1597 VCFCutoff = vcfcutoff & 0x7f;
1599 uint8_t vcfvelscale = _3ewa->
ReadUint8();
1600 VCFCutoffControllerInvert = vcfvelscale & 0x80;
1601 VCFVelocityScale = vcfvelscale & 0x7f;
1603 uint8_t vcfresonance = _3ewa->
ReadUint8();
1604 VCFResonance = vcfresonance & 0x7f;
1605 VCFResonanceDynamic = !(vcfresonance & 0x80);
1606 uint8_t vcfbreakpoint = _3ewa->
ReadUint8();
1607 VCFKeyboardTracking = vcfbreakpoint & 0x80;
1608 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f;
1609 uint8_t vcfvelocity = _3ewa->
ReadUint8();
1610 VCFVelocityDynamicRange = vcfvelocity % 5;
1611 VCFVelocityCurve =
static_cast<curve_type_t>(vcfvelocity / 5);
1614 if (lfo3ctrl & 0x40)
1618 _3ewa->Read(DimensionUpperLimits, 1, 8);
1620 memset(DimensionUpperLimits, 0, 8);
1624 LFO3Frequency = 1.0;
1626 LFO1InternalDepth = 0;
1627 LFO3InternalDepth = 0;
1628 LFO1ControlDepth = 0;
1629 LFO3ControlDepth = 0;
1635 EG1Controller.controller_number = 0;
1636 EG1ControllerInvert =
false;
1637 EG1ControllerAttackInfluence = 0;
1638 EG1ControllerDecayInfluence = 0;
1639 EG1ControllerReleaseInfluence = 0;
1641 EG2Controller.controller_number = 0;
1642 EG2ControllerInvert =
false;
1643 EG2ControllerAttackInfluence = 0;
1644 EG2ControllerDecayInfluence = 0;
1645 EG2ControllerReleaseInfluence = 0;
1646 LFO1Frequency = 1.0;
1651 LFO2ControlDepth = 0;
1652 LFO2Frequency = 1.0;
1653 LFO2InternalDepth = 0;
1655 EG1InfiniteSustain =
true;
1658 EG2InfiniteSustain =
true;
1661 VelocityResponseDepth = 3;
1663 ReleaseVelocityResponseDepth = 3;
1664 VelocityResponseCurveScaling = 32;
1665 AttenuationControllerThreshold = 0;
1666 SampleStartOffset = 0;
1673 InvertAttenuationController =
false;
1675 AttenuationController.controller_number = 0;
1677 LFO2FlipPhase =
false;
1680 LFO1FlipPhase =
false;
1686 SustainDefeat =
false;
1687 VelocityUpperLimit = 0;
1688 ReleaseTriggerDecay = 0;
1693 VCFCutoffControllerInvert =
false;
1694 VCFVelocityScale = 0;
1696 VCFResonanceDynamic =
false;
1697 VCFKeyboardTracking =
false;
1698 VCFKeyboardTrackingBreakpoint = 0;
1699 VCFVelocityDynamicRange = 0x04;
1702 memset(DimensionUpperLimits, 127, 8);
1706 RIFF::Chunk* lsde = _3ewl->
GetSubChunk(CHUNK_ID_LSDE);
1710 eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };
1711 for (
int i = 0; i < 2; ++i) {
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);
1721 if (lsde && lsde->
GetSize() > 3) {
1724 SustainReleaseTrigger =
static_cast<sust_rel_trg_t>(
byte & 0x03);
1725 NoNoteOffReleaseTrigger =
byte >> 7;
1728 NoNoteOffReleaseTrigger =
false;
1732 if (lsde && lsde->
GetSize() > 4) {
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;
1750 LFO3FlipPhase =
false;
1753 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1754 VelocityResponseDepth,
1755 VelocityResponseCurveScaling);
1757 pVelocityReleaseTable = GetReleaseVelocityTable(
1758 ReleaseVelocityResponseCurve,
1759 ReleaseVelocityResponseDepth
1762 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1763 VCFVelocityDynamicRange,
1765 VCFCutoffController);
1767 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1775 DimensionRegion::DimensionRegion(RIFF::List* _3ewl,
const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1779 pParentList = _3ewl;
1782 if (src.VelocityTable) {
1783 VelocityTable = new uint8_t[128];
1784 for (int k = 0 ; k < 128 ; k++)
1785 VelocityTable[k] = src.VelocityTable[k];
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];
1832 pRegion = pOriginalRegion;
1836 if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1840 if (mSamples && mSamples->count(orig->
pSample)) {
1847 for (
int k = 0 ; k < 128 ; k++)
1962 DLS::Sampler::SetGain(gain);
1979 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1981 pData[12] = Crossfade.in_start;
1982 pData[13] = Crossfade.in_end;
1983 pData[14] = Crossfade.out_start;
1984 pData[15] = Crossfade.out_end;
1987 RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1989 File* pFile = (
File*) GetParent()->GetParent()->GetParent();
1991 _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, versiongt2 ? 148 : 140);
1997 const uint32_t chunksize = (uint32_t) _3ewa->
GetNewSize();
1998 store32(&pData[0], chunksize);
2000 const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(
LFO3Frequency);
2001 store32(&pData[4], lfo3freq);
2003 const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(
EG3Attack);
2004 store32(&pData[8], eg3attack);
2022 const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(
EG1Attack);
2023 store32(&pData[28], eg1attack);
2025 const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(
EG1Decay1);
2026 store32(&pData[32], eg1decay1);
2032 const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(
EG1Release);
2033 store32(&pData[40], eg1release);
2035 const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(
EG1Controller);
2038 const uint8_t eg1ctrloptions =
2043 pData[45] = eg1ctrloptions;
2045 const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(
EG2Controller);
2048 const uint8_t eg2ctrloptions =
2053 pData[47] = eg2ctrloptions;
2055 const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(
LFO1Frequency);
2056 store32(&pData[48], lfo1freq);
2058 const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(
EG2Attack);
2059 store32(&pData[52], eg2attack);
2061 const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(
EG2Decay1);
2062 store32(&pData[56], eg2decay1);
2068 const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(
EG2Release);
2069 store32(&pData[64], eg2release);
2075 const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(
LFO2Frequency);
2076 store32(&pData[72], lfo2freq);
2083 store32(&pData[80], eg1decay2);
2090 store32(&pData[88], eg2decay2);
2103 velocityresponse += 5;
2106 velocityresponse += 10;
2110 throw Exception(
"Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
2112 pData[96] = velocityresponse;
2122 releasevelocityresponse += 5;
2125 releasevelocityresponse += 10;
2129 throw Exception(
"Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
2131 pData[97] = releasevelocityresponse;
2145 uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(
PitchTrack);
2148 pitchTrackDimensionBypass |= 0x10;
2151 pitchTrackDimensionBypass |= 0x20;
2157 throw Exception(
"Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
2159 pData[108] = pitchTrackDimensionBypass;
2162 const uint8_t pan = (
Pan >= 0) ?
Pan : ((-
Pan) + 63);
2165 const uint8_t selfmask = (
SelfMask) ? 0x01 : 0x00;
2166 pData[110] = selfmask;
2175 pData[112] = lfo3ctrl;
2179 pData[113] = attenctl;
2186 pData[114] = lfo2ctrl;
2195 pData[115] = lfo1ctrl;
2199 : uint16_t(((-
EG3Depth) - 1) ^ 0xfff);
2200 store16(&pData[116], eg3depth);
2205 pData[120] = channeloffset;
2208 uint8_t regoptions = 0;
2211 pData[121] = regoptions;
2224 const uint8_t eg1hold = (
EG1Hold) ? 0x80 : 0x00;
2225 pData[131] = eg1hold;
2227 const uint8_t vcfcutoff = (
VCFEnabled ? 0x80 : 0x00) |
2229 pData[132] = vcfcutoff;
2235 pData[134] = vcfvelscale;
2241 pData[136] = vcfresonance;
2245 pData[137] = vcfbreakpoint;
2249 pData[138] = vcfvelocity;
2252 pData[139] = vcftype;
2254 if (chunksize >= 148) {
2260 RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);
2261 const int lsdeSize =
2265 if (!lsde && UsesAnyGigFormatExtension()) {
2269 lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize);
2271 pParentList->MoveSubChunk(lsde, (
RIFF::Chunk*)NULL);
2277 unsigned char* pData = (
unsigned char*) lsde->
LoadChunkData();
2279 for (
int i = 0; i < 2; ++i) {
2282 (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) |
2284 (pEGOpts[i]->Decay2Cancel ? (1<<3) : 0) |
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);
2302 store32(&pData[24], flags);
2306 static_assert(lsdeSize == 28,
"Inconsistency in assumed 'LSDE' RIFF chunk size");
2325 bool DimensionRegion::UsesAnyGigFormatExtension()
const {
2335 double* DimensionRegion::GetReleaseVelocityTable(
curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2337 uint8_t depth = releaseVelocityResponseDepth;
2346 return GetVelocityTable(curveType, depth, 0);
2349 double* DimensionRegion::GetCutoffVelocityTable(
curve_type_t vcfVelocityCurve,
2350 uint8_t vcfVelocityDynamicRange,
2351 uint8_t vcfVelocityScale,
2355 uint8_t depth = vcfVelocityDynamicRange;
2364 return GetVelocityTable(curveType, depth,
2366 ? vcfVelocityScale : 0);
2370 double* DimensionRegion::GetVelocityTable(
curve_type_t curveType, uint8_t depth, uint8_t scaling)
2374 switch (curveType) {
2378 printf(
"Warning: Invalid depth (0x%x) for velocity curve type (0x%x).\n", depth, curveType);
2385 printf(
"Warning: Invalid depth (0x%x) for velocity curve type 'special'.\n", depth);
2392 printf(
"Warning: Unknown velocity curve type (0x%x).\n", curveType);
2400 uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2401 if (pVelocityTables->count(tableKey)) {
2402 table = (*pVelocityTables)[tableKey];
2405 table = CreateVelocityTable(curveType, depth, scaling);
2406 (*pVelocityTables)[tableKey] = table;
2411 Region* DimensionRegion::GetParent()
const {
2421 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2422 leverage_ctrl_t decodedcontroller;
2423 switch (EncodedController) {
2425 case _lev_ctrl_none:
2427 decodedcontroller.controller_number = 0;
2429 case _lev_ctrl_velocity:
2431 decodedcontroller.controller_number = 0;
2433 case _lev_ctrl_channelaftertouch:
2435 decodedcontroller.controller_number = 0;
2439 case _lev_ctrl_modwheel:
2441 decodedcontroller.controller_number = 1;
2443 case _lev_ctrl_breath:
2445 decodedcontroller.controller_number = 2;
2447 case _lev_ctrl_foot:
2449 decodedcontroller.controller_number = 4;
2451 case _lev_ctrl_effect1:
2453 decodedcontroller.controller_number = 12;
2455 case _lev_ctrl_effect2:
2457 decodedcontroller.controller_number = 13;
2459 case _lev_ctrl_genpurpose1:
2461 decodedcontroller.controller_number = 16;
2463 case _lev_ctrl_genpurpose2:
2465 decodedcontroller.controller_number = 17;
2467 case _lev_ctrl_genpurpose3:
2469 decodedcontroller.controller_number = 18;
2471 case _lev_ctrl_genpurpose4:
2473 decodedcontroller.controller_number = 19;
2475 case _lev_ctrl_portamentotime:
2477 decodedcontroller.controller_number = 5;
2479 case _lev_ctrl_sustainpedal:
2481 decodedcontroller.controller_number = 64;
2483 case _lev_ctrl_portamento:
2485 decodedcontroller.controller_number = 65;
2487 case _lev_ctrl_sostenutopedal:
2489 decodedcontroller.controller_number = 66;
2491 case _lev_ctrl_softpedal:
2493 decodedcontroller.controller_number = 67;
2495 case _lev_ctrl_genpurpose5:
2497 decodedcontroller.controller_number = 80;
2499 case _lev_ctrl_genpurpose6:
2501 decodedcontroller.controller_number = 81;
2503 case _lev_ctrl_genpurpose7:
2505 decodedcontroller.controller_number = 82;
2507 case _lev_ctrl_genpurpose8:
2509 decodedcontroller.controller_number = 83;
2511 case _lev_ctrl_effect1depth:
2513 decodedcontroller.controller_number = 91;
2515 case _lev_ctrl_effect2depth:
2517 decodedcontroller.controller_number = 92;
2519 case _lev_ctrl_effect3depth:
2521 decodedcontroller.controller_number = 93;
2523 case _lev_ctrl_effect4depth:
2525 decodedcontroller.controller_number = 94;
2527 case _lev_ctrl_effect5depth:
2529 decodedcontroller.controller_number = 95;
2535 case _lev_ctrl_CC3_EXT:
2537 decodedcontroller.controller_number = 3;
2539 case _lev_ctrl_CC6_EXT:
2541 decodedcontroller.controller_number = 6;
2543 case _lev_ctrl_CC7_EXT:
2545 decodedcontroller.controller_number = 7;
2547 case _lev_ctrl_CC8_EXT:
2549 decodedcontroller.controller_number = 8;
2551 case _lev_ctrl_CC9_EXT:
2553 decodedcontroller.controller_number = 9;
2555 case _lev_ctrl_CC10_EXT:
2557 decodedcontroller.controller_number = 10;
2559 case _lev_ctrl_CC11_EXT:
2561 decodedcontroller.controller_number = 11;
2563 case _lev_ctrl_CC14_EXT:
2565 decodedcontroller.controller_number = 14;
2567 case _lev_ctrl_CC15_EXT:
2569 decodedcontroller.controller_number = 15;
2571 case _lev_ctrl_CC20_EXT:
2573 decodedcontroller.controller_number = 20;
2575 case _lev_ctrl_CC21_EXT:
2577 decodedcontroller.controller_number = 21;
2579 case _lev_ctrl_CC22_EXT:
2581 decodedcontroller.controller_number = 22;
2583 case _lev_ctrl_CC23_EXT:
2585 decodedcontroller.controller_number = 23;
2587 case _lev_ctrl_CC24_EXT:
2589 decodedcontroller.controller_number = 24;
2591 case _lev_ctrl_CC25_EXT:
2593 decodedcontroller.controller_number = 25;
2595 case _lev_ctrl_CC26_EXT:
2597 decodedcontroller.controller_number = 26;
2599 case _lev_ctrl_CC27_EXT:
2601 decodedcontroller.controller_number = 27;
2603 case _lev_ctrl_CC28_EXT:
2605 decodedcontroller.controller_number = 28;
2607 case _lev_ctrl_CC29_EXT:
2609 decodedcontroller.controller_number = 29;
2611 case _lev_ctrl_CC30_EXT:
2613 decodedcontroller.controller_number = 30;
2615 case _lev_ctrl_CC31_EXT:
2617 decodedcontroller.controller_number = 31;
2619 case _lev_ctrl_CC68_EXT:
2621 decodedcontroller.controller_number = 68;
2623 case _lev_ctrl_CC69_EXT:
2625 decodedcontroller.controller_number = 69;
2627 case _lev_ctrl_CC70_EXT:
2629 decodedcontroller.controller_number = 70;
2631 case _lev_ctrl_CC71_EXT:
2633 decodedcontroller.controller_number = 71;
2635 case _lev_ctrl_CC72_EXT:
2637 decodedcontroller.controller_number = 72;
2639 case _lev_ctrl_CC73_EXT:
2641 decodedcontroller.controller_number = 73;
2643 case _lev_ctrl_CC74_EXT:
2645 decodedcontroller.controller_number = 74;
2647 case _lev_ctrl_CC75_EXT:
2649 decodedcontroller.controller_number = 75;
2651 case _lev_ctrl_CC76_EXT:
2653 decodedcontroller.controller_number = 76;
2655 case _lev_ctrl_CC77_EXT:
2657 decodedcontroller.controller_number = 77;
2659 case _lev_ctrl_CC78_EXT:
2661 decodedcontroller.controller_number = 78;
2663 case _lev_ctrl_CC79_EXT:
2665 decodedcontroller.controller_number = 79;
2667 case _lev_ctrl_CC84_EXT:
2669 decodedcontroller.controller_number = 84;
2671 case _lev_ctrl_CC85_EXT:
2673 decodedcontroller.controller_number = 85;
2675 case _lev_ctrl_CC86_EXT:
2677 decodedcontroller.controller_number = 86;
2679 case _lev_ctrl_CC87_EXT:
2681 decodedcontroller.controller_number = 87;
2683 case _lev_ctrl_CC89_EXT:
2685 decodedcontroller.controller_number = 89;
2687 case _lev_ctrl_CC90_EXT:
2689 decodedcontroller.controller_number = 90;
2691 case _lev_ctrl_CC96_EXT:
2693 decodedcontroller.controller_number = 96;
2695 case _lev_ctrl_CC97_EXT:
2697 decodedcontroller.controller_number = 97;
2699 case _lev_ctrl_CC102_EXT:
2701 decodedcontroller.controller_number = 102;
2703 case _lev_ctrl_CC103_EXT:
2705 decodedcontroller.controller_number = 103;
2707 case _lev_ctrl_CC104_EXT:
2709 decodedcontroller.controller_number = 104;
2711 case _lev_ctrl_CC105_EXT:
2713 decodedcontroller.controller_number = 105;
2715 case _lev_ctrl_CC106_EXT:
2717 decodedcontroller.controller_number = 106;
2719 case _lev_ctrl_CC107_EXT:
2721 decodedcontroller.controller_number = 107;
2723 case _lev_ctrl_CC108_EXT:
2725 decodedcontroller.controller_number = 108;
2727 case _lev_ctrl_CC109_EXT:
2729 decodedcontroller.controller_number = 109;
2731 case _lev_ctrl_CC110_EXT:
2733 decodedcontroller.controller_number = 110;
2735 case _lev_ctrl_CC111_EXT:
2737 decodedcontroller.controller_number = 111;
2739 case _lev_ctrl_CC112_EXT:
2741 decodedcontroller.controller_number = 112;
2743 case _lev_ctrl_CC113_EXT:
2745 decodedcontroller.controller_number = 113;
2747 case _lev_ctrl_CC114_EXT:
2749 decodedcontroller.controller_number = 114;
2751 case _lev_ctrl_CC115_EXT:
2753 decodedcontroller.controller_number = 115;
2755 case _lev_ctrl_CC116_EXT:
2757 decodedcontroller.controller_number = 116;
2759 case _lev_ctrl_CC117_EXT:
2761 decodedcontroller.controller_number = 117;
2763 case _lev_ctrl_CC118_EXT:
2765 decodedcontroller.controller_number = 118;
2767 case _lev_ctrl_CC119_EXT:
2769 decodedcontroller.controller_number = 119;
2775 decodedcontroller.controller_number = 0;
2776 printf(
"Warning: Unknown leverage controller type (0x%x).\n", EncodedController);
2779 return decodedcontroller;
2785 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(
leverage_ctrl_t DecodedController) {
2786 _lev_ctrl_t encodedcontroller;
2787 switch (DecodedController.type) {
2790 encodedcontroller = _lev_ctrl_none;
2793 encodedcontroller = _lev_ctrl_velocity;
2796 encodedcontroller = _lev_ctrl_channelaftertouch;
2801 switch (DecodedController.controller_number) {
2803 encodedcontroller = _lev_ctrl_modwheel;
2806 encodedcontroller = _lev_ctrl_breath;
2809 encodedcontroller = _lev_ctrl_foot;
2812 encodedcontroller = _lev_ctrl_effect1;
2815 encodedcontroller = _lev_ctrl_effect2;
2818 encodedcontroller = _lev_ctrl_genpurpose1;
2821 encodedcontroller = _lev_ctrl_genpurpose2;
2824 encodedcontroller = _lev_ctrl_genpurpose3;
2827 encodedcontroller = _lev_ctrl_genpurpose4;
2830 encodedcontroller = _lev_ctrl_portamentotime;
2833 encodedcontroller = _lev_ctrl_sustainpedal;
2836 encodedcontroller = _lev_ctrl_portamento;
2839 encodedcontroller = _lev_ctrl_sostenutopedal;
2842 encodedcontroller = _lev_ctrl_softpedal;
2845 encodedcontroller = _lev_ctrl_genpurpose5;
2848 encodedcontroller = _lev_ctrl_genpurpose6;
2851 encodedcontroller = _lev_ctrl_genpurpose7;
2854 encodedcontroller = _lev_ctrl_genpurpose8;
2857 encodedcontroller = _lev_ctrl_effect1depth;
2860 encodedcontroller = _lev_ctrl_effect2depth;
2863 encodedcontroller = _lev_ctrl_effect3depth;
2866 encodedcontroller = _lev_ctrl_effect4depth;
2869 encodedcontroller = _lev_ctrl_effect5depth;
2876 encodedcontroller = _lev_ctrl_CC3_EXT;
2879 encodedcontroller = _lev_ctrl_CC6_EXT;
2882 encodedcontroller = _lev_ctrl_CC7_EXT;
2885 encodedcontroller = _lev_ctrl_CC8_EXT;
2888 encodedcontroller = _lev_ctrl_CC9_EXT;
2891 encodedcontroller = _lev_ctrl_CC10_EXT;
2894 encodedcontroller = _lev_ctrl_CC11_EXT;
2897 encodedcontroller = _lev_ctrl_CC14_EXT;
2900 encodedcontroller = _lev_ctrl_CC15_EXT;
2903 encodedcontroller = _lev_ctrl_CC20_EXT;
2906 encodedcontroller = _lev_ctrl_CC21_EXT;
2909 encodedcontroller = _lev_ctrl_CC22_EXT;
2912 encodedcontroller = _lev_ctrl_CC23_EXT;
2915 encodedcontroller = _lev_ctrl_CC24_EXT;
2918 encodedcontroller = _lev_ctrl_CC25_EXT;
2921 encodedcontroller = _lev_ctrl_CC26_EXT;
2924 encodedcontroller = _lev_ctrl_CC27_EXT;
2927 encodedcontroller = _lev_ctrl_CC28_EXT;
2930 encodedcontroller = _lev_ctrl_CC29_EXT;
2933 encodedcontroller = _lev_ctrl_CC30_EXT;
2936 encodedcontroller = _lev_ctrl_CC31_EXT;
2939 encodedcontroller = _lev_ctrl_CC68_EXT;
2942 encodedcontroller = _lev_ctrl_CC69_EXT;
2945 encodedcontroller = _lev_ctrl_CC70_EXT;
2948 encodedcontroller = _lev_ctrl_CC71_EXT;
2951 encodedcontroller = _lev_ctrl_CC72_EXT;
2954 encodedcontroller = _lev_ctrl_CC73_EXT;
2957 encodedcontroller = _lev_ctrl_CC74_EXT;
2960 encodedcontroller = _lev_ctrl_CC75_EXT;
2963 encodedcontroller = _lev_ctrl_CC76_EXT;
2966 encodedcontroller = _lev_ctrl_CC77_EXT;
2969 encodedcontroller = _lev_ctrl_CC78_EXT;
2972 encodedcontroller = _lev_ctrl_CC79_EXT;
2975 encodedcontroller = _lev_ctrl_CC84_EXT;
2978 encodedcontroller = _lev_ctrl_CC85_EXT;
2981 encodedcontroller = _lev_ctrl_CC86_EXT;
2984 encodedcontroller = _lev_ctrl_CC87_EXT;
2987 encodedcontroller = _lev_ctrl_CC89_EXT;
2990 encodedcontroller = _lev_ctrl_CC90_EXT;
2993 encodedcontroller = _lev_ctrl_CC96_EXT;
2996 encodedcontroller = _lev_ctrl_CC97_EXT;
2999 encodedcontroller = _lev_ctrl_CC102_EXT;
3002 encodedcontroller = _lev_ctrl_CC103_EXT;
3005 encodedcontroller = _lev_ctrl_CC104_EXT;
3008 encodedcontroller = _lev_ctrl_CC105_EXT;
3011 encodedcontroller = _lev_ctrl_CC106_EXT;
3014 encodedcontroller = _lev_ctrl_CC107_EXT;
3017 encodedcontroller = _lev_ctrl_CC108_EXT;
3020 encodedcontroller = _lev_ctrl_CC109_EXT;
3023 encodedcontroller = _lev_ctrl_CC110_EXT;
3026 encodedcontroller = _lev_ctrl_CC111_EXT;
3029 encodedcontroller = _lev_ctrl_CC112_EXT;
3032 encodedcontroller = _lev_ctrl_CC113_EXT;
3035 encodedcontroller = _lev_ctrl_CC114_EXT;
3038 encodedcontroller = _lev_ctrl_CC115_EXT;
3041 encodedcontroller = _lev_ctrl_CC116_EXT;
3044 encodedcontroller = _lev_ctrl_CC117_EXT;
3047 encodedcontroller = _lev_ctrl_CC118_EXT;
3050 encodedcontroller = _lev_ctrl_CC119_EXT;
3054 throw gig::Exception(
"leverage controller number is not supported by the gig format");
3058 throw gig::Exception(
"Unknown leverage controller type.");
3060 return encodedcontroller;
3063 DimensionRegion::~DimensionRegion() {
3067 VelocityTableMap::iterator iter;
3068 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
3069 double* pTable = iter->second;
3070 if (pTable)
delete[] pTable;
3072 pVelocityTables->clear();
3073 delete pVelocityTables;
3074 pVelocityTables = NULL;
3091 return pVelocityAttenuationTable[MIDIKeyVelocity];
3094 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
3095 return pVelocityReleaseTable[MIDIKeyVelocity];
3098 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
3099 return pVelocityCutoffTable[MIDIKeyVelocity];
3107 pVelocityAttenuationTable =
3119 pVelocityAttenuationTable =
3131 pVelocityAttenuationTable =
3192 double* DimensionRegion::CreateVelocityTable(
curve_type_t curveType, uint8_t depth, uint8_t scaling) {
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 };
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,
3207 const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
3209 const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
3211 const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
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,
3226 const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
3227 91, 127, 127, 127 };
3229 const int*
const curves[] = { non0, non1, non2, non3, non4,
3230 lin0, lin1, lin2, lin3, lin4,
3231 spe0, spe1, spe2, spe3, spe4, spe5 };
3233 double*
const table =
new double[128];
3235 const int* curve = curves[curveType * 5 + depth];
3236 const int s = scaling == 0 ? 20 : scaling;
3239 for (
int x = 1 ; x < 128 ; x++) {
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]));
3248 if (s < 20 && y >= 0.5)
3249 y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
3266 for (
int i = 0; i < 256; i++) {
3267 pDimensionRegions[i] = NULL;
3270 File* file = (File*) GetParent()->GetParent();
3271 int dimensionBits = (file->pVersion && file->pVersion->major > 2) ? 8 : 5;
3275 if (!file->GetAutoLoad())
return;
3277 LoadDimensionRegions(rgnList);
3279 RIFF::Chunk* _3lnk = rgnList->
GetSubChunk(CHUNK_ID_3LNK);
3284 for (
int i = 0; i < dimensionBits; i++) {
3292 pDimensionDefinitions[i].bits = 0;
3293 pDimensionDefinitions[i].zones = 0;
3295 pDimensionDefinitions[i].zone_size = 0;
3298 pDimensionDefinitions[i].dimension = dimension;
3299 pDimensionDefinitions[i].bits = bits;
3300 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits;
3301 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
3302 pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
3306 if (dimension ==
dimension_layer) Layers = pDimensionDefinitions[i].zones;
3308 _3lnk->
SetPos(3, RIFF::stream_curpos);
3310 for (
int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
3314 UpdateVelocityTable();
3317 if (file->pVersion && file->pVersion->major > 2)
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);
3332 DimensionRegions = 0;
3333 for (
int i = 0 ; i < 8 ; i++) {
3335 pDimensionDefinitions[i].bits = 0;
3336 pDimensionDefinitions[i].zones = 0;
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;
3375 File* pFile = (
File*) GetParent()->GetParent();
3377 const int iMaxDimensions = versiongt2 ? 8 : 5;
3378 const int iMaxDimensionRegions = versiongt2 ? 256 : 32;
3381 RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3383 const int _3lnkChunkSize = versiongt2 ? 1092 : 172;
3384 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3388 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (
RIFF::Chunk*)NULL);
3395 for (
int i = 0; i < iMaxDimensions; i++) {
3407 const int iWavePoolOffset = versiongt2 ? 68 : 44;
3408 for (uint i = 0; i < iMaxDimensionRegions; i++) {
3409 int iWaveIndex = -1;
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) {
3421 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3431 if (versiongt2 && !UsesAnyGigFormatExtension()) {
3434 if (!_3dnm) _3dnm = pCkRegion->
AddSubList(LIST_TYPE_3DNM);
3437 RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3438 if (!_3ddp) _3ddp = pCkRegion->AddSubChunk(CHUNK_ID_3DDP, 16);
3440 for (
int i = 0; i < 16; i += 4) {
3441 store32(&pData[i], 0xFFFFFFFF);
3445 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3DNM), (
RIFF::Chunk*)NULL);
3446 pCkRegion->MoveSubChunk(pCkRegion->GetSubChunk(CHUNK_ID_3DDP), (
RIFF::Chunk*)NULL);
3453 RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3454 if (_3ddp) pCkRegion->DeleteSubChunk(_3ddp);
3458 void Region::LoadDimensionRegions(
RIFF::List* rgn) {
3461 int dimensionRegionNr = 0;
3468 dimensionRegionNr++;
3471 if (dimensionRegionNr == 0)
throw gig::Exception(
"No dimension region found.");
3482 void Region::UpdateVelocityTable() {
3491 if (veldim == -1)
return;
3508 table =
new uint8_t[128];
3512 int velocityZone = 0;
3514 for (
int k = i ; k < end ; k += step) {
3516 for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3520 for (
int k = i ; k < end ; k += step) {
3522 for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3537 if (j == veldim) i += skipveldim;
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");
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");
3583 File* file = (
File*) GetParent()->GetParent();
3584 const int iMaxDimensions = (file->
pVersion && file->
pVersion->major > 2) ? 8 : 5;
3586 throw gig::Exception(
"Could not add new dimension, max. amount of " + ToString(iMaxDimensions) +
" dimensions already reached");
3588 int iCurrentBits = 0;
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");
3599 throw gig::Exception(
"Could not add new dimension, there is already a dimension of the same type");
3606 for (
int i = 0 ; i < pos ; i++)
3611 for (
int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3632 for (
int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3633 for (
int k = 0 ; k < (1 << bitpos) ; k++) {
3636 for (
int j = 1 ; j < (1 << pDimDef->
bits) ; j++) {
3637 for (
int k = 0 ; k < (1 << bitpos) ; k++) {
3639 if (moveTo) _3prg->
MoveSubChunk(pNewDimRgnListChunk, moveTo);
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++) {
3658 (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3667 UpdateVelocityTable();
3683 int iDimensionNr = -1;
3690 if (iDimensionNr < 0)
throw gig::Exception(
"Invalid dimension_def_t pointer");
3694 for (
int i = 0; i < iDimensionNr; i++)
3699 for (
int i = iDimensionNr + 1; i <
Dimensions; i++)
3706 for (
int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3708 for (
int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3710 iObsoleteBit << iLowerBits |
3723 for (
int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3725 if (iFrom <= iTo) iFrom = iTo + 1;
3737 for (
int i = iDimensionNr + 1; i <
Dimensions; i++) {
3744 for (
int i = iDimensionNr + 1; i <
Dimensions; i++) {
3773 throw gig::Exception(
"Could not delete dimension zone, because there is no dimension at all.");
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.");
3782 const int newZoneSize = oldDef->
zones - 1;
3790 Instrument* instr =
static_cast<Instrument*
>(GetParent());
3791 RIFF::List* pCkInstrument = instr->pCkInstrument;
3793 if (!lrgn) lrgn = pCkInstrument->
AddSubList(LIST_TYPE_LRGN);
3795 tempRgn =
new Region(instr, rgn);
3807 def.
zones = newZoneSize;
3815 throw gig::Exception(
"Unexpected internal failure resolving dimension in DeleteDimensionZone() [this is a bug].");
3819 int tempReducedDimensionIndex = -1;
3820 for (
int d = 0; d < tempRgn->
Dimensions; ++d) {
3822 tempReducedDimensionIndex = d;
3828 for (
int iDst = 0; iDst < 256; ++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) {
3836 (iDst >> baseBits) & ((1 << dstBits) - 1);
3837 baseBits += dstBits;
3840 isValidZone =
false;
3844 if (!isValidZone)
continue;
3847 const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3848 if (dimCase[type] >= zone) dimCase[type]++;
3865 std::vector<dimension_def_t> oldDefs;
3870 for (
int i = 0; i < oldDefs.size(); ++i) {
3877 for (
int iSrc = 0; iSrc < 256; ++iSrc) {
3879 if (!srcDimRgn)
continue;
3880 std::map<dimension_t,int> dimCase;
3881 for (
int d = 0, baseBits = 0; d < tempRgn->
Dimensions; ++d) {
3884 (iSrc >> baseBits) & ((1 << srcBits) - 1);
3885 baseBits += srcBits;
3890 if (!dstDimRgn)
continue;
3898 UpdateVelocityTable();
3917 throw gig::Exception(
"Could not split dimension zone, because there is no dimension at all.");
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.");
3924 const int newZoneSize = oldDef->
zones + 1;
3932 Instrument* instr =
static_cast<Instrument*
>(GetParent());
3933 RIFF::List* pCkInstrument = instr->pCkInstrument;
3935 if (!lrgn) lrgn = pCkInstrument->
AddSubList(LIST_TYPE_LRGN);
3937 tempRgn =
new Region(instr, rgn);
3949 def.
zones = newZoneSize;
3950 if ((1 << oldDef->
bits) < newZoneSize) def.
bits++;
3957 throw gig::Exception(
"Unexpected internal failure resolving dimension in SplitDimensionZone() [this is a bug].");
3961 int tempIncreasedDimensionIndex = -1;
3962 for (
int d = 0; d < tempRgn->
Dimensions; ++d) {
3964 tempIncreasedDimensionIndex = d;
3970 for (
int iSrc = 0; iSrc < 256; ++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) {
3978 (iSrc >> baseBits) & ((1 << srcBits) - 1);
3981 isValidZone =
false;
3984 baseBits += srcBits;
3986 if (!isValidZone)
continue;
3989 if (dimCase[type] > zone) dimCase[type]++;
3995 if (dimCase[type] == zone) {
4002 std::map<dimension_t,int> lowerCase = dimCase;
4024 std::vector<dimension_def_t> oldDefs;
4029 for (
int i = 0; i < oldDefs.size(); ++i) {
4036 for (
int iSrc = 0; iSrc < 256; ++iSrc) {
4038 if (!srcDimRgn)
continue;
4039 std::map<dimension_t,int> dimCase;
4040 for (
int d = 0, baseBits = 0; d < tempRgn->
Dimensions; ++d) {
4043 (iSrc >> baseBits) & ((1 << srcBits) - 1);
4044 baseBits += srcBits;
4049 if (!dstDimRgn)
continue;
4057 UpdateVelocityTable();
4075 if (oldType == newType)
return;
4078 throw gig::Exception(
"No dimension with provided old dimension type exists on this region");
4080 throw gig::Exception(
"Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
4082 throw gig::Exception(
"There is already a dimension with requested new dimension type on this region");
4084 def->
split_type = __resolveSplitType(newType);
4088 uint8_t bits[8] = {};
4089 for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
4090 it != DimCase.end(); ++it)
4094 bits[d] = it->second;
4095 goto nextDimCaseSlice;
4122 for (
int i = 0; i < 256; i++) {
4162 if (DimValues[i] <=
pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i])
break;
4171 bits = DimValues[i] & limiter_mask;
4174 dimregidx |= bits << bitpos;
4179 if (!dimreg)
return NULL;
4188 dimregidx |= (bits & limiter_mask) << velbitpos;
4194 int Region::GetDimensionRegionIndexByValue(
const uint DimValues[8]) {
4211 if (DimValues[i] <=
pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i])
break;
4220 bits = DimValues[i] & limiter_mask;
4223 dimregidx |= bits << bitpos;
4229 if (!dimreg)
return -1;
4232 if (dimreg->VelocityTable)
4233 bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4238 dimregidx |= (bits & limiter_mask) << velbitpos;
4274 if (pSample)
return static_cast<gig::Sample*
>(pSample);
4275 else return static_cast<gig::Sample*
>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
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;
4286 uint64_t soughtoffset =
4287 uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4288 uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4293 if (sample->ullWavePoolOffset == soughtoffset)
4298 file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4299 file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4301 for (Sample* sample = file->
GetSample(i, pProgress); sample;
4304 if (sample->ullWavePoolOffset == soughtoffset &&
4305 sample->FileNo == soughtfileno)
return sample;
4335 if (mSamples && mSamples->count((
gig::Sample*)orig->pSample)) {
4336 pSample = mSamples->find((
gig::Sample*)orig->pSample)->second;
4350 for (
int i = 0; i < 256; i++) {
4374 bool Region::UsesAnyGigFormatExtension()
const {
4375 for (
int i = 0; i < 256; i++) {
4388 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
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();
4399 pTriggers[i].NoteOff = _3ewg->
ReadUint8();
4400 pTriggers[i].Velocity = _3ewg->
ReadUint8();
4401 pTriggers[i].OverridePedal = _3ewg->
ReadUint8();
4406 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4407 ControllerNumber(0),
4411 void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData)
const {
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;
4427 MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4446 MidiRuleLegato::MidiRuleLegato() :
4448 BypassUseController(false),
4450 BypassController(1),
4453 ReleaseTriggerKey(0),
4460 void MidiRuleLegato::UpdateChunks(uint8_t* pData)
const {
4476 MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4482 Selector = (flags & 2) ? selector_controller :
4483 (flags & 1) ? selector_key_switch : selector_none;
4496 for (
int i = 0 ; i < n ; i++) {
4501 for (
int i = 0 ; i < n ; i++) {
4508 MidiRuleAlternator::MidiRuleAlternator() :
4511 Selector(selector_none),
4516 PlayRange.low = PlayRange.high = 0;
4517 KeySwitchRange.low = KeySwitchRange.high = 0;
4520 void MidiRuleAlternator::UpdateChunks(uint8_t* pData)
const {
4525 (
Selector == selector_controller ? 2 :
4526 (
Selector == selector_key_switch ? 1 : 0));
4535 char* str =
reinterpret_cast<char*
>(pData);
4538 for (
int i = 0 ; i < n ; i++, pos += 32) {
4544 for (
int i = 0 ; i < n ; i++, pos += 49) {
4545 strncpy(&str[pos],
pPatterns[i].Name.c_str(), 16);
4547 memcpy(&pData[pos + 16], &(
pPatterns[i][0]), 32);
4554 Script::Script(
ScriptGroup* group, RIFF::Chunk* ckScri) {
4568 Name.resize(nameSize,
' ');
4569 for (
int i = 0; i < nameSize; ++i)
4572 if (headerSize >= 6*
sizeof(int32_t) + nameSize + 16) {
4573 for (uint i = 0; i < 16; ++i) {
4580 ckScri->
SetPos(
sizeof(int32_t) + headerSize);
4582 uint32_t scriptSize = uint32_t(ckScri->
GetSize() - ckScri->
GetPos());
4583 data.resize(scriptSize);
4584 for (
int i = 0; i < scriptSize; ++i)
4592 Name =
"Unnamed Script";
4605 if (data.empty())
return s;
4606 s.resize(data.size(),
' ');
4607 memcpy(&s[0], &data[0], data.size());
4618 data.resize(text.size());
4619 if (text.empty())
return;
4620 memcpy(&data[0], &text[0], text.size());
4647 __calculateCRC(&data[0], data.size(), crc);
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);
4655 uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4657 store32(&pData[pos], uint32_t(6*
sizeof(int32_t) +
Name.size() + 16));
4658 pos +=
sizeof(int32_t);
4660 pos +=
sizeof(int32_t);
4662 pos +=
sizeof(int32_t);
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];
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];
4710 if (this->pGroup == pGroup)
return;
4712 pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4713 this->pGroup = pGroup;
4742 void Script::RemoveAllScriptReferences() {
4743 File* pFile = pGroup->pFile;
4753 ScriptGroup::ScriptGroup(
File* file, RIFF::List* lstRTIS) {
4758 RIFF::Chunk* ckName = lstRTIS->
GetSubChunk(CHUNK_ID_LSNM);
4759 ::LoadString(ckName,
Name);
4761 Name =
"Default Group";
4765 ScriptGroup::~ScriptGroup() {
4767 std::vector<Script*>::iterator iter = pScripts->begin();
4768 std::vector<Script*>::iterator end = pScripts->end();
4769 while (iter != end) {
4801 pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4804 ::SaveString(CHUNK_ID_LSNM, NULL, pList,
Name, String(
"Unnamed Group"),
true, 64);
4806 for (std::vector<Script*>::iterator it = pScripts->begin();
4807 it != pScripts->end(); ++it)
4809 (*it)->UpdateChunks(pProgress);
4822 if (!pScripts) LoadScripts();
4823 if (index >= pScripts->size())
return NULL;
4824 return (*pScripts)[index];
4839 if (!pScripts) LoadScripts();
4840 Script* pScript =
new Script(
this, NULL);
4841 pScripts->push_back(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)
4868 void ScriptGroup::LoadScripts() {
4869 if (pScripts)
return;
4870 pScripts =
new std::vector<Script*>;
4877 if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4878 pScripts->push_back(
new Script(
this, ck));
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 },
4892 pInfo->SetFixedStringLengths(fixedStringLengths);
4895 for (
int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4900 PianoReleaseMode =
false;
4901 DimensionKeyRange.low = 0;
4902 DimensionKeyRange.high = 0;
4903 pMidiRules =
new MidiRule*[3];
4904 pMidiRules[0] = NULL;
4908 RIFF::List* lart = insList->
GetSubList(LIST_TYPE_LART);
4910 RIFF::Chunk* _3ewg = lart->
GetSubChunk(CHUNK_ID_3EWG);
4918 uint8_t dimkeystart = _3ewg->
ReadUint8();
4919 PianoReleaseMode = dimkeystart & 0x01;
4920 DimensionKeyRange.low = dimkeystart >> 1;
4921 DimensionKeyRange.high = _3ewg->
ReadUint8();
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);
4938 pMidiRules[i++] =
new MidiRuleUnknown;
4941 else if (id1 != 0 || id2 != 0) {
4942 pMidiRules[i++] =
new MidiRuleUnknown;
4946 pMidiRules[i] = NULL;
4951 if (pFile->GetAutoLoad()) {
4952 if (!pRegions) pRegions = new RegionList;
4953 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4956 for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn;
4957 rgn = lrgn->GetSubListAt(++i))
4959 if (rgn->GetListType() == LIST_TYPE_RGN) {
4961 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4962 pRegions->push_back(new Region(this, rgn));
4966 UpdateRegionKeyTable();
4971 RIFF::List* lst3LS = insList->
GetSubList(LIST_TYPE_3LS);
4974 RIFF::Chunk* ckSCSL = lst3LS->
GetSubChunk(CHUNK_ID_SCSL);
4982 ckSCSL->
SetPos(headerSize);
4983 int unknownSpace = slotSize - 2*
sizeof(uint32_t);
4984 for (
int i = 0; i < slotCount; ++i) {
4985 _ScriptPooolEntry e;
4988 if (unknownSpace) ckSCSL->
SetPos(unknownSpace, RIFF::stream_curpos);
4989 scriptPoolFileOffsets.push_back(e);
4995 RIFF::Chunk* ckSCPV = lst3LS->
GetSubChunk(CHUNK_ID_SCPV);
5000 for (
int iScript = 0; iScript < nScripts; ++iScript) {
5002 for (
int i = 0; i < 16; ++i)
5007 for (
int iVar = 0; iVar < nVars; ++iVar) {
5017 for (
int i = 0; i < len; ++i)
5020 for (
int i = 0; i < len; ++i)
5023 scriptVars[uuid][slot][name] = value;
5027 ckSCPV->
SetPos(pos + blobSize);
5034 __notify_progress(pProgress, 1.0f);
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) {
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;
5052 for (
int i = 0 ; pMidiRules[i] ; i++) {
5053 delete pMidiRules[i];
5055 delete[] pMidiRules;
5056 if (pScriptRefs)
delete pScriptRefs;
5075 RegionList::iterator iter = pRegions->begin();
5076 RegionList::iterator end = pRegions->end();
5077 for (; iter != end; ++iter)
5078 (*iter)->UpdateChunks(pProgress);
5083 if (!lart) lart = pCkInstrument->
AddSubList(LIST_TYPE_LART);
5087 File* pFile = (File*) GetParent();
5096 store16(&pData[0], EffectSend);
5100 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
5102 pData[10] = dimkeystart;
5105 if (pMidiRules[0] == 0 && _3ewg->
GetSize() >= 34) {
5109 for (
int i = 0 ; pMidiRules[i] ; i++) {
5110 pMidiRules[i]->UpdateChunks(pData);
5121 if (!lst3LS) lst3LS = pCkInstrument->
AddSubList(LIST_TYPE_3LS);
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;
5129 if (!ckSCSL) ckSCSL = lst3LS->
AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
5130 else ckSCSL->
Resize(totalChunkSize);
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) {
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);
5158 _VarsByScript vars = stripScriptVars();
5159 if (!vars.empty()) {
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();
5179 if (!ckSCPV) ckSCPV = lst3LS->
AddSubChunk(CHUNK_ID_SCPV, totalChunkSize);
5180 else ckSCPV->
Resize(totalChunkSize);
5185 store32(&pData[pos], (uint32_t) totalScriptsOverridden);
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];
5192 store32(&pData[pos], (uint32_t) slot.first);
5194 store32(&pData[pos], (uint32_t) 0);
5196 store32(&pData[pos], (uint32_t) slot.second.size());
5198 for (
const auto& var : slot.second) {
5201 store16(&pData[pos], 2 + var.first.size() + 2 + var.second.size());
5203 store16(&pData[pos], var.first.size());
5205 for (
int i = 0; i < var.first.size(); ++i)
5206 pData[pos++] = var.first[i];
5207 store16(&pData[pos], var.second.size());
5209 for (
int i = 0; i < var.second.size(); ++i)
5210 pData[pos++] = var.second[i];
5227 void Instrument::UpdateScriptFileOffsets() {
5229 if (pScriptRefs && pScriptRefs->size() > 0) {
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() -
5243 ckSCSL->
SetPos(
sizeof(uint32_t), RIFF::stream_curpos);
5256 if (!pRegions || pRegions->empty() || Key > 127)
return NULL;
5277 if (!pRegions)
return NULL;
5278 if (pos >= pRegions->size())
return NULL;
5279 return static_cast<gig::Region*
>( (*pRegions)[pos] );
5292 if (!pRegions)
return NULL;
5293 RegionsIterator = pRegions->begin();
5294 return static_cast<gig::Region*
>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
5308 if (!pRegions)
return NULL;
5310 return static_cast<gig::Region*
>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
5313 Region* Instrument::AddRegion() {
5316 if (!lrgn) lrgn = pCkInstrument->
AddSubList(LIST_TYPE_LRGN);
5319 const size_t idxIt = RegionsIterator - pRegions->begin();
5320 pRegions->push_back(pNewRegion);
5321 RegionsIterator = pRegions->begin() + std::min(idxIt, pRegions->size());
5322 Regions = (uint32_t) pRegions->size();
5324 UpdateRegionKeyTable();
5329 void Instrument::DeleteRegion(Region* pRegion) {
5330 if (!pRegions)
return;
5331 DLS::Instrument::DeleteRegion((
DLS::Region*) pRegion);
5333 UpdateRegionKeyTable();
5365 if (dst && GetParent() != dst->GetParent())
5367 "gig::Instrument::MoveTo() can only be used for moving within "
5368 "the same gig file."
5371 File* pFile = (File*) GetParent();
5375 File::InstrumentList& list = *pFile->pInstruments;
5377 File::InstrumentList::iterator itFrom =
5378 std::find(list.begin(), list.end(),
static_cast<DLS::Instrument*
>(
this));
5379 if (itFrom == list.end())
5381 "gig::Instrument::MoveTo(): unexpected missing membership "
5382 "of this instrument."
5386 File::InstrumentList::iterator itTo =
5387 std::find(list.begin(), list.end(),
static_cast<DLS::Instrument*
>(dst));
5389 list.insert(itTo,
this);
5395 this->pCkInstrument,
5396 (
RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
5411 return pMidiRules[i];
5420 delete pMidiRules[0];
5433 delete pMidiRules[0];
5446 delete pMidiRules[0];
5459 delete pMidiRules[i];
5463 void Instrument::LoadScripts() {
5464 if (pScriptRefs)
return;
5465 pScriptRefs =
new std::vector<_ScriptPooolRef>;
5466 if (scriptPoolFileOffsets.empty())
return;
5468 for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
5469 uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
5472 for (uint s = 0; group->
GetScript(s); ++s) {
5474 if (script->pChunk) {
5475 uint32_t offset = uint32_t(
5477 script->pChunk->
GetPos() -
5480 if (offset == soughtOffset)
5482 _ScriptPooolRef ref;
5483 ref.script = script;
5484 ref.bypass = scriptPoolFileOffsets[k].bypass;
5485 pScriptRefs->push_back(ref);
5493 scriptPoolFileOffsets.clear();
5510 if (index >= pScriptRefs->size())
return NULL;
5511 return pScriptRefs->at(index).script;
5551 _ScriptPooolRef ref = { pScript, bypass };
5552 pScriptRefs->push_back(ref);
5571 if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5573 _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5574 (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5575 (*pScriptRefs)[index2] = tmp;
5586 if (index >= pScriptRefs->size())
return;
5587 pScriptRefs->erase( pScriptRefs->begin() + index );
5604 for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5605 if ((*pScriptRefs)[i].script == pScript) {
5606 pScriptRefs->erase( pScriptRefs->begin() + i );
5626 return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
5647 return pScriptRefs ? pScriptRefs->at(index).bypass
5648 : scriptPoolFileOffsets.at(index).bypass;
5668 pScriptRefs->at(index).bypass = bBypass;
5670 scriptPoolFileOffsets.at(index).bypass = bBypass;
5675 std::array<uint8_t,16> uuid;
5676 memcpy(&uuid[0], pData, 16);
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)
5712 if (variable.empty())
return false;
5714 if (!script)
return false;
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);
5722 return slots.begin()->second.count(variable);
5747 if (!script)
return std::map<String,String>();
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;
5779 return (vars.count(variable)) ? vars.find(variable)->second :
"";
5805 if (variable.empty())
5806 throw Exception(
"Variable name must not be empty");
5809 throw Exception(
"No script slot with index " + ToString(slot));
5811 scriptVars[uuid][slot][variable] = value;
5849 if (slot != -1 && !variable.empty()) {
5850 if (!script)
return;
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)
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) );
5866 if (slot == -1 && variable.empty()) {
5873 if (!script)
return;
5875 if (scriptVars.count(uuid))
5876 scriptVars.erase( scriptVars.find(uuid) );
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) );
5892 slots.erase(itSlot++);
5897 scriptVars.erase(itScript++);
5910 Instrument::_VarsByScript Instrument::stripScriptVars() {
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))
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;
5925 if (itSlot->second.empty())
continue;
5926 vars[uuid][itSlot->first] = itSlot->second;
5956 DLS::Instrument::CopyAssignCore(orig);
5960 EffectSend = orig->EffectSend;
5963 PianoReleaseMode = orig->PianoReleaseMode;
5965 scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5967 if (pScriptRefs)
delete pScriptRefs;
5968 pScriptRefs =
new std::vector<_ScriptPooolRef>;
5969 if (orig->pScriptRefs)
5970 *pScriptRefs = *orig->pScriptRefs;
5971 scriptVars = orig->scriptVars;
5974 for (
int i = 0 ; pMidiRules[i] ; i++) {
5975 delete pMidiRules[i];
5978 pMidiRules[0] = NULL;
5984 RegionList::const_iterator it = orig->pRegions->begin();
5985 for (
int i = 0; i < orig->
Regions; ++i, ++it) {
5986 Region* dstRgn = AddRegion();
5995 UpdateRegionKeyTable();
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) {
6018 if (rgn->UsesAnyGigFormatExtension())
6036 pNameChunk = ck3gnm;
6037 SamplesIterator = 0;
6038 ::LoadString(pNameChunk,
Name);
6055 pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
6074 _3gri = pFile->pRIFF->
AddSubList(LIST_TYPE_3GRI);
6078 if (!_3gnl) _3gnl = _3gri->
AddSubList(LIST_TYPE_3GNL);
6080 if (!pNameChunk && pFile->pVersion && pFile->pVersion->major > 2) {
6084 if (strcmp(
static_cast<char*
>(ck->LoadChunkData()),
"") == 0) {
6092 ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl,
Name, String(
"Unnamed Group"),
true, 64);
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))
6109 if (pSample->GetGroup() !=
this)
continue;
6110 if (indexInGroup++ == index)
return pSample;
6129 size_t& i = this->SamplesIterator;
6131 for (
Sample* pSample = pFile->GetSample(i); pSample;
6132 pSample = pFile->GetSample(++i))
6134 if (pSample->GetGroup() ==
this)
6153 size_t& i = this->SamplesIterator;
6154 for (
Sample* pSample = pFile->GetSample(++i); pSample;
6155 pSample = pFile->GetSample(++i))
6157 if (pSample->GetGroup() ==
this)
6179 Group* pOtherGroup = NULL;
6180 for (pOtherGroup = pFile->GetGroup(i); pOtherGroup;
6181 pOtherGroup = pFile->GetGroup(++i))
6183 if (pOtherGroup !=
this)
break;
6186 "Could not move samples to another group, since there is no "
6187 "other Group. This is a bug, report it!"
6203 0, 2, 19980628 & 0xffff, 19980628 >> 16
6208 0, 3, 20030331 & 0xffff, 20030331 >> 16
6213 0, 4, 20071012 & 0xffff, 20071012 >> 16
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 },
6237 File::File() :
DLS::File() {
6239 *pVersion = VERSION_3;
6241 pScriptGroups = NULL;
6242 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
6243 pInfo->ArchivalLocation = String(256,
' ');
6247 pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
6248 pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
6249 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
6257 pScriptGroups = NULL;
6258 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
6263 std::vector<Group*>::iterator iter = pGroups->begin();
6264 std::vector<Group*>::iterator end = pGroups->end();
6265 while (iter != end) {
6271 if (pScriptGroups) {
6272 std::vector<ScriptGroup*>::iterator iter = pScriptGroups->begin();
6273 std::vector<ScriptGroup*>::iterator end = pScriptGroups->end();
6274 while (iter != end) {
6278 delete pScriptGroups;
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 );
6305 if (!pSamples)
return NULL;
6307 return static_cast<gig::Sample*
>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
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] );
6333 if (!pSamples) LoadSamples();
6334 if (!pSamples)
return 0;
6335 return pSamples->size();
6346 if (!pSamples) LoadSamples();
6351 Sample* pSample =
new Sample(
this, wave, 0 );
6357 const size_t idxIt = SamplesIterator - pSamples->begin();
6358 pSamples->push_back(pSample);
6359 SamplesIterator = pSamples->begin() + std::min(idxIt, pSamples->size());
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());
6384 for (Instrument* instrument =
GetInstrument(iIns); instrument;
6388 for (Region* region = instrument->GetRegionAt(iRgn); region;
6389 region = instrument->GetRegionAt(++iRgn))
6391 if (region->GetSample() == pSample) region->SetSample(NULL);
6393 for (
int i = 0 ; i < region->DimensionRegions ; i++) {
6401 void File::LoadSamples() {
6405 void File::LoadSamples(progress_t* pProgress) {
6408 if (!pGroups) LoadGroups();
6410 if (!pSamples) pSamples =
new SampleList;
6413 int iSampleIndex = 0;
6414 int iTotalSamples = WavePoolCount;
6417 const std::string folder = parentPath(pRIFF->GetFileName());
6418 const std::string baseName = pathWithoutExtension(pRIFF->GetFileName());
6422 std::vector<RIFF::File*> poolFiles;
6423 poolFiles.push_back(pRIFF);
6429 for (
int i = 0; i < n; i++) {
6433 std::string path = concatPath(folder, name);
6439 idExpected.ulData1 = ckXfil->
ReadInt32();
6440 idExpected.usData2 = ckXfil->
ReadInt16();
6441 idExpected.usData3 = ckXfil->
ReadInt16();
6442 ckXfil->
Read(idExpected.abData, 8, 1);
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());
6451 poolFiles.push_back(pExtFile);
6452 ExtensionFiles.push_back(pExtFile);
6457 RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
6459 std::string path = baseName +
".gx99";
6460 RIFF::File* pExtFile =
new RIFF::File(path);
6463 ckDoxf->
SetPos(132, RIFF::stream_curpos);
6466 RIFF::Chunk* ckDLSID = pExtFile->
GetSubChunk(CHUNK_ID_DLID);
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());
6481 poolFiles.push_back(pExtFile);
6482 ExtensionFiles.push_back(pExtFile);
6487 for (
int i = 0; i < poolFiles.size(); i++) {
6488 RIFF::File* file = poolFiles[i];
6489 RIFF::List* wvpl = file->
GetSubList(LIST_TYPE_WVPL);
6494 for (RIFF::List* wave = wvpl->
GetSubListAt(iWaveCk); wave;
6497 if (wave->GetListType() == LIST_TYPE_WAVE) {
6500 const float subprogress = (float) iSampleIndex / (
float) iTotalSamples;
6501 __notify_progress(pProgress, subprogress);
6505 pSamples->push_back(
new Sample(
this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex));
6514 __notify_progress(pProgress, 1.0);
6525 if (!pInstruments) LoadInstruments();
6526 if (!pInstruments)
return NULL;
6527 InstrumentsIterator = pInstruments->begin();
6528 return static_cast<gig::Instrument*
>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
6539 if (!pInstruments)
return NULL;
6540 InstrumentsIterator++;
6541 return static_cast<gig::Instrument*
>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
6553 if (!pInstruments) LoadInstruments();
6554 if (!pInstruments)
return 0;
6555 return pInstruments->size();
6566 if (!pInstruments) {
6571 progress_t subprogress;
6572 __divide_progress(pProgress, &subprogress, 3.0f, 0.0f);
6573 __notify_progress(&subprogress, 0.0f);
6576 __notify_progress(&subprogress, 1.0f);
6583 __notify_progress(&subprogress, 0.0f);
6584 LoadInstruments(&subprogress);
6585 __notify_progress(&subprogress, 1.0f);
6595 if (!pInstruments)
return NULL;
6596 if (index >= pInstruments->size())
return NULL;
6608 if (!pInstruments) LoadInstruments();
6617 Instrument* pInstrument =
new Instrument(
this, lstInstr);
6623 pInstrument->
pInfo->Software =
"Endless Wave";
6625 const size_t idxIt = InstrumentsIterator - pInstruments->begin();
6626 pInstruments->push_back(pInstrument);
6627 InstrumentsIterator = pInstruments->begin() + std::min(idxIt, pInstruments->size());
6664 static int iCallCount = -1;
6666 std::map<Group*,Group*> mGroups;
6667 std::map<Sample*,Sample*> mSamples;
6670 for (
int i = 0; pFile->
GetGroup(i); ++i) {
6671 Group* g = AddGroup();
6673 "COPY" + ToString(iCallCount) +
"_" + pFile->
GetGroup(i)->
Name;
6678 for (
int i = 0; pFile->
GetSample(i); ++i) {
6686 for (
size_t iGroup = 0; pFile->
GetScriptGroup(iGroup); ++iGroup) {
6689 dg->
Name =
"COPY" + ToString(iCallCount) +
"_" + sg->
Name;
6690 for (
int iScript = 0; sg->
GetScript(iScript); ++iScript) {
6722 for (
int i = 0; pFile->
GetSample(i); ++i) {
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());
6746 void File::LoadInstruments() {
6747 LoadInstruments(NULL);
6750 void File::LoadInstruments(progress_t* pProgress) {
6751 if (!pInstruments) pInstruments =
new InstrumentList;
6753 if (lstInstruments) {
6754 int iInstrumentIndex = 0;
6757 lstInstr; lstInstr = lstInstruments->
GetSubListAt(++i))
6759 if (lstInstr->GetListType() == LIST_TYPE_INS) {
6762 const float localProgress = (float) iInstrumentIndex / (
float)
Instruments;
6763 __notify_progress(pProgress, localProgress);
6766 progress_t subprogress;
6767 __divide_progress(pProgress, &subprogress,
Instruments, iInstrumentIndex);
6769 pInstruments->push_back(
new Instrument(
this, lstInstr, &subprogress));
6771 pInstruments->push_back(
new Instrument(
this, lstInstr));
6778 __notify_progress(pProgress, 1.0);
6786 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6790 int iWaveIndex = GetWaveTableIndexOf(pSample);
6791 if (iWaveIndex < 0)
throw gig::Exception(
"Could not update crc, could not find sample");
6794 _3crc->
SetPos(iWaveIndex * 8);
6800 uint32_t File::GetSampleChecksum(
Sample* pSample) {
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");
6805 return GetSampleChecksumByIndex(iWaveIndex);
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");
6812 if (!_3crc)
throw gig::Exception(
"Could not retrieve reference crc of sample, no checksums stored for this file yet");
6814 if (!pData)
throw gig::Exception(
"Could not retrieve reference crc of sample, no checksums stored for this file yet");
6817 size_t pos = index * 8;
6819 throw gig::Exception(
"Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
6821 uint32_t one = load32(&pData[pos]);
6823 throw gig::Exception(
"Could not retrieve reference crc of sample, because reference checksum table is damaged");
6825 return load32(&pData[pos+4]);
6828 int File::GetWaveTableIndexOf(gig::Sample* pSample) {
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)
6845 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6846 if (!_3crc)
return false;
6850 if (_3crc->
GetNewSize() != pSamples->size() * 8)
return false;
6852 const file_offset_t n = _3crc->
GetNewSize() / 8;
6855 if (!pData)
return false;
6857 for (file_offset_t i = 0; i < n; ++i) {
6858 uint32_t one = load32(&pData[i*8]);
6859 if (one != 1)
return false;
6885 bool bRequiresSave =
false;
6888 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6890 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
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;
6900 if (bRequiresSave) {
6903 File::SampleList::iterator iter = pSamples->begin();
6904 File::SampleList::iterator end = pSamples->end();
6905 for (; iter != end; ++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);
6910 store32(&pData[index*8 + 4], pSample->CalculateWaveDataChecksum());
6915 pRIFF->SetMode(RIFF::stream_mode_read_write);
6917 File::SampleList::iterator iter = pSamples->begin();
6918 File::SampleList::iterator end = pSamples->end();
6919 for (; iter != end; ++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();
6929 return bRequiresSave;
6939 if (!pGroups) LoadGroups();
6941 GroupsIterator = pGroups->begin();
6942 return *GroupsIterator;
6952 if (!pGroups)
return NULL;
6954 return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
6964 if (!pGroups) LoadGroups();
6965 if (index >= pGroups->size())
return NULL;
6966 return (*pGroups)[index];
6980 if (!pGroups) LoadGroups();
6983 if (pGroup->Name == name)
return pGroup;
6987 Group* File::AddGroup() {
6988 if (!pGroups) LoadGroups();
6992 pGroups->push_back(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!");
7013 while ((pSample = pGroup->
GetSample(0))) {
7017 pGroups->erase(iter);
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!");
7040 pGroups->erase(iter);
7045 void File::LoadGroups() {
7046 if (!pGroups) pGroups =
new std::vector<Group*>;
7056 if (ck->GetChunkID() == CHUNK_ID_3GNM) {
7058 strcmp(
static_cast<char*
>(ck->LoadChunkData()),
"") == 0)
break;
7060 pGroups->push_back(
new Group(
this, ck));
7066 if (!pGroups->size()) {
7067 Group* pGroup =
new Group(
this, NULL);
7068 pGroup->Name =
"Default Group";
7069 pGroups->push_back(pGroup);
7081 if (!pScriptGroups) LoadScriptGroups();
7082 if (index >= pScriptGroups->size())
return NULL;
7083 return (*pScriptGroups)[index];
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;
7112 if (!pScriptGroups) LoadScriptGroups();
7113 ScriptGroup* pScriptGroup =
new ScriptGroup(
this, NULL);
7114 pScriptGroups->push_back(pScriptGroup);
7115 return 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)
7139 if (pScriptGroup->pList)
7142 delete pScriptGroup;
7145 void File::LoadScriptGroups() {
7146 if (pScriptGroups)
return;
7147 pScriptGroups =
new std::vector<ScriptGroup*>;
7154 if (lst->GetListType() == LIST_TYPE_RTIS) {
7155 pScriptGroups->push_back(
new ScriptGroup(
this, lst));
7173 bool newFile = pRIFF->
GetSubList(LIST_TYPE_INFO) == NULL;
7184 RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
7185 pRIFF->MoveSubChunk(lst3LS, ckPTBL);
7190 if (pScriptGroups) {
7192 for (std::vector<ScriptGroup*>::iterator it = pScriptGroups->begin();
7193 it != pScriptGroups->end(); ++it)
7195 (*it)->UpdateChunks(pProgress);
7202 pRIFF->DeleteSubChunk(lst3LS);
7212 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
7214 if (first != info) {
7215 pRIFF->MoveSubChunk(info, first);
7229 if (!_3gnl) _3gnl = _3gri->
AddSubList(LIST_TYPE_3GNL);
7240 ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl,
"",
"",
true, 64);
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);
7267 int sublen = int(pSamples->size() / 8 + 49);
7270 RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
7272 if (einf->
GetSize() != einfSize) {
7276 }
else if (newFile) {
7277 einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
7282 std::map<gig::Sample*,int> sampleMap;
7283 size_t sampleIdx = 0;
7284 for (Sample* pSample =
GetSample(0); pSample;
7287 sampleMap[pSample] = sampleIdx;
7290 int totnbusedsamples = 0;
7291 int totnbusedchannels = 0;
7292 int totnbregions = 0;
7293 int totnbdimregions = 0;
7295 int instrumentIdx = 0;
7297 memset(&pData[48], 0, sublen - 48);
7300 for (Instrument* instrument =
GetInstrument(iIns); instrument;
7303 int nbusedsamples = 0;
7304 int nbusedchannels = 0;
7305 int nbdimregions = 0;
7308 memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
7311 for (Region* region = instrument->GetRegionAt(iRgn); region;
7312 region = instrument->GetRegionAt(++iRgn))
7314 for (
int i = 0 ; i < region->DimensionRegions ; i++) {
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;
7325 if ((pData[
byte] & bit) == 0) {
7334 nbdimregions += region->DimensionRegions;
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);
7345 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
7346 store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
7349 totnbregions += instrument->Regions;
7350 totnbdimregions += nbdimregions;
7351 totnbloops += nbloops;
7356 store32(&pData[4], totnbusedchannels);
7357 store32(&pData[8], totnbusedsamples);
7359 store32(&pData[16], totnbregions);
7360 store32(&pData[20], totnbdimregions);
7361 store32(&pData[24], totnbloops);
7364 store32(&pData[40], (uint32_t) pSamples->size());
7382 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
7384 _3crc->
Resize(pSamples->size() * 8);
7386 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
7388 if (einf &&
pVersion &&
pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf);
7393 File::SampleList::iterator iter = pSamples->begin();
7394 File::SampleList::iterator end = pSamples->end();
7395 for (
int index = 0; iter != end; ++iter, ++index) {
7397 store32(&pData[index*8], 1);
7398 store32(&pData[index*8 + 4], pSample->
crc);
7411 instrument->UpdateScriptFileOffsets();
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) {
7461 if (pInstrument->UsesAnyGigFormatExtension())
7471 Exception::Exception() : DLS::
Exception() {
7474 Exception::Exception(String format, ...) : DLS::
Exception() {
7476 va_start(arg, format);
7477 Message = assemble(format, arg);
7481 Exception::Exception(String format, va_list arg) : DLS::
Exception() {
7482 Message = assemble(format, arg);
7485 void Exception::PrintMessage()
const {
7486 std::cout <<
"gig::Exception: " << Message << std::endl;
virtual void UpdateChunks(progress_t *pProgress)
Apply all the DLS file's current instruments, samples and settings to the respective RIFF chunks.
void __ensureMandatoryChunksExist()
Checks if all (for DLS) mandatory chunks exist, if not they will be created.
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Sample * GetFirstSample()
Returns a pointer to the first Sample object of the file, NULL otherwise.
void SetFixedStringLengths(const string_length_t *lengths)
Forces specific Info fields to be of a fixed length when being saved to a file.
Provides all neccessary information for the synthesis of a DLS Instrument.
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Instrument object.
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Defines Region information of an Instrument.
virtual void CopyAssign(const Region *orig)
Make a (semi) deep copy of the Region object given by orig and assign it to this object.
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings to the respective RIFF chunks.
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.
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Region object.
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
void GenerateDLSID()
Generates a new DLSID for the resource.
Encapsulates sample waves used for playback.
void CopyAssignCore(const Sample *orig)
Make a deep copy of the Sample object given by orig (without the actual sample waveform data however)...
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
void Resize(file_offset_t NewSize)
Resize sample.
uint16_t BitDepth
Size of each sample per channel (only if known sample data format is used, 0 otherwise).
uint16_t Channels
Number of channels represented in the waveform data, e.g. 1 for mono, 2 for stereo (defaults to 1=mon...
file_offset_t GetSize() const
Returns sample size.
uint32_t SamplesPerSecond
Sampling rate at which each channel should be played (defaults to 44100 if Sample was created with In...
file_offset_t SamplesTotal
Reflects total number of sample points (only if known sample data format is used, 0 otherwise),...
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Sample object.
uint FrameSize
Reflects the size (in bytes) of one single sample point (only if known sample data format is used,...
virtual void UpdateChunks(progress_t *pProgress)
Apply all sample player options to the respective RIFF chunk.
File * GetFile() const
Returns pointer to the chunk's File object.
List * GetParent() const
Returns pointer to the chunk's parent list chunk.
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.
void Resize(file_offset_t NewSize)
Resize chunk.
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).
file_offset_t GetFilePos() const
Current, actual offset in file of current chunk data body read/write position.
file_offset_t RemainingBytes() const
Returns the number of bytes left to read in the chunk body.
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...
file_offset_t GetPos() const
Current read/write position within the chunk data body (starting with 0).
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...
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...
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.
void * LoadChunkData()
Load chunk body into RAM.
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.
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...
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...
void ReadString(String &s, int size)
Reads a null-padded string of size characters and copies it into the string s.
file_offset_t GetSize() const
Chunk size in bytes (without header, thus the chunk data body).
file_offset_t GetNewSize() const
New chunk size if it was modified with Resize(), otherwise value returned will be equal to GetSize().
int GetFileOffsetSize() const
Returns the current size (in bytes) of file offsets stored in the headers of all chunks of this file.
file_offset_t GetCurrentFileSize() const
Returns the current size of this file (in bytes) as it is currently yet stored on disk.
bool IsNew() const
Returns true if this file has been created new from scratch and has not been stored to disk yet.
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
List * GetSubListAt(size_t pos)
Returns sublist chunk with list type ListType at supplied pos position among all subchunks of type Li...
size_t CountSubChunks()
Returns number of subchunks within the list (including list chunks).
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
uint32_t GetListType() const
Returns unsigned integer representation of the list's ID.
Chunk * AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize)
Creates a new sub chunk.
Chunk * GetSubChunkAt(size_t pos)
Returns subchunk at supplied pos position within this chunk list.
Destination container for serialization, and source container for deserialization.
Encapsulates articulation informations of a dimension region.
uint8_t VelocityResponseCurveScaling
0 - 127 (usually you don't have to interpret this parameter, use GetVelocityAttenuation() instead).
vcf_cutoff_ctrl_t VCFCutoffController
Specifies which external controller has influence on the filter cutoff frequency.
void SetReleaseVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value.
uint8_t VelocityResponseDepth
Dynamic range of velocity affecting amplitude (0 - 4) (usually you don't have to interpret this param...
bool EG2InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released.
void SetVCFCutoffController(vcf_cutoff_ctrl_t controller)
Updates the respective member variable and the lookup table / cache that depends on this value.
eg2_ctrl_t EG2Controller
MIDI Controller which has influence on filter cutoff EG parameters (attack, decay,...
double EG2Release
Release time of the filter cutoff EG (0.000 - 60.000s).
eg1_ctrl_t EG1Controller
MIDI Controller which has influence on sample amplitude EG parameters (attack, decay,...
vcf_type_t VCFType
Defines the general filter characteristic (lowpass, highpass, bandpass, etc.).
double LFO3Phase
[gig extension]: Phase displacement of the pitch LFO's wave form (0.0° - 360.0°).
bool LFO3Sync
If set to true only one LFO should be used for all voices.
uint8_t VCFVelocityDynamicRange
0x04 = lowest, 0x00 = highest .
lfo3_ctrl_t LFO3Controller
MIDI Controller which controls the sample pitch LFO.
double EG1Decay1
Decay time of the sample amplitude EG (0.000 - 60.000s).
bool PitchTrack
If true: sample will be pitched according to the key position (this will be disabled for drums for ex...
double SampleAttenuation
Sample volume (calculated from DLS::Sampler::Gain).
uint8_t VCFVelocityScale
(0-127) Amount velocity controls VCF cutoff frequency (only if no other VCF cutoff controller is defi...
virtual void CopyAssign(const DimensionRegion *orig)
Make a (semi) deep copy of the DimensionRegion object given by orig and assign it to this object.
uint8_t EG1ControllerDecayInfluence
Amount EG1 Controller has influence on the EG1 Decay time (0 - 3, where 0 means off).
eg_opt_t EG1Options
[gig extension]: Behavior options which should be used for envelope generator 1 (volume amplitude EG)...
uint8_t EG2ControllerDecayInfluence
Amount EG2 Controller has influence on the EG2 Decay time (0 - 3, where 0 means off).
bool EG1InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released.
double EG2Decay1
Decay time of the filter cutoff EG (0.000 - 60.000s).
bool LFO1FlipPhase
Inverts the polarity of the sample amplitude LFO wave, so it flips the wave form vertically.
int16_t EG3Depth
Depth of the sample pitch EG (-1200 - +1200).
uint8_t ChannelOffset
Audio output where the audio signal of the dimension region should be routed to (0 - 9).
Sample * pSample
Points to the Sample which is assigned to the dimension region.
lfo_wave_t LFO1WaveForm
[gig extension]: The fundamental wave form to be used by the amplitude LFO, e.g. sine,...
uint8_t EG2ControllerAttackInfluence
Amount EG2 Controller has influence on the EG2 Attack time (0 - 3, where 0 means off).
void SetVCFVelocityScale(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value.
lfo_wave_t LFO3WaveForm
[gig extension]: The fundamental wave form to be used by the pitch LFO, e.g. sine,...
int16_t LFO3ControlDepth
Controller depth of the sample pitch LFO (-1200 - +1200 cents).
uint8_t EG2ControllerReleaseInfluence
Amount EG2 Controller has influence on the EG2 Release time (0 - 3, where 0 means off).
uint8_t EG1ControllerAttackInfluence
Amount EG1 Controller has influence on the EG1 Attack time (0 - 3, where 0 means off).
void SetReleaseVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
lfo2_ctrl_t LFO2Controller
MIDI Controlle which controls the filter cutoff LFO.
uint8_t VCFKeyboardTrackingBreakpoint
See VCFKeyboardTracking (0 - 127).
bool VCFResonanceDynamic
If true: Increases the resonance Q according to changes of controllers that actually control the VCF ...
double LFO2Phase
[gig extension]: Phase displacement of the filter cutoff LFO's wave form (0.0° - 360....
uint8_t DimensionUpperLimits[8]
gig3: defines the upper limit of the dimension values for this dimension region. In case you wondered...
uint8_t EG1ControllerReleaseInfluence
Amount EG1 Controller has influence on the EG1 Release time (0 - 3, where 0 means off).
uint8_t VCFResonance
Firm internal filter resonance weight.
uint16_t EG1Sustain
Sustain value of the sample amplitude EG (0 - 1000 permille).
dim_bypass_ctrl_t DimensionBypass
If defined, the MIDI controller can switch on/off the dimension in realtime.
bool EG2ControllerInvert
Invert values coming from defined EG2 controller.
void SetVCFVelocityDynamicRange(uint8_t range)
Updates the respective member variable and the lookup table / cache that depends on this value.
uint8_t * VelocityTable
For velocity dimensions with custom defined zone ranges only: used for fast converting from velocity ...
bool LFO1Sync
If set to true only one LFO should be used for all voices.
double EG1Attack
Attack time of the sample amplitude EG (0.000 - 60.000s).
uint32_t SampleLoops
Reflects the number of sample loops.
void SetVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
attenuation_ctrl_t AttenuationController
MIDI Controller which has influence on the volume level of the sample (or entire sample group).
double LFO1Phase
[gig extension]: Phase displacement of the amplitude LFO's wave form (0.0° - 360.0°).
virtual void UpdateChunks(progress_t *pProgress)
Apply dimension region settings to the respective RIFF chunks.
double GetVelocityAttenuation(uint8_t MIDIKeyVelocity)
Returns the correct amplitude factor for the given MIDIKeyVelocity.
double LFO1Frequency
Frequency of the sample amplitude LFO (0.10 - 10.00 Hz).
curve_type_t VelocityResponseCurve
Defines a transformation curve to the incoming velocity values affecting amplitude (usually you don't...
uint16_t EG2Sustain
Sustain value of the filter cutoff EG (0 - 1000 permille).
uint16_t LFO2ControlDepth
Controller depth influencing filter cutoff LFO pitch (0 - 1200).
lfo_wave_t LFO2WaveForm
[gig extension]: The fundamental wave form to be used by the filter cutoff LFO, e....
bool VCFKeyboardTracking
If true: VCF cutoff frequence will be dependend to the note key position relative to the defined brea...
uint8_t AttenuationControllerThreshold
0-127
double EG1Release
Release time of the sample amplitude EG (0.000 - 60.000s).
bool NoNoteOffReleaseTrigger
[gig extension]: If true then don't play a release trigger sample on MIDI note-off events.
void SetVelocityResponseCurveScaling(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value.
uint8_t VelocityUpperLimit
Defines the upper velocity value limit of a velocity split (only if an user defined limit was set,...
bool EG1Hold
If true, Decay1 stage should be postponed until the sample reached the sample loop start.
uint8_t ReleaseVelocityResponseDepth
Dynamic range of release velocity affecting envelope time (0 - 4).
curve_type_t ReleaseVelocityResponseCurve
Defines a transformation curve to the incoming release veloctiy values affecting envelope times.
void SetVCFVelocityCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value.
double EG1Decay2
Only if EG1InfiniteSustain == false: 2nd decay stage time of the sample amplitude EG (0....
bool InvertAttenuationController
Inverts the values coming from the defined Attenuation Controller.
uint16_t SampleStartOffset
Number of samples the sample start should be moved (0 - 2000).
double EG2Decay2
Only if EG2InfiniteSustain == false: 2nd stage decay time of the filter cutoff EG (0....
uint16_t LFO1InternalDepth
Firm pitch of the sample amplitude LFO (0 - 1200 cents).
bool EG1ControllerInvert
Invert values coming from defined EG1 controller.
lfo1_ctrl_t LFO1Controller
MIDI Controller which controls sample amplitude LFO.
bool VCFCutoffControllerInvert
Inverts values coming from the defined cutoff controller.
double LFO3Frequency
Frequency of the sample pitch LFO (0.10 - 10.00 Hz).
uint8_t ReleaseTriggerDecay
0 - 8
double EG3Attack
Attack time of the sample pitch EG (0.000 - 10.000s).
virtual void SetGain(int32_t gain)
Updates the respective member variable and updates SampleAttenuation which depends on this value.
double LFO2Frequency
Frequency of the filter cutoff LFO (0.10 - 10.00 Hz).
bool SustainDefeat
If true: Sustain pedal will not hold a note.
eg_opt_t EG2Options
[gig extension]: Behavior options which should be used for envelope generator 2 (filter cutoff EG).
bool LFO2FlipPhase
Inverts the polarity of the filter cutoff LFO wave, so it flips the wave form vertically.
sust_rel_trg_t SustainReleaseTrigger
[gig extension]: Whether a sustain pedal up event shall play release trigger sample.
sample_loop_t * pSampleLoops
Points to the beginning of a sample loop array, or is NULL if there are no loops defined.
bool MSDecode
Gigastudio flag: defines if Mid Side Recordings should be decoded.
bool VCFEnabled
If filter should be used.
uint16_t LFO1ControlDepth
Controller depth influencing sample amplitude LFO pitch (0 - 1200 cents).
int8_t Pan
Panorama / Balance (-64..0..63 <-> left..middle..right).
void SetVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value.
bool LFO2Sync
If set to true only one LFO should be used for all voices.
uint16_t EG1PreAttack
Preattack value of the sample amplitude EG (0 - 1000 permille).
bool SelfMask
If true: high velocity notes will stop low velocity notes at the same note, with that you can save vo...
uint8_t VCFCutoff
Max. cutoff frequency.
curve_type_t VCFVelocityCurve
Defines a transformation curve for the incoming velocity values, affecting the VCF.
double EG2Attack
Attack time of the filter cutoff EG (0.000 - 60.000s).
uint16_t EG2PreAttack
Preattack value of the filter cutoff EG (0 - 1000 permille).
uint16_t LFO2InternalDepth
Firm pitch of the filter cutoff LFO (0 - 1200 cents).
vcf_res_ctrl_t VCFResonanceController
Specifies which external controller has influence on the filter resonance Q.
int16_t LFO3InternalDepth
Firm depth of the sample pitch LFO (-1200 - +1200 cents).
bool LFO3FlipPhase
[gig extension]: Inverts the polarity of the pitch LFO wave, so it flips the wave form vertically (NO...
Will be thrown whenever a gig specific error occurs while trying to access a Gigasampler File.
Provides convenient access to Gigasampler/GigaStudio .gig files.
version_t * pVersion
Points to a version_t structure if the file provided a version number else is set to NULL.
virtual void UpdateChunks(progress_t *pProgress)
Apply all the gig file's current instruments, samples, groups and settings to the respective RIFF chu...
Sample * GetNextSample()
Returns a pointer to the next Sample object of the file, NULL otherwise.
size_t CountInstruments()
Returns the total amount of instruments of this gig file.
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
ScriptGroup * AddScriptGroup()
Add new instrument script group.
void SetSampleChecksum(Sample *pSample, uint32_t crc)
Updates the 3crc chunk with the checksum of a sample.
void DeleteScriptGroup(ScriptGroup *pGroup)
Delete an instrument script group.
Instrument * GetInstrument(size_t index, progress_t *pProgress=NULL)
Returns the instrument with the given index.
size_t CountSamples()
Returns the total amount of samples of this gig file.
Instrument * AddInstrument()
Add a new instrument definition.
Instrument * GetNextInstrument()
Returns a pointer to the next Instrument object of the file, NULL otherwise.
static const DLS::version_t VERSION_2
Reflects Gigasampler file format version 2.0 (1998-06-28).
Group * GetNextGroup()
Returns a pointer to the next Group object of the file, NULL otherwise.
bool GetAutoLoad()
Returns whether automatic loading is enabled.
uint32_t Instruments
Reflects the number of available Instrument objects.
void DeleteInstrument(Instrument *pInstrument)
Delete an instrument.
virtual void Save(const String &Path, progress_t *pProgress=NULL)
Save changes to another file.
Sample * GetSample(size_t index, progress_t *pProgress=NULL)
Returns Sample object of index.
bool RebuildSampleChecksumTable()
Recalculates CRC32 checksums for all samples and rebuilds this gig file's checksum table with those n...
void DeleteSample(Sample *pSample)
Delete a sample.
Instrument * AddDuplicateInstrument(const Instrument *orig)
Add a duplicate of an existing instrument.
ScriptGroup * GetScriptGroup(size_t index)
Get instrument script group (by index).
Group * GetFirstGroup()
Returns a pointer to the first Group object of the file, NULL otherwise.
Instrument * GetFirstInstrument()
Returns a pointer to the first Instrument object of the file, NULL otherwise.
void AddContentOf(File *pFile)
Add content of another existing file.
Group * GetGroup(size_t index)
Returns the group with the given index.
Sample * AddSample()
Add a new sample.
void DeleteGroup(Group *pGroup)
Delete a group and its samples.
String GetFileName()
File name of this DLS file.
void DeleteGroupOnly(Group *pGroup)
Delete a group.
void SetAutoLoad(bool b)
Enable / disable automatic loading.
bool VerifySampleChecksumTable()
Checks whether the file's "3CRC" chunk was damaged.
Group of Gigasampler samples.
Group(File *file, RIFF::Chunk *ck3gnm)
Constructor.
Sample * GetSample(size_t index)
Returns Sample object at index of this sample group.
Sample * GetFirstSample()
Returns the first Sample of this Group.
Sample * GetNextSample()
Returns the next Sample of the Group.
void MoveAll()
Move all members of this group to another group (preferably the 1st one except this).
virtual void UpdateChunks(progress_t *pProgress)
Update chunks with current group settings.
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Group object.
virtual ~Group()
Destructor.
void AddSample(Sample *pSample)
Move Sample given by pSample from another Group to this Group.
String Name
Stores the name of this Group.
Provides access to a Gigasampler/GigaStudio instrument.
void UnsetScriptPatchVariable(ssize_t slot=-1, String variable="")
Drop overridden initial value(s) for 'patch' variable(s).
MidiRule * GetMidiRule(int i)
Returns a MIDI rule of the instrument.
void DeleteMidiRule(int i)
Deletes a MIDI rule from the instrument.
void SetScriptSlotBypassed(size_t index, bool bBypass)
Defines whether execution shall be skipped.
bool IsScriptPatchVariableSet(size_t slot, String variable)
Checks whether a certain script 'patch' variable value is set.
virtual void CopyAssign(const Instrument *orig)
Make a (semi) deep copy of the Instrument object given by orig and assign it to this object.
void SwapScriptSlots(size_t index1, size_t index2)
Flip two script slots with each other (gig format extension).
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
size_t ScriptSlotCount() const
Instrument's amount of script slots.
Region * GetNextRegion()
Returns the next Region of the instrument.
MidiRuleCtrlTrigger * AddMidiRuleCtrlTrigger()
Adds the "controller trigger" MIDI rule to the instrument.
std::map< String, String > GetScriptPatchVariables(size_t slot)
Get all overridden script 'patch' variables.
MidiRuleAlternator * AddMidiRuleAlternator()
Adds the alternator MIDI rule to the instrument.
void MoveTo(Instrument *dst)
Move this instrument at the position before.
uint32_t Regions
Reflects the number of Region defintions this Instrument has.
Script * GetScriptOfSlot(size_t index)
Get instrument script (gig format extension).
MidiRuleLegato * AddMidiRuleLegato()
Adds the legato MIDI rule to the instrument.
String GetScriptPatchVariable(size_t slot, String variable)
Get overridden initial value for 'patch' variable.
uint16_t PitchbendRange
Number of semitones pitchbend controller can pitch (default is 2).
range_t DimensionKeyRange
0-127 (where 0 means C1 and 127 means G9)
Region * GetRegion(unsigned int Key)
Returns the appropriate Region for a triggered note.
void AddScriptSlot(Script *pScript, bool bypass=false)
Add new instrument script slot (gig format extension).
Region * RegionKeyTable[128]
fast lookup for the corresponding Region of a MIDI key
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
void RemoveScript(Script *pScript)
Remove reference to given Script (gig format extension).
void SetScriptPatchVariable(size_t slot, String variable, String value)
Override initial value for 'patch' variable.
Region * GetFirstRegion()
Returns the first Region of the instrument.
bool IsScriptSlotBypassed(size_t index)
Whether script execution shall be skipped.
void RemoveScriptSlot(size_t index)
Remove script slot.
Region * GetRegionAt(size_t pos)
Returns Region at supplied pos position within the region list of this instrument.
MIDI rule to automatically cycle through specified sequences of different articulations.
uint8_t Controller
CC number for controller selector.
struct gig::MidiRuleAlternator::pattern_t pPatterns[32]
A pattern is a sequence of articulation numbers.
range_t KeySwitchRange
Key range for key switch selector.
bool Polyphonic
If alternator should step forward only when all notes are off.
selector_t Selector
Method by which pattern is chosen.
uint8_t Patterns
Number of alternator patterns.
range_t PlayRange
Key range of the playable keys in the instrument.
uint8_t Articulations
Number of articulations in the instrument.
String pArticulations[32]
Names of the articulations.
bool Chained
If all patterns should be chained together.
MIDI rule for triggering notes by control change events.
uint8_t ControllerNumber
MIDI controller number.
uint8_t Triggers
Number of triggers.
MIDI rule for instruments with legato samples.
uint16_t ThresholdTime
Maximum time (ms) between two notes that should be played legato.
uint8_t LegatoSamples
Number of legato samples per key in each direction (always 12).
uint8_t BypassKey
Key to be used to bypass the sustain note.
uint8_t AltSustain1Key
Key triggering alternate sustain samples.
bool BypassUseController
If a controller should be used to bypass the sustain note.
uint8_t AltSustain2Key
Key triggering a second set of alternate sustain samples.
uint16_t ReleaseTime
Release time.
range_t KeyRange
Key range for legato notes.
uint8_t ReleaseTriggerKey
Key triggering release samples.
uint8_t BypassController
Controller to be used to bypass the sustain note.
Abstract base class for all MIDI rules.
Defines Region information of a Gigasampler/GigaStudio instrument.
DimensionRegion * pDimensionRegions[256]
Pointer array to the 32 (gig2) or 256 (gig3) possible dimension regions (reflects NULL for dimension ...
unsigned int Dimensions
Number of defined dimensions, do not alter!
dimension_def_t pDimensionDefinitions[8]
Defines the five (gig2) or eight (gig3) possible dimensions (the dimension's controller and number of...
virtual void CopyAssign(const Region *orig)
Make a (semi) deep copy of the Region object given by orig and assign it to this object.
void SetDimensionType(dimension_t oldType, dimension_t newType)
Change type of an existing dimension.
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...
void SplitDimensionZone(dimension_t type, int zone)
Divide split zone of a dimension in two (increment zone amount).
DimensionRegion * GetDimensionRegionByValue(const uint DimValues[8])
Use this method in your audio engine to get the appropriate dimension region with it's articulation d...
void DeleteDimensionZone(dimension_t type, int zone)
Delete one split zone of a dimension (decrement zone amount).
void AddDimension(dimension_def_t *pDimDef)
Einstein would have dreamed of it - create a new dimension.
unsigned int Layers
Amount of defined layers (1 - 32). A value of 1 actually means no layering, a value > 1 means there i...
Sample * GetSample()
Returns pointer address to the Sample referenced with this region.
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.
DimensionRegion * GetDimensionRegionByBit(const uint8_t DimBits[8])
Returns the appropriate DimensionRegion for the given dimension bit numbers (zone index).
void DeleteDimension(dimension_def_t *pDimDef)
Delete an existing dimension.
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings and all its DimensionRegions to the respective RIFF chunks.
uint32_t DimensionRegions
Total number of DimensionRegions this Region contains, do not alter!
Encapsulates sample waves of Gigasampler/GigaStudio files used for playback.
static void DestroyDecompressionBuffer(buffer_t &DecompressionBuffer)
Free decompression buffer, previously created with CreateDecompressionBuffer().
file_offset_t SamplesInLastFrame
For compressed samples only: length of the last sample frame.
loop_type_t LoopType
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
uint32_t Loops
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: Numb...
bool VerifyWaveData(uint32_t *pActually=NULL)
Checks the integrity of this sample's raw audio wave data.
uint32_t LoopFraction
The fractional value specifies a fraction of a sample at which to loop. This allows a loop to be fine...
unsigned long FileNo
File number (> 0 when sample is stored in an extension file, 0 when it's in the gig).
void CopyAssignMeta(const Sample *orig)
Make a (semi) deep copy of the Sample object given by orig (without the actual waveform data) and ass...
uint32_t LoopStart
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
uint32_t SMPTEOffset
The SMPTE Offset value specifies the time offset to be used for the synchronization / calibration to ...
buffer_t RAMCache
Buffers samples (already uncompressed) in RAM.
file_offset_t * FrameTable
For positioning within compressed samples only: stores the offset values for each frame.
uint32_t Product
Specifies the MIDI model ID defined by the manufacturer corresponding to the Manufacturer field....
uint32_t LoopEnd
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Group * pGroup
pointer to the Group this sample belongs to (always not-NULL)
file_offset_t WorstCaseFrameSize
For compressed samples only: size (in bytes) of the largest possible sample frame.
static buffer_t CreateDecompressionBuffer(file_offset_t MaxReadSize)
Allocates a decompression buffer for streaming (compressed) samples with Sample::Read().
Sample(File *pFile, RIFF::List *waveList, file_offset_t WavePoolOffset, unsigned long fileNo=0, int index=-1)
Constructor.
void Resize(file_offset_t NewSize)
Resize sample.
file_offset_t SamplePos
For compressed samples only: stores the current position (in sample points).
file_offset_t FrameOffset
Current offset (sample points) in current sample frame (for decompression only).
bool Compressed
If the sample wave is compressed (probably just interesting for instrument and sample editors,...
Group * GetGroup() const
Returns pointer to the Group this Sample belongs to.
uint32_t MIDIUnityNote
Specifies the musical note at which the sample will be played at it's original sample rate.
uint32_t crc
Reflects CRC-32 checksum of the raw sample data at the last time when the sample's raw wave form data...
buffer_t LoadSampleData()
Loads (and uncompresses if needed) the whole sample wave into RAM.
void CopyAssignWave(const Sample *orig)
Should be called after CopyAssignMeta() and File::Save() sequence.
smpte_format_t SMPTEFormat
Specifies the Society of Motion Pictures and Television E time format used in the following SMPTEOffs...
file_offset_t GetPos() const
Returns the current position in the sample (in sample points).
static size_t Instances
Number of instances of class Sample.
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).
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...
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 ...
bool Dithered
For 24-bit compressed samples only: if dithering was used during compression with bit reduction.
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...
uint32_t LoopID
Specifies the unique ID that corresponds to one of the defined cue points in the cue point list (only...
static buffer_t InternalDecompressionBuffer
Buffer used for decompression of samples, and only if no external decompression buffer was supplied.
uint32_t SamplePeriod
Specifies the duration of time that passes during the playback of one sample in nanoseconds (normally...
uint32_t LoopPlayCount
Number of times the loop should be played (a value of 0 = infinite).
buffer_t LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount)
Loads (and uncompresses if needed) the whole sample wave into RAM.
void ReleaseSampleData()
Frees the cached sample from RAM if loaded with LoadSampleData() previously.
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
file_offset_t Write(void *pBuffer, file_offset_t SampleCount)
Write sample wave data.
uint32_t Manufacturer
Specifies the MIDI Manufacturer's Association (MMA) Manufacturer code for the sampler intended to rec...
uint32_t TruncatedBits
For 24-bit compressed samples only: number of bits truncated during compression (0,...
buffer_t GetCache()
Returns current cached sample points.
uint32_t FineTune
Specifies the fraction of a semitone up from the specified MIDI unity note field. A value of 0x800000...
file_offset_t SamplesPerFrame
For compressed samples only: number of samples in a full sample frame.
uint32_t LoopSize
Caution: Use the respective fields in the DimensionRegion instead of this one! (Intended purpose: Len...
Group of instrument scripts (gig format extension).
virtual void UpdateChunks(progress_t *pProgress)
Apply this script group to the respective RIFF chunks.
void DeleteScript(Script *pScript)
Delete an instrument script.
Script * AddScript()
Add new instrument script.
String Name
Name of this script group. For example to be displayed in an instrument editor.
Script * GetScript(size_t index)
Get instrument script.
virtual void DeleteChunks()
Remove all RIFF chunks associated with this ScriptGroup object.
Real-time instrument script (gig format extension).
Compression_t Compression
Whether the script was/should be compressed, and if so, which compression algorithm shall be used.
@ COMPRESSION_NONE
Is not compressed at all (default).
void SetGroup(ScriptGroup *pGroup)
Move this script from its current ScriptGroup to another ScriptGroup given by pGroup.
Language_t Language
Programming language and dialect the script is written in.
Encoding_t Encoding
Format the script's source code text is encoded with.
uint8_t Uuid[16]
Persistent Universally Unique Identifier of this script, which remains identical after any changes to...
@ ENCODING_ASCII
Standard 8 bit US ASCII character encoding (default).
void UpdateChunks(progress_t *pProgress)
Apply this script to the respective RIFF chunks.
@ LANGUAGE_NKSP
NKSP stands for "Is Not KSP" (default). Refer to the NKSP Reference Manual for details about this scr...
bool Bypass
Global bypass: if enabled, this script shall not be executed by the sampler for any instrument.
String Name
Arbitrary name of the script, which may be displayed i.e. in an instrument editor.
void DeleteChunks()
Remove all RIFF chunks associated with this Script object.
void SetScriptAsText(const String &text)
Replaces the current script with the new script source code text given by text.
String GetScriptAsText()
Returns the current script (i.e.
void CopyAssign(const Script *orig)
Make a (semi) deep copy of the Script object given by orig and assign it to this object.
ScriptGroup * GetGroup() const
Returns the script group this script currently belongs to.
void GenerateUuid()
Generate a new Universally Unique Identifier (UUID) for this script.
DLS specific classes and definitions.
stream_whence_t
File stream position dependent to these relations.
uint64_t file_offset_t
Type used by libgig for handling file positioning during file I/O tasks.
Gigasampler/GigaStudio specific classes and definitions.
@ dim_bypass_ctrl_94
Effect 4 Depth (MIDI Controller 94).
@ dim_bypass_ctrl_95
Effect 5 Depth (MIDI Controller 95).
@ dim_bypass_ctrl_none
No controller bypass.
vcf_res_ctrl_t
Defines how the filter resonance is controlled by.
@ vcf_res_ctrl_none
No MIDI controller assigned for filter resonance.
String libraryName()
Returns the name of this C++ library.
@ smpte_format_no_offset
no SMPTE offset
curve_type_t
Defines the shape of a function graph.
@ curve_type_nonlinear
Non-linear curve type.
@ curve_type_unknown
Unknown curve type.
@ curve_type_linear
Linear curve type.
@ curve_type_special
Special curve type.
lfo1_ctrl_t
Defines how LFO1 is controlled by.
@ lfo1_ctrl_internal
Only internally controlled.
sust_rel_trg_t
Defines behaviour of release triggered sample(s) on sustain pedal up event.
@ sust_rel_trg_none
No release triggered sample(s) are played on sustain pedal up (default).
vcf_cutoff_ctrl_t
Defines how the filter cutoff frequency is controlled by.
@ vcf_cutoff_ctrl_none2
The difference between none and none2 is unknown.
@ vcf_cutoff_ctrl_none
No MIDI controller assigned for filter cutoff frequency.
lfo_wave_t
Defines the wave form type used by an LFO (gig format extension).
@ lfo_wave_sine
Sine (sinus) wave form (this is the default wave form).
split_type_t
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
@ split_type_bit
dimension values are already the sought bit number
@ split_type_normal
dimension value between 0-127
std::array< uint8_t, 16 > _UUIDFromCArray(const uint8_t *pData)
type cast (by copy) uint8_t[16] -> std::array<uint8_t,16>
String libraryVersion()
Returns version of this C++ library.
@ loop_type_bidirectional
Alternating loop (forward/backward, also known as Ping Pong).
@ loop_type_backward
Loop backward (reverse).
@ loop_type_normal
Loop forward (normal).
lfo3_ctrl_t
Defines how LFO3 is controlled by.
@ lfo3_ctrl_modwheel
Only controlled by external modulation wheel.
lfo2_ctrl_t
Defines how LFO2 is controlled by.
@ lfo2_ctrl_internal
Only internally controlled.
dimension_t
Defines the type of dimension, that is how the dimension zones (and thus how the dimension regions ar...
@ dimension_keyboard
Dimension for keyswitching.
@ dimension_roundrobinkeyboard
Different samples triggered each time a note is played, any key advances the counter.
@ dimension_samplechannel
If used sample has more than one channel (thus is not mono).
@ dimension_smartmidi
For MIDI tools like legato and repetition mode.
@ dimension_releasetrigger
Special dimension for triggering samples on releasing a key.
@ dimension_velocity
Key Velocity (this is the only dimension in gig2 where the ranges can exactly be defined).
@ dimension_random
Different samples triggered each time a note is played, random order.
@ dimension_none
Dimension not in use.
@ dimension_roundrobin
Different samples triggered each time a note is played, dimension regions selected in sequence.
@ dimension_layer
For layering of up to 8 instruments (and eventually crossfading of 2 or 4 layers).
vcf_type_t
Audio filter types.
@ vcf_type_lowpassturbo
More poles than normal lowpass (GigaStudio).
@ vcf_type_lowpass
Standard lowpass filter type (GigaStudio).
Every subject of an DLS file and the file itself can have an unique, computer generated ID.
uint16_t low
Low value of range.
uint16_t high
High value of range.
Defines Sample Loop Points.
uint32_t LoopLength
Length of the looping area (in sample points).
uint32_t LoopStart
The start value specifies the offset (in sample points) in the waveform data of the first sample poin...
uint32_t LoopType
Defines how the waveform samples will be looped (appropriate loop types for the gig format are define...
Quadtuple version number ("major.minor.release.build").
float __range_min
Only for internal usage, do not modify!
void(*) callback(progress_t *)
Callback function pointer which has to be assigned to a function for progress notification.
float __range_max
Only for internal usage, do not modify!
Pointer address and size of a buffer.
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...
void * pStart
Points to the beginning of the buffer.
file_offset_t Size
Size of the actual data in the buffer in bytes.
uint8_t in_end
End position of fade in.
uint8_t in_start
Start position of fade in.
uint8_t out_end
End postition of fade out.
uint8_t out_start
Start position of fade out.
General dimension definition.
dimension_t dimension
Specifies which source (usually a MIDI controller) is associated with the dimension.
uint8_t zones
Number of zones the dimension has.
uint8_t bits
Number of "bits" (1 bit = 2 splits/zones, 2 bit = 4 splits/zones, 3 bit = 8 splits/zones,...
float zone_size
Intended for internal usage: reflects the size of each zone (128/zones) for normal split types only,...
split_type_t split_type
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Defines behavior options for envelope generators (gig format extension).
bool AttackHoldCancel
Whether the "attack hold" stage is cancelled when receiving a note-off (default: true).
bool Decay1Cancel
Whether the "decay 1" stage is cancelled when receiving a note-off (default: true).
bool ReleaseCancel
Whether the "release" stage is cancelled when receiving a note-on (default: true).
bool AttackCancel
Whether the "attack" stage is cancelled when receiving a note-off (default: true).
bool Decay2Cancel
Whether the "decay 2" stage is cancelled when receiving a note-off (default: true).
Defines a controller that has a certain contrained influence on a particular synthesis parameter (use...
@ type_none
No controller defined.
@ type_velocity
Key Velocity.
@ type_controlchange
Ordinary MIDI control change controller, see field 'controller_number'.
@ type_channelaftertouch
Channel Key Pressure.
uint controller_number
MIDI controller number if this controller is a control change controller, 0 otherwise.
type_t type
Controller type.
Reflects the current playback state for a sample.
bool reverse
If playback direction is currently backwards (in case there is a pingpong or reverse loop defined).
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.
file_offset_t position
Current position within the sample.
uint8_t high
High value of range.
uint8_t low
Low value of range.