00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include "gig.h"
00025
00026 #include "helper.h"
00027
00028 #include <algorithm>
00029 #include <math.h>
00030 #include <iostream>
00031 #include <algorithm>
00032
00038 #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
00039
00041 #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
00042 #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
00043 #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
00044 #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
00045 #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
00046 #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
00047 #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
00048 #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
00049 #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
00050 #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
00051 #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
00052 #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
00053
00054 namespace gig {
00055
00056
00057
00058
00059 progress_t::progress_t() {
00060 callback = NULL;
00061 custom = NULL;
00062 __range_min = 0.0f;
00063 __range_max = 1.0f;
00064 }
00065
00066
00067 static void __notify_progress(progress_t* pProgress, float subprogress) {
00068 if (pProgress && pProgress->callback) {
00069 const float totalrange = pProgress->__range_max - pProgress->__range_min;
00070 const float totalprogress = pProgress->__range_min + subprogress * totalrange;
00071 pProgress->factor = totalprogress;
00072 pProgress->callback(pProgress);
00073 }
00074 }
00075
00076
00077 static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
00078 if (pParentProgress && pParentProgress->callback) {
00079 const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
00080 pSubProgress->callback = pParentProgress->callback;
00081 pSubProgress->custom = pParentProgress->custom;
00082 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
00083 pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
00084 }
00085 }
00086
00087
00088
00089
00090
00091 namespace {
00092
00093 inline int get12lo(const unsigned char* pSrc)
00094 {
00095 const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
00096 return x & 0x800 ? x - 0x1000 : x;
00097 }
00098
00099 inline int get12hi(const unsigned char* pSrc)
00100 {
00101 const int x = pSrc[1] >> 4 | pSrc[2] << 4;
00102 return x & 0x800 ? x - 0x1000 : x;
00103 }
00104
00105 inline int16_t get16(const unsigned char* pSrc)
00106 {
00107 return int16_t(pSrc[0] | pSrc[1] << 8);
00108 }
00109
00110 inline int get24(const unsigned char* pSrc)
00111 {
00112 const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
00113 return x & 0x800000 ? x - 0x1000000 : x;
00114 }
00115
00116 inline void store24(unsigned char* pDst, int x)
00117 {
00118 pDst[0] = x;
00119 pDst[1] = x >> 8;
00120 pDst[2] = x >> 16;
00121 }
00122
00123 void Decompress16(int compressionmode, const unsigned char* params,
00124 int srcStep, int dstStep,
00125 const unsigned char* pSrc, int16_t* pDst,
00126 unsigned long currentframeoffset,
00127 unsigned long copysamples)
00128 {
00129 switch (compressionmode) {
00130 case 0:
00131 pSrc += currentframeoffset * srcStep;
00132 while (copysamples) {
00133 *pDst = get16(pSrc);
00134 pDst += dstStep;
00135 pSrc += srcStep;
00136 copysamples--;
00137 }
00138 break;
00139
00140 case 1:
00141 int y = get16(params);
00142 int dy = get16(params + 2);
00143 while (currentframeoffset) {
00144 dy -= int8_t(*pSrc);
00145 y -= dy;
00146 pSrc += srcStep;
00147 currentframeoffset--;
00148 }
00149 while (copysamples) {
00150 dy -= int8_t(*pSrc);
00151 y -= dy;
00152 *pDst = y;
00153 pDst += dstStep;
00154 pSrc += srcStep;
00155 copysamples--;
00156 }
00157 break;
00158 }
00159 }
00160
00161 void Decompress24(int compressionmode, const unsigned char* params,
00162 int dstStep, const unsigned char* pSrc, uint8_t* pDst,
00163 unsigned long currentframeoffset,
00164 unsigned long copysamples, int truncatedBits)
00165 {
00166 int y, dy, ddy, dddy;
00167
00168 #define GET_PARAMS(params) \
00169 y = get24(params); \
00170 dy = y - get24((params) + 3); \
00171 ddy = get24((params) + 6); \
00172 dddy = get24((params) + 9)
00173
00174 #define SKIP_ONE(x) \
00175 dddy -= (x); \
00176 ddy -= dddy; \
00177 dy = -dy - ddy; \
00178 y += dy
00179
00180 #define COPY_ONE(x) \
00181 SKIP_ONE(x); \
00182 store24(pDst, y << truncatedBits); \
00183 pDst += dstStep
00184
00185 switch (compressionmode) {
00186 case 2:
00187 pSrc += currentframeoffset * 3;
00188 while (copysamples) {
00189 store24(pDst, get24(pSrc) << truncatedBits);
00190 pDst += dstStep;
00191 pSrc += 3;
00192 copysamples--;
00193 }
00194 break;
00195
00196 case 3:
00197 GET_PARAMS(params);
00198 while (currentframeoffset) {
00199 SKIP_ONE(get16(pSrc));
00200 pSrc += 2;
00201 currentframeoffset--;
00202 }
00203 while (copysamples) {
00204 COPY_ONE(get16(pSrc));
00205 pSrc += 2;
00206 copysamples--;
00207 }
00208 break;
00209
00210 case 4:
00211 GET_PARAMS(params);
00212 while (currentframeoffset > 1) {
00213 SKIP_ONE(get12lo(pSrc));
00214 SKIP_ONE(get12hi(pSrc));
00215 pSrc += 3;
00216 currentframeoffset -= 2;
00217 }
00218 if (currentframeoffset) {
00219 SKIP_ONE(get12lo(pSrc));
00220 currentframeoffset--;
00221 if (copysamples) {
00222 COPY_ONE(get12hi(pSrc));
00223 pSrc += 3;
00224 copysamples--;
00225 }
00226 }
00227 while (copysamples > 1) {
00228 COPY_ONE(get12lo(pSrc));
00229 COPY_ONE(get12hi(pSrc));
00230 pSrc += 3;
00231 copysamples -= 2;
00232 }
00233 if (copysamples) {
00234 COPY_ONE(get12lo(pSrc));
00235 }
00236 break;
00237
00238 case 5:
00239 GET_PARAMS(params);
00240 while (currentframeoffset) {
00241 SKIP_ONE(int8_t(*pSrc++));
00242 currentframeoffset--;
00243 }
00244 while (copysamples) {
00245 COPY_ONE(int8_t(*pSrc++));
00246 copysamples--;
00247 }
00248 break;
00249 }
00250 }
00251
00252 const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
00253 const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
00254 const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
00255 const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
00256 }
00257
00258
00259
00260
00261
00262
00263 static uint32_t* __initCRCTable() {
00264 static uint32_t res[256];
00265
00266 for (int i = 0 ; i < 256 ; i++) {
00267 uint32_t c = i;
00268 for (int j = 0 ; j < 8 ; j++) {
00269 c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
00270 }
00271 res[i] = c;
00272 }
00273 return res;
00274 }
00275
00276 static const uint32_t* __CRCTable = __initCRCTable();
00277
00283 inline static void __resetCRC(uint32_t& crc) {
00284 crc = 0xffffffff;
00285 }
00286
00306 static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
00307 for (int i = 0 ; i < bufSize ; i++) {
00308 crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
00309 }
00310 }
00311
00317 inline static uint32_t __encodeCRC(const uint32_t& crc) {
00318 return crc ^ 0xffffffff;
00319 }
00320
00321
00322
00323
00324
00325
00326 static split_type_t __resolveSplitType(dimension_t dimension) {
00327 return (
00328 dimension == dimension_layer ||
00329 dimension == dimension_samplechannel ||
00330 dimension == dimension_releasetrigger ||
00331 dimension == dimension_keyboard ||
00332 dimension == dimension_roundrobin ||
00333 dimension == dimension_random ||
00334 dimension == dimension_smartmidi ||
00335 dimension == dimension_roundrobinkeyboard
00336 ) ? split_type_bit : split_type_normal;
00337 }
00338
00339 static int __resolveZoneSize(dimension_def_t& dimension_definition) {
00340 return (dimension_definition.split_type == split_type_normal)
00341 ? int(128.0 / dimension_definition.zones) : 0;
00342 }
00343
00344
00345
00346
00347
00348
00349 unsigned int Sample::Instances = 0;
00350 buffer_t Sample::InternalDecompressionBuffer;
00351
00370 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
00371 static const DLS::Info::string_length_t fixedStringLengths[] = {
00372 { CHUNK_ID_INAM, 64 },
00373 { 0, 0 }
00374 };
00375 pInfo->SetFixedStringLengths(fixedStringLengths);
00376 Instances++;
00377 FileNo = fileNo;
00378
00379 __resetCRC(crc);
00380
00381 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
00382 if (pCk3gix) {
00383 uint16_t iSampleGroup = pCk3gix->ReadInt16();
00384 pGroup = pFile->GetGroup(iSampleGroup);
00385 } else {
00386
00387 pGroup = pFile->GetGroup(0);
00388 }
00389
00390 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
00391 if (pCkSmpl) {
00392 Manufacturer = pCkSmpl->ReadInt32();
00393 Product = pCkSmpl->ReadInt32();
00394 SamplePeriod = pCkSmpl->ReadInt32();
00395 MIDIUnityNote = pCkSmpl->ReadInt32();
00396 FineTune = pCkSmpl->ReadInt32();
00397 pCkSmpl->Read(&SMPTEFormat, 1, 4);
00398 SMPTEOffset = pCkSmpl->ReadInt32();
00399 Loops = pCkSmpl->ReadInt32();
00400 pCkSmpl->ReadInt32();
00401 LoopID = pCkSmpl->ReadInt32();
00402 pCkSmpl->Read(&LoopType, 1, 4);
00403 LoopStart = pCkSmpl->ReadInt32();
00404 LoopEnd = pCkSmpl->ReadInt32();
00405 LoopFraction = pCkSmpl->ReadInt32();
00406 LoopPlayCount = pCkSmpl->ReadInt32();
00407 } else {
00408
00409 Manufacturer = 0;
00410 Product = 0;
00411 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
00412 MIDIUnityNote = 60;
00413 FineTune = 0;
00414 SMPTEFormat = smpte_format_no_offset;
00415 SMPTEOffset = 0;
00416 Loops = 0;
00417 LoopID = 0;
00418 LoopType = loop_type_normal;
00419 LoopStart = 0;
00420 LoopEnd = 0;
00421 LoopFraction = 0;
00422 LoopPlayCount = 0;
00423 }
00424
00425 FrameTable = NULL;
00426 SamplePos = 0;
00427 RAMCache.Size = 0;
00428 RAMCache.pStart = NULL;
00429 RAMCache.NullExtensionSize = 0;
00430
00431 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
00432
00433 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
00434 Compressed = ewav;
00435 Dithered = false;
00436 TruncatedBits = 0;
00437 if (Compressed) {
00438 uint32_t version = ewav->ReadInt32();
00439 if (version == 3 && BitDepth == 24) {
00440 Dithered = ewav->ReadInt32();
00441 ewav->SetPos(Channels == 2 ? 84 : 64);
00442 TruncatedBits = ewav->ReadInt32();
00443 }
00444 ScanCompressedSample();
00445 }
00446
00447
00448 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
00449 InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
00450 InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
00451 }
00452 FrameOffset = 0;
00453
00454 LoopSize = LoopEnd - LoopStart + 1;
00455 }
00456
00468 void Sample::UpdateChunks() {
00469
00470 DLS::Sample::UpdateChunks();
00471
00472
00473 pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
00474 if (!pCkSmpl) {
00475 pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
00476 memset(pCkSmpl->LoadChunkData(), 0, 60);
00477 }
00478
00479 uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
00480 SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
00481 store32(&pData[0], Manufacturer);
00482 store32(&pData[4], Product);
00483 store32(&pData[8], SamplePeriod);
00484 store32(&pData[12], MIDIUnityNote);
00485 store32(&pData[16], FineTune);
00486 store32(&pData[20], SMPTEFormat);
00487 store32(&pData[24], SMPTEOffset);
00488 store32(&pData[28], Loops);
00489
00490
00491
00492 store32(&pData[36], LoopID);
00493 store32(&pData[40], LoopType);
00494 store32(&pData[44], LoopStart);
00495 store32(&pData[48], LoopEnd);
00496 store32(&pData[52], LoopFraction);
00497 store32(&pData[56], LoopPlayCount);
00498
00499
00500 pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
00501 if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
00502
00503 uint16_t iSampleGroup = 0;
00504 File* pFile = static_cast<File*>(pParent);
00505 if (pFile->pGroups) {
00506 std::list<Group*>::iterator iter = pFile->pGroups->begin();
00507 std::list<Group*>::iterator end = pFile->pGroups->end();
00508 for (int i = 0; iter != end; i++, iter++) {
00509 if (*iter == pGroup) {
00510 iSampleGroup = i;
00511 break;
00512 }
00513 }
00514 }
00515
00516 pData = (uint8_t*) pCk3gix->LoadChunkData();
00517 store16(&pData[0], iSampleGroup);
00518 }
00519
00521 void Sample::ScanCompressedSample() {
00522
00523 this->SamplesTotal = 0;
00524 std::list<unsigned long> frameOffsets;
00525
00526 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
00527 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;
00528
00529
00530 pCkData->SetPos(0);
00531 if (Channels == 2) {
00532 for (int i = 0 ; ; i++) {
00533
00534
00535 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
00536
00537 const int mode_l = pCkData->ReadUint8();
00538 const int mode_r = pCkData->ReadUint8();
00539 if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
00540 const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
00541
00542 if (pCkData->RemainingBytes() <= frameSize) {
00543 SamplesInLastFrame =
00544 ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
00545 (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
00546 SamplesTotal += SamplesInLastFrame;
00547 break;
00548 }
00549 SamplesTotal += SamplesPerFrame;
00550 pCkData->SetPos(frameSize, RIFF::stream_curpos);
00551 }
00552 }
00553 else {
00554 for (int i = 0 ; ; i++) {
00555 if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
00556
00557 const int mode = pCkData->ReadUint8();
00558 if (mode > 5) throw gig::Exception("Unknown compression mode");
00559 const unsigned long frameSize = bytesPerFrame[mode];
00560
00561 if (pCkData->RemainingBytes() <= frameSize) {
00562 SamplesInLastFrame =
00563 ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
00564 SamplesTotal += SamplesInLastFrame;
00565 break;
00566 }
00567 SamplesTotal += SamplesPerFrame;
00568 pCkData->SetPos(frameSize, RIFF::stream_curpos);
00569 }
00570 }
00571 pCkData->SetPos(0);
00572
00573
00574 if (FrameTable) delete[] FrameTable;
00575 FrameTable = new unsigned long[frameOffsets.size()];
00576 std::list<unsigned long>::iterator end = frameOffsets.end();
00577 std::list<unsigned long>::iterator iter = frameOffsets.begin();
00578 for (int i = 0; iter != end; i++, iter++) {
00579 FrameTable[i] = *iter;
00580 }
00581 }
00582
00592 buffer_t Sample::LoadSampleData() {
00593 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0);
00594 }
00595
00618 buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
00619 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0);
00620 }
00621
00641 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
00642 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
00643 }
00644
00677 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
00678 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
00679 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
00680 unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
00681 SetPos(0);
00682 RAMCache.pStart = new int8_t[allocationsize];
00683 RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
00684 RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
00685
00686 memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
00687 return GetCache();
00688 }
00689
00700 buffer_t Sample::GetCache() {
00701
00702 buffer_t result;
00703 result.Size = this->RAMCache.Size;
00704 result.pStart = this->RAMCache.pStart;
00705 result.NullExtensionSize = this->RAMCache.NullExtensionSize;
00706 return result;
00707 }
00708
00715 void Sample::ReleaseSampleData() {
00716 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
00717 RAMCache.pStart = NULL;
00718 RAMCache.Size = 0;
00719 RAMCache.NullExtensionSize = 0;
00720 }
00721
00752 void Sample::Resize(int iNewSize) {
00753 if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
00754 DLS::Sample::Resize(iNewSize);
00755 }
00756
00778 unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
00779 if (Compressed) {
00780 switch (Whence) {
00781 case RIFF::stream_curpos:
00782 this->SamplePos += SampleCount;
00783 break;
00784 case RIFF::stream_end:
00785 this->SamplePos = this->SamplesTotal - 1 - SampleCount;
00786 break;
00787 case RIFF::stream_backward:
00788 this->SamplePos -= SampleCount;
00789 break;
00790 case RIFF::stream_start: default:
00791 this->SamplePos = SampleCount;
00792 break;
00793 }
00794 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
00795
00796 unsigned long frame = this->SamplePos / 2048;
00797 this->FrameOffset = this->SamplePos % 2048;
00798 pCkData->SetPos(FrameTable[frame]);
00799 return this->SamplePos;
00800 }
00801 else {
00802 unsigned long orderedBytes = SampleCount * this->FrameSize;
00803 unsigned long result = pCkData->SetPos(orderedBytes, Whence);
00804 return (result == orderedBytes) ? SampleCount
00805 : result / this->FrameSize;
00806 }
00807 }
00808
00812 unsigned long Sample::GetPos() {
00813 if (Compressed) return SamplePos;
00814 else return pCkData->GetPos() / FrameSize;
00815 }
00816
00851 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
00852 DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
00853 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
00854 uint8_t* pDst = (uint8_t*) pBuffer;
00855
00856 SetPos(pPlaybackState->position);
00857
00858 if (pDimRgn->SampleLoops) {
00859
00860 const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
00861 const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
00862
00863 if (GetPos() <= loopEnd) {
00864 switch (loop.LoopType) {
00865
00866 case loop_type_bidirectional: {
00867 do {
00868
00869 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
00870
00871 if (!pPlaybackState->reverse) {
00872 do {
00873 samplestoloopend = loopEnd - GetPos();
00874 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
00875 samplestoread -= readsamples;
00876 totalreadsamples += readsamples;
00877 if (readsamples == samplestoloopend) {
00878 pPlaybackState->reverse = true;
00879 break;
00880 }
00881 } while (samplestoread && readsamples);
00882 }
00883 else {
00884
00885
00886
00887
00888
00889
00890
00891 unsigned long swapareastart = totalreadsamples;
00892 unsigned long loopoffset = GetPos() - loop.LoopStart;
00893 unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
00894 unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
00895
00896 SetPos(reverseplaybackend);
00897
00898
00899 do {
00900 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
00901 samplestoreadinloop -= readsamples;
00902 samplestoread -= readsamples;
00903 totalreadsamples += readsamples;
00904 } while (samplestoreadinloop && readsamples);
00905
00906 SetPos(reverseplaybackend);
00907
00908 if (reverseplaybackend == loop.LoopStart) {
00909 pPlaybackState->loop_cycles_left--;
00910 pPlaybackState->reverse = false;
00911 }
00912
00913
00914 if (totalreadsamples > swapareastart)
00915 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
00916 }
00917 } while (samplestoread && readsamples);
00918 break;
00919 }
00920
00921 case loop_type_backward: {
00922
00923 if (!pPlaybackState->reverse) do {
00924 samplestoloopend = loopEnd - GetPos();
00925 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
00926 samplestoread -= readsamples;
00927 totalreadsamples += readsamples;
00928 if (readsamples == samplestoloopend) {
00929 pPlaybackState->reverse = true;
00930 break;
00931 }
00932 } while (samplestoread && readsamples);
00933
00934 if (!samplestoread) break;
00935
00936
00937
00938
00939
00940
00941
00942 unsigned long swapareastart = totalreadsamples;
00943 unsigned long loopoffset = GetPos() - loop.LoopStart;
00944 unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
00945 : samplestoread;
00946 unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
00947
00948 SetPos(reverseplaybackend);
00949
00950
00951 do {
00952
00953 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
00954 samplestoloopend = loopEnd - GetPos();
00955 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
00956 samplestoreadinloop -= readsamples;
00957 samplestoread -= readsamples;
00958 totalreadsamples += readsamples;
00959 if (readsamples == samplestoloopend) {
00960 pPlaybackState->loop_cycles_left--;
00961 SetPos(loop.LoopStart);
00962 }
00963 } while (samplestoreadinloop && readsamples);
00964
00965 SetPos(reverseplaybackend);
00966
00967
00968 SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
00969 break;
00970 }
00971
00972 default: case loop_type_normal: {
00973 do {
00974
00975 if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
00976 samplestoloopend = loopEnd - GetPos();
00977 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
00978 samplestoread -= readsamples;
00979 totalreadsamples += readsamples;
00980 if (readsamples == samplestoloopend) {
00981 pPlaybackState->loop_cycles_left--;
00982 SetPos(loop.LoopStart);
00983 }
00984 } while (samplestoread && readsamples);
00985 break;
00986 }
00987 }
00988 }
00989 }
00990
00991
00992 if (samplestoread) do {
00993 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
00994 samplestoread -= readsamples;
00995 totalreadsamples += readsamples;
00996 } while (readsamples && samplestoread);
00997
00998
00999 pPlaybackState->position = GetPos();
01000
01001 return totalreadsamples;
01002 }
01003
01026 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
01027 if (SampleCount == 0) return 0;
01028 if (!Compressed) {
01029 if (BitDepth == 24) {
01030 return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
01031 }
01032 else {
01033
01034 return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
01035 : pCkData->Read(pBuffer, SampleCount, 2);
01036 }
01037 }
01038 else {
01039 if (this->SamplePos >= this->SamplesTotal) return 0;
01040
01041 unsigned long assumedsize = GuessSize(SampleCount),
01042 remainingbytes = 0,
01043 remainingsamples = SampleCount,
01044 copysamples, skipsamples,
01045 currentframeoffset = this->FrameOffset;
01046 this->FrameOffset = 0;
01047
01048 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
01049
01050
01051 if (pDecompressionBuffer->Size < assumedsize) {
01052 std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
01053 SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
01054 remainingsamples = SampleCount;
01055 assumedsize = GuessSize(SampleCount);
01056 }
01057
01058 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
01059 int16_t* pDst = static_cast<int16_t*>(pBuffer);
01060 uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
01061 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
01062
01063 while (remainingsamples && remainingbytes) {
01064 unsigned long framesamples = SamplesPerFrame;
01065 unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
01066
01067 int mode_l = *pSrc++, mode_r = 0;
01068
01069 if (Channels == 2) {
01070 mode_r = *pSrc++;
01071 framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
01072 rightChannelOffset = bytesPerFrameNoHdr[mode_l];
01073 nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
01074 if (remainingbytes < framebytes) {
01075 framesamples = SamplesInLastFrame;
01076 if (mode_l == 4 && (framesamples & 1)) {
01077 rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
01078 }
01079 else {
01080 rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
01081 }
01082 }
01083 }
01084 else {
01085 framebytes = bytesPerFrame[mode_l] + 1;
01086 nextFrameOffset = bytesPerFrameNoHdr[mode_l];
01087 if (remainingbytes < framebytes) {
01088 framesamples = SamplesInLastFrame;
01089 }
01090 }
01091
01092
01093 if (currentframeoffset + remainingsamples >= framesamples) {
01094 if (currentframeoffset <= framesamples) {
01095 copysamples = framesamples - currentframeoffset;
01096 skipsamples = currentframeoffset;
01097 }
01098 else {
01099 copysamples = 0;
01100 skipsamples = framesamples;
01101 }
01102 }
01103 else {
01104
01105
01106
01107 copysamples = remainingsamples;
01108 skipsamples = currentframeoffset;
01109 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
01110 this->FrameOffset = currentframeoffset + copysamples;
01111 }
01112 remainingsamples -= copysamples;
01113
01114 if (remainingbytes > framebytes) {
01115 remainingbytes -= framebytes;
01116 if (remainingsamples == 0 &&
01117 currentframeoffset + copysamples == framesamples) {
01118
01119
01120
01121
01122 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
01123 }
01124 }
01125 else remainingbytes = 0;
01126
01127 currentframeoffset -= skipsamples;
01128
01129 if (copysamples == 0) {
01130
01131 pSrc += framebytes - Channels;
01132 }
01133 else {
01134 const unsigned char* const param_l = pSrc;
01135 if (BitDepth == 24) {
01136 if (mode_l != 2) pSrc += 12;
01137
01138 if (Channels == 2) {
01139 const unsigned char* const param_r = pSrc;
01140 if (mode_r != 2) pSrc += 12;
01141
01142 Decompress24(mode_l, param_l, 6, pSrc, pDst24,
01143 skipsamples, copysamples, TruncatedBits);
01144 Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
01145 skipsamples, copysamples, TruncatedBits);
01146 pDst24 += copysamples * 6;
01147 }
01148 else {
01149 Decompress24(mode_l, param_l, 3, pSrc, pDst24,
01150 skipsamples, copysamples, TruncatedBits);
01151 pDst24 += copysamples * 3;
01152 }
01153 }
01154 else {
01155 if (mode_l) pSrc += 4;
01156
01157 int step;
01158 if (Channels == 2) {
01159 const unsigned char* const param_r = pSrc;
01160 if (mode_r) pSrc += 4;
01161
01162 step = (2 - mode_l) + (2 - mode_r);
01163 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
01164 Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
01165 skipsamples, copysamples);
01166 pDst += copysamples << 1;
01167 }
01168 else {
01169 step = 2 - mode_l;
01170 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
01171 pDst += copysamples;
01172 }
01173 }
01174 pSrc += nextFrameOffset;
01175 }
01176
01177
01178 if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
01179 assumedsize = GuessSize(remainingsamples);
01180 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
01181 if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
01182 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
01183 pSrc = (unsigned char*) pDecompressionBuffer->pStart;
01184 }
01185 }
01186
01187 this->SamplePos += (SampleCount - remainingsamples);
01188 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
01189 return (SampleCount - remainingsamples);
01190 }
01191 }
01192
01215 unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
01216 if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
01217
01218
01219
01220 if (pCkData->GetPos() == 0) {
01221 __resetCRC(crc);
01222 }
01223 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
01224 unsigned long res;
01225 if (BitDepth == 24) {
01226 res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
01227 } else {
01228 res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
01229 : pCkData->Write(pBuffer, SampleCount, 2);
01230 }
01231 __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
01232
01233
01234
01235 if (pCkData->GetPos() == pCkData->GetSize()) {
01236 File* pFile = static_cast<File*>(GetParent());
01237 pFile->SetSampleChecksum(this, __encodeCRC(crc));
01238 }
01239 return res;
01240 }
01241
01258 buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
01259 buffer_t result;
01260 const double worstCaseHeaderOverhead =
01261 (256.0 + 12.0 + 2.0 ) / 256.0;
01262 result.Size = (unsigned long) (double(MaxReadSize) * 3.0 * 2.0 * worstCaseHeaderOverhead);
01263 result.pStart = new int8_t[result.Size];
01264 result.NullExtensionSize = 0;
01265 return result;
01266 }
01267
01275 void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
01276 if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
01277 delete[] (int8_t*) DecompressionBuffer.pStart;
01278 DecompressionBuffer.pStart = NULL;
01279 DecompressionBuffer.Size = 0;
01280 DecompressionBuffer.NullExtensionSize = 0;
01281 }
01282 }
01283
01292 Group* Sample::GetGroup() const {
01293 return pGroup;
01294 }
01295
01296 Sample::~Sample() {
01297 Instances--;
01298 if (!Instances && InternalDecompressionBuffer.Size) {
01299 delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
01300 InternalDecompressionBuffer.pStart = NULL;
01301 InternalDecompressionBuffer.Size = 0;
01302 }
01303 if (FrameTable) delete[] FrameTable;
01304 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
01305 }
01306
01307
01308
01309
01310
01311
01312 uint DimensionRegion::Instances = 0;
01313 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
01314
01315 DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
01316 Instances++;
01317
01318 pSample = NULL;
01319 pRegion = pParent;
01320
01321 if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
01322 else memset(&Crossfade, 0, 4);
01323
01324 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
01325
01326 RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
01327 if (_3ewa) {
01328 _3ewa->ReadInt32();
01329 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01330 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01331 _3ewa->ReadInt16();
01332 LFO1InternalDepth = _3ewa->ReadUint16();
01333 _3ewa->ReadInt16();
01334 LFO3InternalDepth = _3ewa->ReadInt16();
01335 _3ewa->ReadInt16();
01336 LFO1ControlDepth = _3ewa->ReadUint16();
01337 _3ewa->ReadInt16();
01338 LFO3ControlDepth = _3ewa->ReadInt16();
01339 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01340 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01341 _3ewa->ReadInt16();
01342 EG1Sustain = _3ewa->ReadUint16();
01343 EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01344 EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
01345 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
01346 EG1ControllerInvert = eg1ctrloptions & 0x01;
01347 EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
01348 EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
01349 EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
01350 EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
01351 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
01352 EG2ControllerInvert = eg2ctrloptions & 0x01;
01353 EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
01354 EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
01355 EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
01356 LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01357 EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01358 EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01359 _3ewa->ReadInt16();
01360 EG2Sustain = _3ewa->ReadUint16();
01361 EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01362 _3ewa->ReadInt16();
01363 LFO2ControlDepth = _3ewa->ReadUint16();
01364 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
01365 _3ewa->ReadInt16();
01366 LFO2InternalDepth = _3ewa->ReadUint16();
01367 int32_t eg1decay2 = _3ewa->ReadInt32();
01368 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
01369 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
01370 _3ewa->ReadInt16();
01371 EG1PreAttack = _3ewa->ReadUint16();
01372 int32_t eg2decay2 = _3ewa->ReadInt32();
01373 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
01374 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
01375 _3ewa->ReadInt16();
01376 EG2PreAttack = _3ewa->ReadUint16();
01377 uint8_t velocityresponse = _3ewa->ReadUint8();
01378 if (velocityresponse < 5) {
01379 VelocityResponseCurve = curve_type_nonlinear;
01380 VelocityResponseDepth = velocityresponse;
01381 } else if (velocityresponse < 10) {
01382 VelocityResponseCurve = curve_type_linear;
01383 VelocityResponseDepth = velocityresponse - 5;
01384 } else if (velocityresponse < 15) {
01385 VelocityResponseCurve = curve_type_special;
01386 VelocityResponseDepth = velocityresponse - 10;
01387 } else {
01388 VelocityResponseCurve = curve_type_unknown;
01389 VelocityResponseDepth = 0;
01390 }
01391 uint8_t releasevelocityresponse = _3ewa->ReadUint8();
01392 if (releasevelocityresponse < 5) {
01393 ReleaseVelocityResponseCurve = curve_type_nonlinear;
01394 ReleaseVelocityResponseDepth = releasevelocityresponse;
01395 } else if (releasevelocityresponse < 10) {
01396 ReleaseVelocityResponseCurve = curve_type_linear;
01397 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
01398 } else if (releasevelocityresponse < 15) {
01399 ReleaseVelocityResponseCurve = curve_type_special;
01400 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
01401 } else {
01402 ReleaseVelocityResponseCurve = curve_type_unknown;
01403 ReleaseVelocityResponseDepth = 0;
01404 }
01405 VelocityResponseCurveScaling = _3ewa->ReadUint8();
01406 AttenuationControllerThreshold = _3ewa->ReadInt8();
01407 _3ewa->ReadInt32();
01408 SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
01409 _3ewa->ReadInt16();
01410 uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
01411 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
01412 if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
01413 else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
01414 else DimensionBypass = dim_bypass_ctrl_none;
01415 uint8_t pan = _3ewa->ReadUint8();
01416 Pan = (pan < 64) ? pan : -((int)pan - 63);
01417 SelfMask = _3ewa->ReadInt8() & 0x01;
01418 _3ewa->ReadInt8();
01419 uint8_t lfo3ctrl = _3ewa->ReadUint8();
01420 LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07);
01421 LFO3Sync = lfo3ctrl & 0x20;
01422 InvertAttenuationController = lfo3ctrl & 0x80;
01423 AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
01424 uint8_t lfo2ctrl = _3ewa->ReadUint8();
01425 LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07);
01426 LFO2FlipPhase = lfo2ctrl & 0x80;
01427 LFO2Sync = lfo2ctrl & 0x20;
01428 bool extResonanceCtrl = lfo2ctrl & 0x40;
01429 uint8_t lfo1ctrl = _3ewa->ReadUint8();
01430 LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07);
01431 LFO1FlipPhase = lfo1ctrl & 0x80;
01432 LFO1Sync = lfo1ctrl & 0x40;
01433 VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
01434 : vcf_res_ctrl_none;
01435 uint16_t eg3depth = _3ewa->ReadUint16();
01436 EG3Depth = (eg3depth <= 1200) ? eg3depth
01437 : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1);
01438 _3ewa->ReadInt16();
01439 ChannelOffset = _3ewa->ReadUint8() / 4;
01440 uint8_t regoptions = _3ewa->ReadUint8();
01441 MSDecode = regoptions & 0x01;
01442 SustainDefeat = regoptions & 0x02;
01443 _3ewa->ReadInt16();
01444 VelocityUpperLimit = _3ewa->ReadInt8();
01445 _3ewa->ReadInt8();
01446 _3ewa->ReadInt16();
01447 ReleaseTriggerDecay = _3ewa->ReadUint8();
01448 _3ewa->ReadInt8();
01449 _3ewa->ReadInt8();
01450 EG1Hold = _3ewa->ReadUint8() & 0x80;
01451 uint8_t vcfcutoff = _3ewa->ReadUint8();
01452 VCFEnabled = vcfcutoff & 0x80;
01453 VCFCutoff = vcfcutoff & 0x7f;
01454 VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
01455 uint8_t vcfvelscale = _3ewa->ReadUint8();
01456 VCFCutoffControllerInvert = vcfvelscale & 0x80;
01457 VCFVelocityScale = vcfvelscale & 0x7f;
01458 _3ewa->ReadInt8();
01459 uint8_t vcfresonance = _3ewa->ReadUint8();
01460 VCFResonance = vcfresonance & 0x7f;
01461 VCFResonanceDynamic = !(vcfresonance & 0x80);
01462 uint8_t vcfbreakpoint = _3ewa->ReadUint8();
01463 VCFKeyboardTracking = vcfbreakpoint & 0x80;
01464 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f;
01465 uint8_t vcfvelocity = _3ewa->ReadUint8();
01466 VCFVelocityDynamicRange = vcfvelocity % 5;
01467 VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
01468 VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
01469 if (VCFType == vcf_type_lowpass) {
01470 if (lfo3ctrl & 0x40)
01471 VCFType = vcf_type_lowpassturbo;
01472 }
01473 if (_3ewa->RemainingBytes() >= 8) {
01474 _3ewa->Read(DimensionUpperLimits, 1, 8);
01475 } else {
01476 memset(DimensionUpperLimits, 0, 8);
01477 }
01478 } else {
01479
01480 LFO3Frequency = 1.0;
01481 EG3Attack = 0.0;
01482 LFO1InternalDepth = 0;
01483 LFO3InternalDepth = 0;
01484 LFO1ControlDepth = 0;
01485 LFO3ControlDepth = 0;
01486 EG1Attack = 0.0;
01487 EG1Decay1 = 0.005;
01488 EG1Sustain = 1000;
01489 EG1Release = 0.3;
01490 EG1Controller.type = eg1_ctrl_t::type_none;
01491 EG1Controller.controller_number = 0;
01492 EG1ControllerInvert = false;
01493 EG1ControllerAttackInfluence = 0;
01494 EG1ControllerDecayInfluence = 0;
01495 EG1ControllerReleaseInfluence = 0;
01496 EG2Controller.type = eg2_ctrl_t::type_none;
01497 EG2Controller.controller_number = 0;
01498 EG2ControllerInvert = false;
01499 EG2ControllerAttackInfluence = 0;
01500 EG2ControllerDecayInfluence = 0;
01501 EG2ControllerReleaseInfluence = 0;
01502 LFO1Frequency = 1.0;
01503 EG2Attack = 0.0;
01504 EG2Decay1 = 0.005;
01505 EG2Sustain = 1000;
01506 EG2Release = 0.3;
01507 LFO2ControlDepth = 0;
01508 LFO2Frequency = 1.0;
01509 LFO2InternalDepth = 0;
01510 EG1Decay2 = 0.0;
01511 EG1InfiniteSustain = true;
01512 EG1PreAttack = 0;
01513 EG2Decay2 = 0.0;
01514 EG2InfiniteSustain = true;
01515 EG2PreAttack = 0;
01516 VelocityResponseCurve = curve_type_nonlinear;
01517 VelocityResponseDepth = 3;
01518 ReleaseVelocityResponseCurve = curve_type_nonlinear;
01519 ReleaseVelocityResponseDepth = 3;
01520 VelocityResponseCurveScaling = 32;
01521 AttenuationControllerThreshold = 0;
01522 SampleStartOffset = 0;
01523 PitchTrack = true;
01524 DimensionBypass = dim_bypass_ctrl_none;
01525 Pan = 0;
01526 SelfMask = true;
01527 LFO3Controller = lfo3_ctrl_modwheel;
01528 LFO3Sync = false;
01529 InvertAttenuationController = false;
01530 AttenuationController.type = attenuation_ctrl_t::type_none;
01531 AttenuationController.controller_number = 0;
01532 LFO2Controller = lfo2_ctrl_internal;
01533 LFO2FlipPhase = false;
01534 LFO2Sync = false;
01535 LFO1Controller = lfo1_ctrl_internal;
01536 LFO1FlipPhase = false;
01537 LFO1Sync = false;
01538 VCFResonanceController = vcf_res_ctrl_none;
01539 EG3Depth = 0;
01540 ChannelOffset = 0;
01541 MSDecode = false;
01542 SustainDefeat = false;
01543 VelocityUpperLimit = 0;
01544 ReleaseTriggerDecay = 0;
01545 EG1Hold = false;
01546 VCFEnabled = false;
01547 VCFCutoff = 0;
01548 VCFCutoffController = vcf_cutoff_ctrl_none;
01549 VCFCutoffControllerInvert = false;
01550 VCFVelocityScale = 0;
01551 VCFResonance = 0;
01552 VCFResonanceDynamic = false;
01553 VCFKeyboardTracking = false;
01554 VCFKeyboardTrackingBreakpoint = 0;
01555 VCFVelocityDynamicRange = 0x04;
01556 VCFVelocityCurve = curve_type_linear;
01557 VCFType = vcf_type_lowpass;
01558 memset(DimensionUpperLimits, 127, 8);
01559 }
01560
01561 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
01562 VelocityResponseDepth,
01563 VelocityResponseCurveScaling);
01564
01565 pVelocityReleaseTable = GetReleaseVelocityTable(
01566 ReleaseVelocityResponseCurve,
01567 ReleaseVelocityResponseDepth
01568 );
01569
01570 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
01571 VCFVelocityDynamicRange,
01572 VCFVelocityScale,
01573 VCFCutoffController);
01574
01575 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
01576 VelocityTable = 0;
01577 }
01578
01579
01580
01581
01582
01583 DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
01584 Instances++;
01585 *this = src;
01586 pParentList = _3ewl;
01587
01588
01589 if (src.VelocityTable) {
01590 VelocityTable = new uint8_t[128];
01591 for (int k = 0 ; k < 128 ; k++)
01592 VelocityTable[k] = src.VelocityTable[k];
01593 }
01594 if (src.pSampleLoops) {
01595 pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
01596 for (int k = 0 ; k < src.SampleLoops ; k++)
01597 pSampleLoops[k] = src.pSampleLoops[k];
01598 }
01599 }
01600
01605 void DimensionRegion::SetGain(int32_t gain) {
01606 DLS::Sampler::SetGain(gain);
01607 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
01608 }
01609
01617 void DimensionRegion::UpdateChunks() {
01618
01619 DLS::Sampler::UpdateChunks();
01620
01621 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
01622 uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
01623 pData[12] = Crossfade.in_start;
01624 pData[13] = Crossfade.in_end;
01625 pData[14] = Crossfade.out_start;
01626 pData[15] = Crossfade.out_end;
01627
01628
01629 RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
01630 if (!_3ewa) {
01631 File* pFile = (File*) GetParent()->GetParent()->GetParent();
01632 bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
01633 _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
01634 }
01635 pData = (uint8_t*) _3ewa->LoadChunkData();
01636
01637
01638
01639 const uint32_t chunksize = _3ewa->GetNewSize();
01640 store32(&pData[0], chunksize);
01641
01642 const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
01643 store32(&pData[4], lfo3freq);
01644
01645 const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
01646 store32(&pData[8], eg3attack);
01647
01648
01649
01650 store16(&pData[14], LFO1InternalDepth);
01651
01652
01653
01654 store16(&pData[18], LFO3InternalDepth);
01655
01656
01657
01658 store16(&pData[22], LFO1ControlDepth);
01659
01660
01661
01662 store16(&pData[26], LFO3ControlDepth);
01663
01664 const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
01665 store32(&pData[28], eg1attack);
01666
01667 const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
01668 store32(&pData[32], eg1decay1);
01669
01670
01671
01672 store16(&pData[38], EG1Sustain);
01673
01674 const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
01675 store32(&pData[40], eg1release);
01676
01677 const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
01678 pData[44] = eg1ctl;
01679
01680 const uint8_t eg1ctrloptions =
01681 (EG1ControllerInvert ? 0x01 : 0x00) |
01682 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
01683 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
01684 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
01685 pData[45] = eg1ctrloptions;
01686
01687 const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
01688 pData[46] = eg2ctl;
01689
01690 const uint8_t eg2ctrloptions =
01691 (EG2ControllerInvert ? 0x01 : 0x00) |
01692 GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
01693 GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
01694 GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
01695 pData[47] = eg2ctrloptions;
01696
01697 const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
01698 store32(&pData[48], lfo1freq);
01699
01700 const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
01701 store32(&pData[52], eg2attack);
01702
01703 const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
01704 store32(&pData[56], eg2decay1);
01705
01706
01707
01708 store16(&pData[62], EG2Sustain);
01709
01710 const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
01711 store32(&pData[64], eg2release);
01712
01713
01714
01715 store16(&pData[70], LFO2ControlDepth);
01716
01717 const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
01718 store32(&pData[72], lfo2freq);
01719
01720
01721
01722 store16(&pData[78], LFO2InternalDepth);
01723
01724 const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
01725 store32(&pData[80], eg1decay2);
01726
01727
01728
01729 store16(&pData[86], EG1PreAttack);
01730
01731 const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
01732 store32(&pData[88], eg2decay2);
01733
01734
01735
01736 store16(&pData[94], EG2PreAttack);
01737
01738 {
01739 if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
01740 uint8_t velocityresponse = VelocityResponseDepth;
01741 switch (VelocityResponseCurve) {
01742 case curve_type_nonlinear:
01743 break;
01744 case curve_type_linear:
01745 velocityresponse += 5;
01746 break;
01747 case curve_type_special:
01748 velocityresponse += 10;
01749 break;
01750 case curve_type_unknown:
01751 default:
01752 throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
01753 }
01754 pData[96] = velocityresponse;
01755 }
01756
01757 {
01758 if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
01759 uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
01760 switch (ReleaseVelocityResponseCurve) {
01761 case curve_type_nonlinear:
01762 break;
01763 case curve_type_linear:
01764 releasevelocityresponse += 5;
01765 break;
01766 case curve_type_special:
01767 releasevelocityresponse += 10;
01768 break;
01769 case curve_type_unknown:
01770 default:
01771 throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
01772 }
01773 pData[97] = releasevelocityresponse;
01774 }
01775
01776 pData[98] = VelocityResponseCurveScaling;
01777
01778 pData[99] = AttenuationControllerThreshold;
01779
01780
01781
01782 store16(&pData[104], SampleStartOffset);
01783
01784
01785
01786 {
01787 uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
01788 switch (DimensionBypass) {
01789 case dim_bypass_ctrl_94:
01790 pitchTrackDimensionBypass |= 0x10;
01791 break;
01792 case dim_bypass_ctrl_95:
01793 pitchTrackDimensionBypass |= 0x20;
01794 break;
01795 case dim_bypass_ctrl_none:
01796
01797 break;
01798 default:
01799 throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
01800 }
01801 pData[108] = pitchTrackDimensionBypass;
01802 }
01803
01804 const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63);
01805 pData[109] = pan;
01806
01807 const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
01808 pData[110] = selfmask;
01809
01810
01811
01812 {
01813 uint8_t lfo3ctrl = LFO3Controller & 0x07;
01814 if (LFO3Sync) lfo3ctrl |= 0x20;
01815 if (InvertAttenuationController) lfo3ctrl |= 0x80;
01816 if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40;
01817 pData[112] = lfo3ctrl;
01818 }
01819
01820 const uint8_t attenctl = EncodeLeverageController(AttenuationController);
01821 pData[113] = attenctl;
01822
01823 {
01824 uint8_t lfo2ctrl = LFO2Controller & 0x07;
01825 if (LFO2FlipPhase) lfo2ctrl |= 0x80;
01826 if (LFO2Sync) lfo2ctrl |= 0x20;
01827 if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40;
01828 pData[114] = lfo2ctrl;
01829 }
01830
01831 {
01832 uint8_t lfo1ctrl = LFO1Controller & 0x07;
01833 if (LFO1FlipPhase) lfo1ctrl |= 0x80;
01834 if (LFO1Sync) lfo1ctrl |= 0x40;
01835 if (VCFResonanceController != vcf_res_ctrl_none)
01836 lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
01837 pData[115] = lfo1ctrl;
01838 }
01839
01840 const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
01841 : uint16_t(((-EG3Depth) - 1) ^ 0xffff);
01842 store16(&pData[116], eg3depth);
01843
01844
01845
01846 const uint8_t channeloffset = ChannelOffset * 4;
01847 pData[120] = channeloffset;
01848
01849 {
01850 uint8_t regoptions = 0;
01851 if (MSDecode) regoptions |= 0x01;
01852 if (SustainDefeat) regoptions |= 0x02;
01853 pData[121] = regoptions;
01854 }
01855
01856
01857
01858 pData[124] = VelocityUpperLimit;
01859
01860
01861
01862 pData[128] = ReleaseTriggerDecay;
01863
01864
01865
01866 const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00;
01867 pData[131] = eg1hold;
01868
01869 const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |
01870 (VCFCutoff & 0x7f);
01871 pData[132] = vcfcutoff;
01872
01873 pData[133] = VCFCutoffController;
01874
01875 const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) |
01876 (VCFVelocityScale & 0x7f);
01877 pData[134] = vcfvelscale;
01878
01879
01880
01881 const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) |
01882 (VCFResonance & 0x7f);
01883 pData[136] = vcfresonance;
01884
01885 const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) |
01886 (VCFKeyboardTrackingBreakpoint & 0x7f);
01887 pData[137] = vcfbreakpoint;
01888
01889 const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
01890 VCFVelocityCurve * 5;
01891 pData[138] = vcfvelocity;
01892
01893 const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
01894 pData[139] = vcftype;
01895
01896 if (chunksize >= 148) {
01897 memcpy(&pData[140], DimensionUpperLimits, 8);
01898 }
01899 }
01900
01901 double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
01902 curve_type_t curveType = releaseVelocityResponseCurve;
01903 uint8_t depth = releaseVelocityResponseDepth;
01904
01905
01906
01907 if ((curveType == curve_type_nonlinear && depth == 0) ||
01908 (curveType == curve_type_special && depth == 4)) {
01909 curveType = curve_type_nonlinear;
01910 depth = 3;
01911 }
01912 return GetVelocityTable(curveType, depth, 0);
01913 }
01914
01915 double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
01916 uint8_t vcfVelocityDynamicRange,
01917 uint8_t vcfVelocityScale,
01918 vcf_cutoff_ctrl_t vcfCutoffController)
01919 {
01920 curve_type_t curveType = vcfVelocityCurve;
01921 uint8_t depth = vcfVelocityDynamicRange;
01922
01923
01924
01925 if ((curveType == curve_type_nonlinear && depth == 0) ||
01926 (curveType == curve_type_special && depth == 4)) {
01927 curveType = curve_type_special;
01928 depth = 5;
01929 }
01930 return GetVelocityTable(curveType, depth,
01931 (vcfCutoffController <= vcf_cutoff_ctrl_none2)
01932 ? vcfVelocityScale : 0);
01933 }
01934
01935
01936 double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
01937 {
01938 double* table;
01939 uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
01940 if (pVelocityTables->count(tableKey)) {
01941 table = (*pVelocityTables)[tableKey];
01942 }
01943 else {
01944 table = CreateVelocityTable(curveType, depth, scaling);
01945 (*pVelocityTables)[tableKey] = table;
01946 }
01947 return table;
01948 }
01949
01950 Region* DimensionRegion::GetParent() const {
01951 return pRegion;
01952 }
01953
01954 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
01955 leverage_ctrl_t decodedcontroller;
01956 switch (EncodedController) {
01957
01958 case _lev_ctrl_none:
01959 decodedcontroller.type = leverage_ctrl_t::type_none;
01960 decodedcontroller.controller_number = 0;
01961 break;
01962 case _lev_ctrl_velocity:
01963 decodedcontroller.type = leverage_ctrl_t::type_velocity;
01964 decodedcontroller.controller_number = 0;
01965 break;
01966 case _lev_ctrl_channelaftertouch:
01967 decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
01968 decodedcontroller.controller_number = 0;
01969 break;
01970
01971
01972 case _lev_ctrl_modwheel:
01973 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01974 decodedcontroller.controller_number = 1;
01975 break;
01976 case _lev_ctrl_breath:
01977 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01978 decodedcontroller.controller_number = 2;
01979 break;
01980 case _lev_ctrl_foot:
01981 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01982 decodedcontroller.controller_number = 4;
01983 break;
01984 case _lev_ctrl_effect1:
01985 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01986 decodedcontroller.controller_number = 12;
01987 break;
01988 case _lev_ctrl_effect2:
01989 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01990 decodedcontroller.controller_number = 13;
01991 break;
01992 case _lev_ctrl_genpurpose1:
01993 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01994 decodedcontroller.controller_number = 16;
01995 break;
01996 case _lev_ctrl_genpurpose2:
01997 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
01998 decodedcontroller.controller_number = 17;
01999 break;
02000 case _lev_ctrl_genpurpose3:
02001 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02002 decodedcontroller.controller_number = 18;
02003 break;
02004 case _lev_ctrl_genpurpose4:
02005 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02006 decodedcontroller.controller_number = 19;
02007 break;
02008 case _lev_ctrl_portamentotime:
02009 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02010 decodedcontroller.controller_number = 5;
02011 break;
02012 case _lev_ctrl_sustainpedal:
02013 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02014 decodedcontroller.controller_number = 64;
02015 break;
02016 case _lev_ctrl_portamento:
02017 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02018 decodedcontroller.controller_number = 65;
02019 break;
02020 case _lev_ctrl_sostenutopedal:
02021 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02022 decodedcontroller.controller_number = 66;
02023 break;
02024 case _lev_ctrl_softpedal:
02025 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02026 decodedcontroller.controller_number = 67;
02027 break;
02028 case _lev_ctrl_genpurpose5:
02029 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02030 decodedcontroller.controller_number = 80;
02031 break;
02032 case _lev_ctrl_genpurpose6:
02033 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02034 decodedcontroller.controller_number = 81;
02035 break;
02036 case _lev_ctrl_genpurpose7:
02037 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02038 decodedcontroller.controller_number = 82;
02039 break;
02040 case _lev_ctrl_genpurpose8:
02041 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02042 decodedcontroller.controller_number = 83;
02043 break;
02044 case _lev_ctrl_effect1depth:
02045 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02046 decodedcontroller.controller_number = 91;
02047 break;
02048 case _lev_ctrl_effect2depth:
02049 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02050 decodedcontroller.controller_number = 92;
02051 break;
02052 case _lev_ctrl_effect3depth:
02053 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02054 decodedcontroller.controller_number = 93;
02055 break;
02056 case _lev_ctrl_effect4depth:
02057 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02058 decodedcontroller.controller_number = 94;
02059 break;
02060 case _lev_ctrl_effect5depth:
02061 decodedcontroller.type = leverage_ctrl_t::type_controlchange;
02062 decodedcontroller.controller_number = 95;
02063 break;
02064
02065
02066 default:
02067 throw gig::Exception("Unknown leverage controller type.");
02068 }
02069 return decodedcontroller;
02070 }
02071
02072 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
02073 _lev_ctrl_t encodedcontroller;
02074 switch (DecodedController.type) {
02075
02076 case leverage_ctrl_t::type_none:
02077 encodedcontroller = _lev_ctrl_none;
02078 break;
02079 case leverage_ctrl_t::type_velocity:
02080 encodedcontroller = _lev_ctrl_velocity;
02081 break;
02082 case leverage_ctrl_t::type_channelaftertouch:
02083 encodedcontroller = _lev_ctrl_channelaftertouch;
02084 break;
02085
02086
02087 case leverage_ctrl_t::type_controlchange:
02088 switch (DecodedController.controller_number) {
02089 case 1:
02090 encodedcontroller = _lev_ctrl_modwheel;
02091 break;
02092 case 2:
02093 encodedcontroller = _lev_ctrl_breath;
02094 break;
02095 case 4:
02096 encodedcontroller = _lev_ctrl_foot;
02097 break;
02098 case 12:
02099 encodedcontroller = _lev_ctrl_effect1;
02100 break;
02101 case 13:
02102 encodedcontroller = _lev_ctrl_effect2;
02103 break;
02104 case 16:
02105 encodedcontroller = _lev_ctrl_genpurpose1;
02106 break;
02107 case 17:
02108 encodedcontroller = _lev_ctrl_genpurpose2;
02109 break;
02110 case 18:
02111 encodedcontroller = _lev_ctrl_genpurpose3;
02112 break;
02113 case 19:
02114 encodedcontroller = _lev_ctrl_genpurpose4;
02115 break;
02116 case 5:
02117 encodedcontroller = _lev_ctrl_portamentotime;
02118 break;
02119 case 64:
02120 encodedcontroller = _lev_ctrl_sustainpedal;
02121 break;
02122 case 65:
02123 encodedcontroller = _lev_ctrl_portamento;
02124 break;
02125 case 66:
02126 encodedcontroller = _lev_ctrl_sostenutopedal;
02127 break;
02128 case 67:
02129 encodedcontroller = _lev_ctrl_softpedal;
02130 break;
02131 case 80:
02132 encodedcontroller = _lev_ctrl_genpurpose5;
02133 break;
02134 case 81:
02135 encodedcontroller = _lev_ctrl_genpurpose6;
02136 break;
02137 case 82:
02138 encodedcontroller = _lev_ctrl_genpurpose7;
02139 break;
02140 case 83:
02141 encodedcontroller = _lev_ctrl_genpurpose8;
02142 break;
02143 case 91:
02144 encodedcontroller = _lev_ctrl_effect1depth;
02145 break;
02146 case 92:
02147 encodedcontroller = _lev_ctrl_effect2depth;
02148 break;
02149 case 93:
02150 encodedcontroller = _lev_ctrl_effect3depth;
02151 break;
02152 case 94:
02153 encodedcontroller = _lev_ctrl_effect4depth;
02154 break;
02155 case 95:
02156 encodedcontroller = _lev_ctrl_effect5depth;
02157 break;
02158 default:
02159 throw gig::Exception("leverage controller number is not supported by the gig format");
02160 }
02161 break;
02162 default:
02163 throw gig::Exception("Unknown leverage controller type.");
02164 }
02165 return encodedcontroller;
02166 }
02167
02168 DimensionRegion::~DimensionRegion() {
02169 Instances--;
02170 if (!Instances) {
02171
02172 VelocityTableMap::iterator iter;
02173 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
02174 double* pTable = iter->second;
02175 if (pTable) delete[] pTable;
02176 }
02177 pVelocityTables->clear();
02178 delete pVelocityTables;
02179 pVelocityTables = NULL;
02180 }
02181 if (VelocityTable) delete[] VelocityTable;
02182 }
02183
02195 double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
02196 return pVelocityAttenuationTable[MIDIKeyVelocity];
02197 }
02198
02199 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
02200 return pVelocityReleaseTable[MIDIKeyVelocity];
02201 }
02202
02203 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
02204 return pVelocityCutoffTable[MIDIKeyVelocity];
02205 }
02206
02211 void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
02212 pVelocityAttenuationTable =
02213 GetVelocityTable(
02214 curve, VelocityResponseDepth, VelocityResponseCurveScaling
02215 );
02216 VelocityResponseCurve = curve;
02217 }
02218
02223 void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
02224 pVelocityAttenuationTable =
02225 GetVelocityTable(
02226 VelocityResponseCurve, depth, VelocityResponseCurveScaling
02227 );
02228 VelocityResponseDepth = depth;
02229 }
02230
02235 void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
02236 pVelocityAttenuationTable =
02237 GetVelocityTable(
02238 VelocityResponseCurve, VelocityResponseDepth, scaling
02239 );
02240 VelocityResponseCurveScaling = scaling;
02241 }
02242
02247 void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
02248 pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
02249 ReleaseVelocityResponseCurve = curve;
02250 }
02251
02256 void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
02257 pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
02258 ReleaseVelocityResponseDepth = depth;
02259 }
02260
02265 void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
02266 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
02267 VCFCutoffController = controller;
02268 }
02269
02274 void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
02275 pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
02276 VCFVelocityCurve = curve;
02277 }
02278
02283 void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
02284 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
02285 VCFVelocityDynamicRange = range;
02286 }
02287
02292 void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
02293 pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
02294 VCFVelocityScale = scaling;
02295 }
02296
02297 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
02298
02299
02300
02301
02302 const int lin0[] = { 1, 1, 127, 127 };
02303 const int lin1[] = { 1, 21, 127, 127 };
02304 const int lin2[] = { 1, 45, 127, 127 };
02305 const int lin3[] = { 1, 74, 127, 127 };
02306 const int lin4[] = { 1, 127, 127, 127 };
02307
02308
02309 const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
02310 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
02311 127, 127 };
02312 const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
02313 127, 127 };
02314 const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
02315 127, 127 };
02316 const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
02317
02318
02319 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
02320 113, 127, 127, 127 };
02321 const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
02322 118, 127, 127, 127 };
02323 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
02324 85, 90, 91, 127, 127, 127 };
02325 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
02326 117, 127, 127, 127 };
02327 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
02328 127, 127 };
02329
02330
02331 const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
02332 91, 127, 127, 127 };
02333
02334 const int* const curves[] = { non0, non1, non2, non3, non4,
02335 lin0, lin1, lin2, lin3, lin4,
02336 spe0, spe1, spe2, spe3, spe4, spe5 };
02337
02338 double* const table = new double[128];
02339
02340 const int* curve = curves[curveType * 5 + depth];
02341 const int s = scaling == 0 ? 20 : scaling;
02342
02343 table[0] = 0;
02344 for (int x = 1 ; x < 128 ; x++) {
02345
02346 if (x > curve[2]) curve += 2;
02347 double y = curve[1] + (x - curve[0]) *
02348 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
02349 y = y / 127;
02350
02351
02352
02353 if (s < 20 && y >= 0.5)
02354 y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
02355 else
02356 y = y * (s / 20.0);
02357 if (y > 1) y = 1;
02358
02359 table[x] = y;
02360 }
02361 return table;
02362 }
02363
02364
02365
02366
02367
02368 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
02369
02370 Dimensions = 0;
02371 for (int i = 0; i < 256; i++) {
02372 pDimensionRegions[i] = NULL;
02373 }
02374 Layers = 1;
02375 File* file = (File*) GetParent()->GetParent();
02376 int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
02377
02378
02379
02380 if (!file->GetAutoLoad()) return;
02381
02382 LoadDimensionRegions(rgnList);
02383
02384 RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
02385 if (_3lnk) {
02386 DimensionRegions = _3lnk->ReadUint32();
02387 for (int i = 0; i < dimensionBits; i++) {
02388 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
02389 uint8_t bits = _3lnk->ReadUint8();
02390 _3lnk->ReadUint8();
02391 _3lnk->ReadUint8();
02392 uint8_t zones = _3lnk->ReadUint8();
02393 if (dimension == dimension_none) {
02394 pDimensionDefinitions[i].dimension = dimension_none;
02395 pDimensionDefinitions[i].bits = 0;
02396 pDimensionDefinitions[i].zones = 0;
02397 pDimensionDefinitions[i].split_type = split_type_bit;
02398 pDimensionDefinitions[i].zone_size = 0;
02399 }
02400 else {
02401 pDimensionDefinitions[i].dimension = dimension;
02402 pDimensionDefinitions[i].bits = bits;
02403 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits;
02404 pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
02405 pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
02406 Dimensions++;
02407
02408
02409 if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
02410 }
02411 _3lnk->SetPos(3, RIFF::stream_curpos);
02412 }
02413 for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
02414
02415
02416
02417 UpdateVelocityTable();
02418
02419
02420 if (file->pVersion && file->pVersion->major == 3)
02421 _3lnk->SetPos(68);
02422 else
02423 _3lnk->SetPos(44);
02424
02425
02426 if (file->GetAutoLoad()) {
02427 for (uint i = 0; i < DimensionRegions; i++) {
02428 uint32_t wavepoolindex = _3lnk->ReadUint32();
02429 if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
02430 }
02431 GetSample();
02432 }
02433 } else {
02434 DimensionRegions = 0;
02435 for (int i = 0 ; i < 8 ; i++) {
02436 pDimensionDefinitions[i].dimension = dimension_none;
02437 pDimensionDefinitions[i].bits = 0;
02438 pDimensionDefinitions[i].zones = 0;
02439 }
02440 }
02441
02442
02443 if (!DimensionRegions) {
02444 RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
02445 if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
02446 RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
02447 pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
02448 DimensionRegions = 1;
02449 }
02450 }
02451
02461 void Region::UpdateChunks() {
02462
02463
02464
02465
02466 pSample = pDimensionRegions[0]->pSample;
02467
02468
02469 DLS::Region::UpdateChunks();
02470
02471
02472 for (int i = 0; i < DimensionRegions; i++) {
02473 pDimensionRegions[i]->UpdateChunks();
02474 }
02475
02476 File* pFile = (File*) GetParent()->GetParent();
02477 bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
02478 const int iMaxDimensions = version3 ? 8 : 5;
02479 const int iMaxDimensionRegions = version3 ? 256 : 32;
02480
02481
02482 RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
02483 if (!_3lnk) {
02484 const int _3lnkChunkSize = version3 ? 1092 : 172;
02485 _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
02486 memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
02487
02488
02489 pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
02490 }
02491
02492
02493 uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
02494 store32(&pData[0], DimensionRegions);
02495 int shift = 0;
02496 for (int i = 0; i < iMaxDimensions; i++) {
02497 pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
02498 pData[5 + i * 8] = pDimensionDefinitions[i].bits;
02499 pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
02500 pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
02501 pData[8 + i * 8] = pDimensionDefinitions[i].zones;
02502
02503
02504 shift += pDimensionDefinitions[i].bits;
02505 }
02506
02507
02508 const int iWavePoolOffset = version3 ? 68 : 44;
02509 for (uint i = 0; i < iMaxDimensionRegions; i++) {
02510 int iWaveIndex = -1;
02511 if (i < DimensionRegions) {
02512 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
02513 File::SampleList::iterator iter = pFile->pSamples->begin();
02514 File::SampleList::iterator end = pFile->pSamples->end();
02515 for (int index = 0; iter != end; ++iter, ++index) {
02516 if (*iter == pDimensionRegions[i]->pSample) {
02517 iWaveIndex = index;
02518 break;
02519 }
02520 }
02521 }
02522 store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
02523 }
02524 }
02525
02526 void Region::LoadDimensionRegions(RIFF::List* rgn) {
02527 RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
02528 if (_3prg) {
02529 int dimensionRegionNr = 0;
02530 RIFF::List* _3ewl = _3prg->GetFirstSubList();
02531 while (_3ewl) {
02532 if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
02533 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
02534 dimensionRegionNr++;
02535 }
02536 _3ewl = _3prg->GetNextSubList();
02537 }
02538 if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
02539 }
02540 }
02541
02542 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
02543
02544 DLS::Region::SetKeyRange(Low, High);
02545
02546 ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
02547 }
02548
02549 void Region::UpdateVelocityTable() {
02550
02551 int veldim = -1;
02552 for (int i = 0 ; i < Dimensions ; i++) {
02553 if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
02554 veldim = i;
02555 break;
02556 }
02557 }
02558 if (veldim == -1) return;
02559
02560 int step = 1;
02561 for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
02562 int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
02563 int end = step * pDimensionDefinitions[veldim].zones;
02564
02565
02566 int dim[8] = { 0 };
02567 for (int i = 0 ; i < DimensionRegions ; i++) {
02568
02569 if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
02570 pDimensionRegions[i]->VelocityUpperLimit) {
02571
02572 uint8_t* table = pDimensionRegions[i]->VelocityTable;
02573 if (!table) {
02574 table = new uint8_t[128];
02575 pDimensionRegions[i]->VelocityTable = table;
02576 }
02577 int tableidx = 0;
02578 int velocityZone = 0;
02579 if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) {
02580 for (int k = i ; k < end ; k += step) {
02581 DimensionRegion *d = pDimensionRegions[k];
02582 for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
02583 velocityZone++;
02584 }
02585 } else {
02586 for (int k = i ; k < end ; k += step) {
02587 DimensionRegion *d = pDimensionRegions[k];
02588 for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
02589 velocityZone++;
02590 }
02591 }
02592 } else {
02593 if (pDimensionRegions[i]->VelocityTable) {
02594 delete[] pDimensionRegions[i]->VelocityTable;
02595 pDimensionRegions[i]->VelocityTable = 0;
02596 }
02597 }
02598
02599 int j;
02600 int shift = 0;
02601 for (j = 0 ; j < Dimensions ; j++) {
02602 if (j == veldim) i += skipveldim;
02603 else {
02604 dim[j]++;
02605 if (dim[j] < pDimensionDefinitions[j].zones) break;
02606 else {
02607
02608 dim[j] = 0;
02609 i += ((1 << pDimensionDefinitions[j].bits) -
02610 pDimensionDefinitions[j].zones) << shift;
02611 }
02612 }
02613 shift += pDimensionDefinitions[j].bits;
02614 }
02615 if (j == Dimensions) break;
02616 }
02617 }
02618
02634 void Region::AddDimension(dimension_def_t* pDimDef) {
02635
02636 File* file = (File*) GetParent()->GetParent();
02637 const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
02638 if (Dimensions >= iMaxDimensions)
02639 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
02640
02641 int iCurrentBits = 0;
02642 for (int i = 0; i < Dimensions; i++)
02643 iCurrentBits += pDimensionDefinitions[i].bits;
02644 if (iCurrentBits >= iMaxDimensions)
02645 throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
02646 const int iNewBits = iCurrentBits + pDimDef->bits;
02647 if (iNewBits > iMaxDimensions)
02648 throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
02649
02650 for (int i = 0; i < Dimensions; i++)
02651 if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
02652 throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
02653
02654
02655
02656
02657 int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
02658 int bitpos = 0;
02659 for (int i = 0 ; i < pos ; i++)
02660 bitpos += pDimensionDefinitions[i].bits;
02661
02662
02663 for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
02664 for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
02665 for (int j = Dimensions ; j > pos ; j--) {
02666 pDimensionRegions[i]->DimensionUpperLimits[j] =
02667 pDimensionRegions[i]->DimensionUpperLimits[j - 1];
02668 }
02669 }
02670
02671
02672 pDimensionDefinitions[pos] = *pDimDef;
02673
02674
02675 pDimensionDefinitions[pos].split_type =
02676 __resolveSplitType(pDimensionDefinitions[pos].dimension);
02677 pDimensionDefinitions[pos].zone_size =
02678 __resolveZoneSize(pDimensionDefinitions[pos]);
02679
02680
02681
02682
02683 RIFF::Chunk* moveTo = NULL;
02684 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
02685 for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
02686 for (int k = 0 ; k < (1 << bitpos) ; k++) {
02687 pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
02688 }
02689 for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
02690 for (int k = 0 ; k < (1 << bitpos) ; k++) {
02691 RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
02692 if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
02693
02694
02695 pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
02696 new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
02697
02698 DimensionRegions++;
02699 }
02700 }
02701 moveTo = pDimensionRegions[i]->pParentList;
02702 }
02703
02704
02705 int mask = (1 << bitpos) - 1;
02706 for (int z = 0 ; z < pDimDef->zones ; z++) {
02707 uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
02708 for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
02709 pDimensionRegions[((i & ~mask) << pDimDef->bits) |
02710 (z << bitpos) |
02711 (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
02712 }
02713 }
02714
02715 Dimensions++;
02716
02717
02718 if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
02719
02720 UpdateVelocityTable();
02721 }
02722
02734 void Region::DeleteDimension(dimension_def_t* pDimDef) {
02735
02736 int iDimensionNr = -1;
02737 for (int i = 0; i < Dimensions; i++) {
02738 if (&pDimensionDefinitions[i] == pDimDef) {
02739 iDimensionNr = i;
02740 break;
02741 }
02742 }
02743 if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
02744
02745
02746 int iLowerBits = 0;
02747 for (int i = 0; i < iDimensionNr; i++)
02748 iLowerBits += pDimensionDefinitions[i].bits;
02749
02750
02751 int iUpperBits = 0;
02752 for (int i = iDimensionNr + 1; i < Dimensions; i++)
02753 iUpperBits += pDimensionDefinitions[i].bits;
02754
02755 RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
02756
02757
02758
02759 for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
02760 for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
02761 for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
02762 int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
02763 iObsoleteBit << iLowerBits |
02764 iLowerBit;
02765
02766 _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
02767 delete pDimensionRegions[iToDelete];
02768 pDimensionRegions[iToDelete] = NULL;
02769 DimensionRegions--;
02770 }
02771 }
02772 }
02773
02774
02775
02776 for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
02777 if (!pDimensionRegions[iTo]) {
02778 if (iFrom <= iTo) iFrom = iTo + 1;
02779 while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
02780 if (iFrom < 256 && pDimensionRegions[iFrom]) {
02781 pDimensionRegions[iTo] = pDimensionRegions[iFrom];
02782 pDimensionRegions[iFrom] = NULL;
02783 }
02784 }
02785 }
02786
02787
02788 for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
02789 DimensionRegion* d = pDimensionRegions[j];
02790 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
02791 d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
02792 }
02793 d->DimensionUpperLimits[Dimensions - 1] = 127;
02794 }
02795
02796
02797 for (int i = iDimensionNr + 1; i < Dimensions; i++) {
02798 pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
02799 }
02800 pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
02801 pDimensionDefinitions[Dimensions - 1].bits = 0;
02802 pDimensionDefinitions[Dimensions - 1].zones = 0;
02803
02804 Dimensions--;
02805
02806
02807 if (pDimDef->dimension == dimension_layer) Layers = 1;
02808 }
02809
02810 Region::~Region() {
02811 for (int i = 0; i < 256; i++) {
02812 if (pDimensionRegions[i]) delete pDimensionRegions[i];
02813 }
02814 }
02815
02834 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
02835 uint8_t bits;
02836 int veldim = -1;
02837 int velbitpos;
02838 int bitpos = 0;
02839 int dimregidx = 0;
02840 for (uint i = 0; i < Dimensions; i++) {
02841 if (pDimensionDefinitions[i].dimension == dimension_velocity) {
02842
02843 veldim = i;
02844 velbitpos = bitpos;
02845 } else {
02846 switch (pDimensionDefinitions[i].split_type) {
02847 case split_type_normal:
02848 if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
02849
02850 for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
02851 if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
02852 }
02853 } else {
02854
02855 bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
02856 }
02857 break;
02858 case split_type_bit:
02859 const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
02860 bits = DimValues[i] & limiter_mask;
02861 break;
02862 }
02863 dimregidx |= bits << bitpos;
02864 }
02865 bitpos += pDimensionDefinitions[i].bits;
02866 }
02867 DimensionRegion* dimreg = pDimensionRegions[dimregidx];
02868 if (veldim != -1) {
02869
02870 if (dimreg->VelocityTable)
02871 bits = dimreg->VelocityTable[DimValues[veldim]];
02872 else
02873 bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
02874
02875 dimregidx |= bits << velbitpos;
02876 dimreg = pDimensionRegions[dimregidx];
02877 }
02878 return dimreg;
02879 }
02880
02891 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
02892 return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
02893 << pDimensionDefinitions[5].bits | DimBits[5])
02894 << pDimensionDefinitions[4].bits | DimBits[4])
02895 << pDimensionDefinitions[3].bits | DimBits[3])
02896 << pDimensionDefinitions[2].bits | DimBits[2])
02897 << pDimensionDefinitions[1].bits | DimBits[1])
02898 << pDimensionDefinitions[0].bits | DimBits[0]];
02899 }
02900
02910 Sample* Region::GetSample() {
02911 if (pSample) return static_cast<gig::Sample*>(pSample);
02912 else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
02913 }
02914
02915 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
02916 if ((int32_t)WavePoolTableIndex == -1) return NULL;
02917 File* file = (File*) GetParent()->GetParent();
02918 if (!file->pWavePoolTable) return NULL;
02919 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
02920 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
02921 Sample* sample = file->GetFirstSample(pProgress);
02922 while (sample) {
02923 if (sample->ulWavePoolOffset == soughtoffset &&
02924 sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
02925 sample = file->GetNextSample();
02926 }
02927 return NULL;
02928 }
02929
02930
02931
02932
02933
02934 MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
02935 _3ewg->SetPos(36);
02936 Triggers = _3ewg->ReadUint8();
02937 _3ewg->SetPos(40);
02938 ControllerNumber = _3ewg->ReadUint8();
02939 _3ewg->SetPos(46);
02940 for (int i = 0 ; i < Triggers ; i++) {
02941 pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
02942 pTriggers[i].Descending = _3ewg->ReadUint8();
02943 pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
02944 pTriggers[i].Key = _3ewg->ReadUint8();
02945 pTriggers[i].NoteOff = _3ewg->ReadUint8();
02946 pTriggers[i].Velocity = _3ewg->ReadUint8();
02947 pTriggers[i].OverridePedal = _3ewg->ReadUint8();
02948 _3ewg->ReadUint8();
02949 }
02950 }
02951
02952
02953
02954
02955
02956 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
02957 static const DLS::Info::string_length_t fixedStringLengths[] = {
02958 { CHUNK_ID_INAM, 64 },
02959 { CHUNK_ID_ISFT, 12 },
02960 { 0, 0 }
02961 };
02962 pInfo->SetFixedStringLengths(fixedStringLengths);
02963
02964
02965 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
02966 EffectSend = 0;
02967 Attenuation = 0;
02968 FineTune = 0;
02969 PitchbendRange = 0;
02970 PianoReleaseMode = false;
02971 DimensionKeyRange.low = 0;
02972 DimensionKeyRange.high = 0;
02973 pMidiRules = new MidiRule*[3];
02974 pMidiRules[0] = NULL;
02975
02976
02977 RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
02978 if (lart) {
02979 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
02980 if (_3ewg) {
02981 EffectSend = _3ewg->ReadUint16();
02982 Attenuation = _3ewg->ReadInt32();
02983 FineTune = _3ewg->ReadInt16();
02984 PitchbendRange = _3ewg->ReadInt16();
02985 uint8_t dimkeystart = _3ewg->ReadUint8();
02986 PianoReleaseMode = dimkeystart & 0x01;
02987 DimensionKeyRange.low = dimkeystart >> 1;
02988 DimensionKeyRange.high = _3ewg->ReadUint8();
02989
02990 if (_3ewg->GetSize() > 32) {
02991
02992 int i = 0;
02993 _3ewg->SetPos(32);
02994 uint8_t id1 = _3ewg->ReadUint8();
02995 uint8_t id2 = _3ewg->ReadUint8();
02996
02997 if (id1 == 4 && id2 == 16) {
02998 pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
02999 }
03000
03001
03002 pMidiRules[i] = NULL;
03003 }
03004 }
03005 }
03006
03007 if (pFile->GetAutoLoad()) {
03008 if (!pRegions) pRegions = new RegionList;
03009 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
03010 if (lrgn) {
03011 RIFF::List* rgn = lrgn->GetFirstSubList();
03012 while (rgn) {
03013 if (rgn->GetListType() == LIST_TYPE_RGN) {
03014 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
03015 pRegions->push_back(new Region(this, rgn));
03016 }
03017 rgn = lrgn->GetNextSubList();
03018 }
03019
03020 UpdateRegionKeyTable();
03021 }
03022 }
03023
03024 __notify_progress(pProgress, 1.0f);
03025 }
03026
03027 void Instrument::UpdateRegionKeyTable() {
03028 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
03029 RegionList::iterator iter = pRegions->begin();
03030 RegionList::iterator end = pRegions->end();
03031 for (; iter != end; ++iter) {
03032 gig::Region* pRegion = static_cast<gig::Region*>(*iter);
03033 for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
03034 RegionKeyTable[iKey] = pRegion;
03035 }
03036 }
03037 }
03038
03039 Instrument::~Instrument() {
03040 for (int i = 0 ; pMidiRules[i] ; i++) {
03041 delete pMidiRules[i];
03042 }
03043 delete[] pMidiRules;
03044 }
03045
03055 void Instrument::UpdateChunks() {
03056
03057 DLS::Instrument::UpdateChunks();
03058
03059
03060 {
03061 RegionList::iterator iter = pRegions->begin();
03062 RegionList::iterator end = pRegions->end();
03063 for (; iter != end; ++iter)
03064 (*iter)->UpdateChunks();
03065 }
03066
03067
03068 RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
03069 if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
03070
03071 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
03072 if (!_3ewg) {
03073 File* pFile = (File*) GetParent();
03074
03075
03076 int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
03077 _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
03078 memset(_3ewg->LoadChunkData(), 0, size);
03079 }
03080
03081 uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
03082 store16(&pData[0], EffectSend);
03083 store32(&pData[2], Attenuation);
03084 store16(&pData[6], FineTune);
03085 store16(&pData[8], PitchbendRange);
03086 const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
03087 DimensionKeyRange.low << 1;
03088 pData[10] = dimkeystart;
03089 pData[11] = DimensionKeyRange.high;
03090 }
03091
03099 Region* Instrument::GetRegion(unsigned int Key) {
03100 if (!pRegions || pRegions->empty() || Key > 127) return NULL;
03101 return RegionKeyTable[Key];
03102
03103
03104
03105
03106
03107
03108 }
03109
03117 Region* Instrument::GetFirstRegion() {
03118 if (!pRegions) return NULL;
03119 RegionsIterator = pRegions->begin();
03120 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
03121 }
03122
03131 Region* Instrument::GetNextRegion() {
03132 if (!pRegions) return NULL;
03133 RegionsIterator++;
03134 return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
03135 }
03136
03137 Region* Instrument::AddRegion() {
03138
03139 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
03140 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
03141 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
03142 Region* pNewRegion = new Region(this, rgn);
03143 pRegions->push_back(pNewRegion);
03144 Regions = pRegions->size();
03145
03146 UpdateRegionKeyTable();
03147
03148 return pNewRegion;
03149 }
03150
03151 void Instrument::DeleteRegion(Region* pRegion) {
03152 if (!pRegions) return;
03153 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
03154
03155 UpdateRegionKeyTable();
03156 }
03157
03168 MidiRule* Instrument::GetMidiRule(int i) {
03169 return pMidiRules[i];
03170 }
03171
03172
03173
03174
03175
03182 Group::Group(File* file, RIFF::Chunk* ck3gnm) {
03183 pFile = file;
03184 pNameChunk = ck3gnm;
03185 ::LoadString(pNameChunk, Name);
03186 }
03187
03188 Group::~Group() {
03189
03190 if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
03191 }
03192
03201 void Group::UpdateChunks() {
03202
03203 RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
03204 if (!_3gri) {
03205 _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
03206 pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
03207 }
03208 RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
03209 if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
03210
03211 if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
03212
03213 for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
03214 if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
03215 pNameChunk = ck;
03216 break;
03217 }
03218 }
03219 }
03220
03221
03222 ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
03223 }
03224
03236 Sample* Group::GetFirstSample() {
03237
03238 for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
03239 if (pSample->GetGroup() == this) return pSample;
03240 }
03241 return NULL;
03242 }
03243
03254 Sample* Group::GetNextSample() {
03255
03256 for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
03257 if (pSample->GetGroup() == this) return pSample;
03258 }
03259 return NULL;
03260 }
03261
03265 void Group::AddSample(Sample* pSample) {
03266 pSample->pGroup = this;
03267 }
03268
03275 void Group::MoveAll() {
03276
03277 Group* pOtherGroup = NULL;
03278 for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
03279 if (pOtherGroup != this) break;
03280 }
03281 if (!pOtherGroup) throw Exception(
03282 "Could not move samples to another group, since there is no "
03283 "other Group. This is a bug, report it!"
03284 );
03285
03286 for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
03287 pOtherGroup->AddSample(pSample);
03288 }
03289 }
03290
03291
03292
03293
03294
03295
03297 const DLS::version_t File::VERSION_2 = {
03298 0, 2, 19980628 & 0xffff, 19980628 >> 16
03299 };
03300
03302 const DLS::version_t File::VERSION_3 = {
03303 0, 3, 20030331 & 0xffff, 20030331 >> 16
03304 };
03305
03306 static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
03307 { CHUNK_ID_IARL, 256 },
03308 { CHUNK_ID_IART, 128 },
03309 { CHUNK_ID_ICMS, 128 },
03310 { CHUNK_ID_ICMT, 1024 },
03311 { CHUNK_ID_ICOP, 128 },
03312 { CHUNK_ID_ICRD, 128 },
03313 { CHUNK_ID_IENG, 128 },
03314 { CHUNK_ID_IGNR, 128 },
03315 { CHUNK_ID_IKEY, 128 },
03316 { CHUNK_ID_IMED, 128 },
03317 { CHUNK_ID_INAM, 128 },
03318 { CHUNK_ID_IPRD, 128 },
03319 { CHUNK_ID_ISBJ, 128 },
03320 { CHUNK_ID_ISFT, 128 },
03321 { CHUNK_ID_ISRC, 128 },
03322 { CHUNK_ID_ISRF, 128 },
03323 { CHUNK_ID_ITCH, 128 },
03324 { 0, 0 }
03325 };
03326
03327 File::File() : DLS::File() {
03328 bAutoLoad = true;
03329 *pVersion = VERSION_3;
03330 pGroups = NULL;
03331 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
03332 pInfo->ArchivalLocation = String(256, ' ');
03333
03334
03335
03336 pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
03337 pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
03338 pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
03339
03340 GenerateDLSID();
03341 }
03342
03343 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
03344 bAutoLoad = true;
03345 pGroups = NULL;
03346 pInfo->SetFixedStringLengths(_FileFixedStringLengths);
03347 }
03348
03349 File::~File() {
03350 if (pGroups) {
03351 std::list<Group*>::iterator iter = pGroups->begin();
03352 std::list<Group*>::iterator end = pGroups->end();
03353 while (iter != end) {
03354 delete *iter;
03355 ++iter;
03356 }
03357 delete pGroups;
03358 }
03359 }
03360
03361 Sample* File::GetFirstSample(progress_t* pProgress) {
03362 if (!pSamples) LoadSamples(pProgress);
03363 if (!pSamples) return NULL;
03364 SamplesIterator = pSamples->begin();
03365 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
03366 }
03367
03368 Sample* File::GetNextSample() {
03369 if (!pSamples) return NULL;
03370 SamplesIterator++;
03371 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
03372 }
03373
03381 Sample* File::AddSample() {
03382 if (!pSamples) LoadSamples();
03383 __ensureMandatoryChunksExist();
03384 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
03385
03386 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
03387 Sample* pSample = new Sample(this, wave, 0 );
03388
03389
03390 wave->AddSubChunk(CHUNK_ID_FMT, 16);
03391 wave->AddSubList(LIST_TYPE_INFO);
03392
03393 pSamples->push_back(pSample);
03394 return pSample;
03395 }
03396
03406 void File::DeleteSample(Sample* pSample) {
03407 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
03408 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
03409 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
03410 if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator;
03411 pSamples->erase(iter);
03412 delete pSample;
03413
03414 SampleList::iterator tmp = SamplesIterator;
03415
03416 for (Instrument* instrument = GetFirstInstrument() ; instrument ;
03417 instrument = GetNextInstrument()) {
03418 for (Region* region = instrument->GetFirstRegion() ; region ;
03419 region = instrument->GetNextRegion()) {
03420
03421 if (region->GetSample() == pSample) region->SetSample(NULL);
03422
03423 for (int i = 0 ; i < region->DimensionRegions ; i++) {
03424 gig::DimensionRegion *d = region->pDimensionRegions[i];
03425 if (d->pSample == pSample) d->pSample = NULL;
03426 }
03427 }
03428 }
03429 SamplesIterator = tmp;
03430 }
03431
03432 void File::LoadSamples() {
03433 LoadSamples(NULL);
03434 }
03435
03436 void File::LoadSamples(progress_t* pProgress) {
03437
03438
03439 if (!pGroups) LoadGroups();
03440
03441 if (!pSamples) pSamples = new SampleList;
03442
03443 RIFF::File* file = pRIFF;
03444
03445
03446 int iSampleIndex = 0;
03447 int iTotalSamples = WavePoolCount;
03448
03449
03450 int lastFileNo = 0;
03451 for (int i = 0 ; i < WavePoolCount ; i++) {
03452 if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
03453 }
03454 String name(pRIFF->GetFileName());
03455 int nameLen = name.length();
03456 char suffix[6];
03457 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
03458
03459 for (int fileNo = 0 ; ; ) {
03460 RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
03461 if (wvpl) {
03462 unsigned long wvplFileOffset = wvpl->GetFilePos();
03463 RIFF::List* wave = wvpl->GetFirstSubList();
03464 while (wave) {
03465 if (wave->GetListType() == LIST_TYPE_WAVE) {
03466
03467 const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
03468 __notify_progress(pProgress, subprogress);
03469
03470 unsigned long waveFileOffset = wave->GetFilePos();
03471 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
03472
03473 iSampleIndex++;
03474 }
03475 wave = wvpl->GetNextSubList();
03476 }
03477
03478 if (fileNo == lastFileNo) break;
03479
03480
03481 fileNo++;
03482 sprintf(suffix, ".gx%02d", fileNo);
03483 name.replace(nameLen, 5, suffix);
03484 file = new RIFF::File(name);
03485 ExtensionFiles.push_back(file);
03486 } else break;
03487 }
03488
03489 __notify_progress(pProgress, 1.0);
03490 }
03491
03492 Instrument* File::GetFirstInstrument() {
03493 if (!pInstruments) LoadInstruments();
03494 if (!pInstruments) return NULL;
03495 InstrumentsIterator = pInstruments->begin();
03496 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
03497 }
03498
03499 Instrument* File::GetNextInstrument() {
03500 if (!pInstruments) return NULL;
03501 InstrumentsIterator++;
03502 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
03503 }
03504
03512 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
03513 if (!pInstruments) {
03514
03515
03516
03517 progress_t subprogress;
03518 __divide_progress(pProgress, &subprogress, 3.0f, 0.0f);
03519 __notify_progress(&subprogress, 0.0f);
03520 if (GetAutoLoad())
03521 GetFirstSample(&subprogress);
03522 __notify_progress(&subprogress, 1.0f);
03523
03524
03525 if (pProgress && pProgress->callback) {
03526 subprogress.__range_min = subprogress.__range_max;
03527 subprogress.__range_max = pProgress->__range_max;
03528 }
03529 __notify_progress(&subprogress, 0.0f);
03530 LoadInstruments(&subprogress);
03531 __notify_progress(&subprogress, 1.0f);
03532 }
03533 if (!pInstruments) return NULL;
03534 InstrumentsIterator = pInstruments->begin();
03535 for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
03536 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
03537 InstrumentsIterator++;
03538 }
03539 return NULL;
03540 }
03541
03549 Instrument* File::AddInstrument() {
03550 if (!pInstruments) LoadInstruments();
03551 __ensureMandatoryChunksExist();
03552 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
03553 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
03554
03555
03556 lstInstr->AddSubList(LIST_TYPE_INFO);
03557 lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
03558
03559 Instrument* pInstrument = new Instrument(this, lstInstr);
03560 pInstrument->GenerateDLSID();
03561
03562 lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
03563
03564
03565 pInstrument->pInfo->Software = "Endless Wave";
03566
03567 pInstruments->push_back(pInstrument);
03568 return pInstrument;
03569 }
03570
03579 void File::DeleteInstrument(Instrument* pInstrument) {
03580 if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
03581 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
03582 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
03583 pInstruments->erase(iter);
03584 delete pInstrument;
03585 }
03586
03587 void File::LoadInstruments() {
03588 LoadInstruments(NULL);
03589 }
03590
03591 void File::LoadInstruments(progress_t* pProgress) {
03592 if (!pInstruments) pInstruments = new InstrumentList;
03593 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
03594 if (lstInstruments) {
03595 int iInstrumentIndex = 0;
03596 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
03597 while (lstInstr) {
03598 if (lstInstr->GetListType() == LIST_TYPE_INS) {
03599
03600 const float localProgress = (float) iInstrumentIndex / (float) Instruments;
03601 __notify_progress(pProgress, localProgress);
03602
03603
03604 progress_t subprogress;
03605 __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
03606
03607 pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
03608
03609 iInstrumentIndex++;
03610 }
03611 lstInstr = lstInstruments->GetNextSubList();
03612 }
03613 __notify_progress(pProgress, 1.0);
03614 }
03615 }
03616
03620 void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
03621 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
03622 if (!_3crc) return;
03623
03624
03625 int iWaveIndex = -1;
03626 File::SampleList::iterator iter = pSamples->begin();
03627 File::SampleList::iterator end = pSamples->end();
03628 for (int index = 0; iter != end; ++iter, ++index) {
03629 if (*iter == pSample) {
03630 iWaveIndex = index;
03631 break;
03632 }
03633 }
03634 if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
03635
03636
03637 _3crc->SetPos(iWaveIndex * 8);
03638 uint32_t tmp = 1;
03639 _3crc->WriteUint32(&tmp);
03640 _3crc->WriteUint32(&crc);
03641 }
03642
03643 Group* File::GetFirstGroup() {
03644 if (!pGroups) LoadGroups();
03645
03646 GroupsIterator = pGroups->begin();
03647 return *GroupsIterator;
03648 }
03649
03650 Group* File::GetNextGroup() {
03651 if (!pGroups) return NULL;
03652 ++GroupsIterator;
03653 return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
03654 }
03655
03662 Group* File::GetGroup(uint index) {
03663 if (!pGroups) LoadGroups();
03664 GroupsIterator = pGroups->begin();
03665 for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
03666 if (i == index) return *GroupsIterator;
03667 ++GroupsIterator;
03668 }
03669 return NULL;
03670 }
03671
03672 Group* File::AddGroup() {
03673 if (!pGroups) LoadGroups();
03674
03675 __ensureMandatoryChunksExist();
03676 Group* pGroup = new Group(this, NULL);
03677 pGroups->push_back(pGroup);
03678 return pGroup;
03679 }
03680
03690 void File::DeleteGroup(Group* pGroup) {
03691 if (!pGroups) LoadGroups();
03692 std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
03693 if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
03694 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
03695
03696 for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
03697 DeleteSample(pSample);
03698 }
03699
03700 pGroups->erase(iter);
03701 delete pGroup;
03702 }
03703
03714 void File::DeleteGroupOnly(Group* pGroup) {
03715 if (!pGroups) LoadGroups();
03716 std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
03717 if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
03718 if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
03719
03720 pGroup->MoveAll();
03721 pGroups->erase(iter);
03722 delete pGroup;
03723 }
03724
03725 void File::LoadGroups() {
03726 if (!pGroups) pGroups = new std::list<Group*>;
03727
03728 RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
03729 if (lst3gri) {
03730 RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
03731 if (lst3gnl) {
03732 RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
03733 while (ck) {
03734 if (ck->GetChunkID() == CHUNK_ID_3GNM) {
03735 if (pVersion && pVersion->major == 3 &&
03736 strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
03737
03738 pGroups->push_back(new Group(this, ck));
03739 }
03740 ck = lst3gnl->GetNextSubChunk();
03741 }
03742 }
03743 }
03744
03745 if (!pGroups->size()) {
03746 Group* pGroup = new Group(this, NULL);
03747 pGroup->Name = "Default Group";
03748 pGroups->push_back(pGroup);
03749 }
03750 }
03751
03762 void File::UpdateChunks() {
03763 bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
03764
03765 b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
03766
03767
03768 DLS::File::UpdateChunks();
03769
03770 if (newFile) {
03771
03772
03773 RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
03774 RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
03775 if (first != info) {
03776 pRIFF->MoveSubChunk(info, first);
03777 }
03778 }
03779
03780
03781 if (pGroups) {
03782 std::list<Group*>::iterator iter = pGroups->begin();
03783 std::list<Group*>::iterator end = pGroups->end();
03784 for (; iter != end; ++iter) {
03785 (*iter)->UpdateChunks();
03786 }
03787
03788
03789 if (pVersion && pVersion->major == 3) {
03790 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);
03791 RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
03792 for (int i = 0 ; i < 128 ; i++) {
03793 if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
03794 if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
03795 }
03796 }
03797 }
03798
03799
03800
03801
03802
03803
03804
03805
03806
03807
03808
03809
03810
03811
03812
03813
03814
03815 int sublen = pSamples->size() / 8 + 49;
03816 int einfSize = (Instruments + 1) * sublen;
03817
03818 RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
03819 if (einf) {
03820 if (einf->GetSize() != einfSize) {
03821 einf->Resize(einfSize);
03822 memset(einf->LoadChunkData(), 0, einfSize);
03823 }
03824 } else if (newFile) {
03825 einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
03826 }
03827 if (einf) {
03828 uint8_t* pData = (uint8_t*) einf->LoadChunkData();
03829
03830 std::map<gig::Sample*,int> sampleMap;
03831 int sampleIdx = 0;
03832 for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
03833 sampleMap[pSample] = sampleIdx++;
03834 }
03835
03836 int totnbusedsamples = 0;
03837 int totnbusedchannels = 0;
03838 int totnbregions = 0;
03839 int totnbdimregions = 0;
03840 int totnbloops = 0;
03841 int instrumentIdx = 0;
03842
03843 memset(&pData[48], 0, sublen - 48);
03844
03845 for (Instrument* instrument = GetFirstInstrument() ; instrument ;
03846 instrument = GetNextInstrument()) {
03847 int nbusedsamples = 0;
03848 int nbusedchannels = 0;
03849 int nbdimregions = 0;
03850 int nbloops = 0;
03851
03852 memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
03853
03854 for (Region* region = instrument->GetFirstRegion() ; region ;
03855 region = instrument->GetNextRegion()) {
03856 for (int i = 0 ; i < region->DimensionRegions ; i++) {
03857 gig::DimensionRegion *d = region->pDimensionRegions[i];
03858 if (d->pSample) {
03859 int sampleIdx = sampleMap[d->pSample];
03860 int byte = 48 + sampleIdx / 8;
03861 int bit = 1 << (sampleIdx & 7);
03862 if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
03863 pData[(instrumentIdx + 1) * sublen + byte] |= bit;
03864 nbusedsamples++;
03865 nbusedchannels += d->pSample->Channels;
03866
03867 if ((pData[byte] & bit) == 0) {
03868 pData[byte] |= bit;
03869 totnbusedsamples++;
03870 totnbusedchannels += d->pSample->Channels;
03871 }
03872 }
03873 }
03874 if (d->SampleLoops) nbloops++;
03875 }
03876 nbdimregions += region->DimensionRegions;
03877 }
03878
03879
03880 store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
03881 store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
03882 store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
03883 store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
03884 store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
03885 store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
03886
03887 store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
03888 store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
03889
03890
03891 totnbregions += instrument->Regions;
03892 totnbdimregions += nbdimregions;
03893 totnbloops += nbloops;
03894 instrumentIdx++;
03895 }
03896
03897
03898 store32(&pData[4], totnbusedchannels);
03899 store32(&pData[8], totnbusedsamples);
03900 store32(&pData[12], Instruments);
03901 store32(&pData[16], totnbregions);
03902 store32(&pData[20], totnbdimregions);
03903 store32(&pData[24], totnbloops);
03904
03905
03906 store32(&pData[40], pSamples->size());
03907
03908 }
03909
03910
03911
03912
03913
03914
03915
03916 RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
03917 if (_3crc) {
03918 _3crc->Resize(pSamples->size() * 8);
03919 } else if (newFile) {
03920 _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
03921 _3crc->LoadChunkData();
03922
03923
03924 if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
03925 }
03926 }
03927
03943 void File::SetAutoLoad(bool b) {
03944 bAutoLoad = b;
03945 }
03946
03951 bool File::GetAutoLoad() {
03952 return bAutoLoad;
03953 }
03954
03955
03956
03957
03958
03959
03960 Exception::Exception(String Message) : DLS::Exception(Message) {
03961 }
03962
03963 void Exception::PrintMessage() {
03964 std::cout << "gig::Exception: " << Message << std::endl;
03965 }
03966
03967
03968
03969
03970
03976 String libraryName() {
03977 return PACKAGE;
03978 }
03979
03984 String libraryVersion() {
03985 return VERSION;
03986 }
03987
03988 }