--- libgig/trunk/src/gig.cpp 2005/11/22 11:26:55 809 +++ libgig/trunk/src/gig.cpp 2006/10/29 17:57:20 930 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file loader library * * * - * Copyright (C) 2003-2005 by Christian Schoenebeck * + * Copyright (C) 2003-2006 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -51,26 +51,6 @@ namespace gig { -// *************** dimension_def_t *************** -// * - - dimension_def_t& dimension_def_t::operator=(const dimension_def_t& arg) { - dimension = arg.dimension; - bits = arg.bits; - zones = arg.zones; - split_type = arg.split_type; - ranges = arg.ranges; - zone_size = arg.zone_size; - if (ranges) { - ranges = new range_t[zones]; - for (int i = 0; i < zones; i++) - ranges[i] = arg.ranges[i]; - } - return *this; - } - - - // *************** progress_t *************** // * @@ -131,6 +111,13 @@ return x & 0x800000 ? x - 0x1000000 : x; } + inline void store24(unsigned char* pDst, int x) + { + pDst[0] = x; + pDst[1] = x >> 8; + pDst[2] = x >> 16; + } + void Decompress16(int compressionmode, const unsigned char* params, int srcStep, int dstStep, const unsigned char* pSrc, int16_t* pDst, @@ -170,14 +157,11 @@ } void Decompress24(int compressionmode, const unsigned char* params, - int dstStep, const unsigned char* pSrc, int16_t* pDst, + int dstStep, const unsigned char* pSrc, uint8_t* pDst, unsigned long currentframeoffset, unsigned long copysamples, int truncatedBits) { - // Note: The 24 bits are truncated to 16 bits for now. - int y, dy, ddy, dddy; - const int shift = 8 - truncatedBits; #define GET_PARAMS(params) \ y = get24(params); \ @@ -193,14 +177,14 @@ #define COPY_ONE(x) \ SKIP_ONE(x); \ - *pDst = y >> shift; \ + store24(pDst, y << truncatedBits); \ pDst += dstStep switch (compressionmode) { case 2: // 24 bit uncompressed pSrc += currentframeoffset * 3; while (copysamples) { - *pDst = get24(pSrc) >> shift; + store24(pDst, get24(pSrc) << truncatedBits); pDst += dstStep; pSrc += 3; copysamples--; @@ -295,15 +279,17 @@ * is located, 0 otherwise */ Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) { + pInfo->UseFixedLengthStrings = true; Instances++; FileNo = fileNo; pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX); if (pCk3gix) { - SampleGroup = pCk3gix->ReadInt16(); + uint16_t iSampleGroup = pCk3gix->ReadInt16(); + pGroup = pFile->GetGroup(iSampleGroup); } else { // '3gix' chunk missing - // use default value(s) - SampleGroup = 0; + // by default assigned to that mandatory "Default Group" + pGroup = pFile->GetGroup(0); } pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL); @@ -327,7 +313,7 @@ // use default values Manufacturer = 0; Product = 0; - SamplePeriod = 1 / SamplesPerSecond; + SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5); MIDIUnityNote = 64; FineTune = 0; SMPTEOffset = 0; @@ -368,7 +354,7 @@ } FrameOffset = 0; // just for streaming compressed samples - LoopSize = LoopEnd - LoopStart; + LoopSize = LoopEnd - LoopStart + 1; } /** @@ -391,7 +377,7 @@ if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60); // update 'smpl' chunk uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData(); - SamplePeriod = 1 / SamplesPerSecond; + SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5); memcpy(&pData[0], &Manufacturer, 4); memcpy(&pData[4], &Product, 4); memcpy(&pData[8], &SamplePeriod, 4); @@ -413,9 +399,22 @@ // make sure '3gix' chunk exists pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX); if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4); + // determine appropriate sample group index (to be stored in chunk) + uint16_t iSampleGroup = 0; // 0 refers to default sample group + File* pFile = static_cast(pParent); + if (pFile->pGroups) { + std::list::iterator iter = pFile->pGroups->begin(); + std::list::iterator end = pFile->pGroups->end(); + for (int i = 0; iter != end; i++, iter++) { + if (*iter == pGroup) { + iSampleGroup = i; + break; // found + } + } + } // update '3gix' chunk pData = (uint8_t*) pCk3gix->LoadChunkData(); - memcpy(&pData[0], &SampleGroup, 2); + memcpy(&pData[0], &iSampleGroup, 2); } /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points). @@ -742,139 +741,146 @@ * @param SampleCount number of sample points to read * @param pPlaybackState will be used to store and reload the playback * state for the next ReadAndLoop() call + * @param pDimRgn dimension region with looping information * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression * @returns number of successfully read sample points * @see CreateDecompressionBuffer() */ - unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) { + unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, + DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) { unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend; uint8_t* pDst = (uint8_t*) pBuffer; SetPos(pPlaybackState->position); // recover position from the last time - if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined + if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined - switch (this->LoopType) { + const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0]; + const uint32_t loopEnd = loop.LoopStart + loop.LoopLength; - case loop_type_bidirectional: { //TODO: not tested yet! - do { - // if not endless loop check if max. number of loop cycles have been passed - if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; - - if (!pPlaybackState->reverse) { // forward playback - do { - samplestoloopend = this->LoopEnd - GetPos(); - readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); - samplestoread -= readsamples; - totalreadsamples += readsamples; - if (readsamples == samplestoloopend) { - pPlaybackState->reverse = true; - break; - } - } while (samplestoread && readsamples); - } - else { // backward playback + if (GetPos() <= loopEnd) { + switch (loop.LoopType) { - // as we can only read forward from disk, we have to - // determine the end position within the loop first, - // read forward from that 'end' and finally after - // reading, swap all sample frames so it reflects - // backward playback - - unsigned long swapareastart = totalreadsamples; - unsigned long loopoffset = GetPos() - this->LoopStart; - unsigned long samplestoreadinloop = Min(samplestoread, loopoffset); - unsigned long reverseplaybackend = GetPos() - samplestoreadinloop; - - SetPos(reverseplaybackend); - - // read samples for backward playback - do { - readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer); - samplestoreadinloop -= readsamples; - samplestoread -= readsamples; - totalreadsamples += readsamples; - } while (samplestoreadinloop && readsamples); + case loop_type_bidirectional: { //TODO: not tested yet! + do { + // if not endless loop check if max. number of loop cycles have been passed + if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; + + if (!pPlaybackState->reverse) { // forward playback + do { + samplestoloopend = loopEnd - GetPos(); + readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); + samplestoread -= readsamples; + totalreadsamples += readsamples; + if (readsamples == samplestoloopend) { + pPlaybackState->reverse = true; + break; + } + } while (samplestoread && readsamples); + } + else { // backward playback - SetPos(reverseplaybackend); // pretend we really read backwards + // as we can only read forward from disk, we have to + // determine the end position within the loop first, + // read forward from that 'end' and finally after + // reading, swap all sample frames so it reflects + // backward playback + + unsigned long swapareastart = totalreadsamples; + unsigned long loopoffset = GetPos() - loop.LoopStart; + unsigned long samplestoreadinloop = Min(samplestoread, loopoffset); + unsigned long reverseplaybackend = GetPos() - samplestoreadinloop; + + SetPos(reverseplaybackend); + + // read samples for backward playback + do { + readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer); + samplestoreadinloop -= readsamples; + samplestoread -= readsamples; + totalreadsamples += readsamples; + } while (samplestoreadinloop && readsamples); + + SetPos(reverseplaybackend); // pretend we really read backwards + + if (reverseplaybackend == loop.LoopStart) { + pPlaybackState->loop_cycles_left--; + pPlaybackState->reverse = false; + } - if (reverseplaybackend == this->LoopStart) { - pPlaybackState->loop_cycles_left--; - pPlaybackState->reverse = false; + // reverse the sample frames for backward playback + SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); } + } while (samplestoread && readsamples); + break; + } - // reverse the sample frames for backward playback - SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); - } - } while (samplestoread && readsamples); - break; - } - - case loop_type_backward: { // TODO: not tested yet! - // forward playback (not entered the loop yet) - if (!pPlaybackState->reverse) do { - samplestoloopend = this->LoopEnd - GetPos(); - readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); - samplestoread -= readsamples; - totalreadsamples += readsamples; - if (readsamples == samplestoloopend) { - pPlaybackState->reverse = true; - break; - } - } while (samplestoread && readsamples); + case loop_type_backward: { // TODO: not tested yet! + // forward playback (not entered the loop yet) + if (!pPlaybackState->reverse) do { + samplestoloopend = loopEnd - GetPos(); + readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); + samplestoread -= readsamples; + totalreadsamples += readsamples; + if (readsamples == samplestoloopend) { + pPlaybackState->reverse = true; + break; + } + } while (samplestoread && readsamples); - if (!samplestoread) break; + if (!samplestoread) break; - // as we can only read forward from disk, we have to - // determine the end position within the loop first, - // read forward from that 'end' and finally after - // reading, swap all sample frames so it reflects - // backward playback - - unsigned long swapareastart = totalreadsamples; - unsigned long loopoffset = GetPos() - this->LoopStart; - unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset) - : samplestoread; - unsigned long reverseplaybackend = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize); - - SetPos(reverseplaybackend); - - // read samples for backward playback - do { - // if not endless loop check if max. number of loop cycles have been passed - if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; - samplestoloopend = this->LoopEnd - GetPos(); - readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer); - samplestoreadinloop -= readsamples; - samplestoread -= readsamples; - totalreadsamples += readsamples; - if (readsamples == samplestoloopend) { - pPlaybackState->loop_cycles_left--; - SetPos(this->LoopStart); - } - } while (samplestoreadinloop && readsamples); + // as we can only read forward from disk, we have to + // determine the end position within the loop first, + // read forward from that 'end' and finally after + // reading, swap all sample frames so it reflects + // backward playback + + unsigned long swapareastart = totalreadsamples; + unsigned long loopoffset = GetPos() - loop.LoopStart; + unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset) + : samplestoread; + unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength); + + SetPos(reverseplaybackend); + + // read samples for backward playback + do { + // if not endless loop check if max. number of loop cycles have been passed + if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; + samplestoloopend = loopEnd - GetPos(); + readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer); + samplestoreadinloop -= readsamples; + samplestoread -= readsamples; + totalreadsamples += readsamples; + if (readsamples == samplestoloopend) { + pPlaybackState->loop_cycles_left--; + SetPos(loop.LoopStart); + } + } while (samplestoreadinloop && readsamples); - SetPos(reverseplaybackend); // pretend we really read backwards + SetPos(reverseplaybackend); // pretend we really read backwards - // reverse the sample frames for backward playback - SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); - break; - } + // reverse the sample frames for backward playback + SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); + break; + } - default: case loop_type_normal: { - do { - // if not endless loop check if max. number of loop cycles have been passed - if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; - samplestoloopend = this->LoopEnd - GetPos(); - readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); - samplestoread -= readsamples; - totalreadsamples += readsamples; - if (readsamples == samplestoloopend) { - pPlaybackState->loop_cycles_left--; - SetPos(this->LoopStart); - } - } while (samplestoread && readsamples); - break; + default: case loop_type_normal: { + do { + // if not endless loop check if max. number of loop cycles have been passed + if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break; + samplestoloopend = loopEnd - GetPos(); + readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer); + samplestoread -= readsamples; + totalreadsamples += readsamples; + if (readsamples == samplestoloopend) { + pPlaybackState->loop_cycles_left--; + SetPos(loop.LoopStart); + } + } while (samplestoread && readsamples); + break; + } } } } @@ -904,6 +910,10 @@ * have to use an external decompression buffer for EACH * streaming thread to avoid race conditions and crashes! * + * For 16 bit samples, the data in the buffer will be int16_t + * (using native endianness). For 24 bit, the buffer will + * contain three bytes per sample, little-endian. + * * @param pBuffer destination buffer * @param SampleCount number of sample points to read * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression @@ -914,27 +924,7 @@ if (SampleCount == 0) return 0; if (!Compressed) { if (BitDepth == 24) { - // 24 bit sample. For now just truncate to 16 bit. - unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart); - int16_t* pDst = static_cast(pBuffer); - if (Channels == 2) { // Stereo - unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1); - pSrc++; - for (unsigned long i = readBytes ; i > 0 ; i -= 3) { - *pDst++ = get16(pSrc); - pSrc += 3; - } - return (pDst - static_cast(pBuffer)) >> 1; - } - else { // Mono - unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1); - pSrc++; - for (unsigned long i = readBytes ; i > 0 ; i -= 3) { - *pDst++ = get16(pSrc); - pSrc += 3; - } - return pDst - static_cast(pBuffer); - } + return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize; } else { // 16 bit // (pCkData->Read does endian correction) @@ -964,6 +954,7 @@ unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart; int16_t* pDst = static_cast(pBuffer); + uint8_t* pDst24 = static_cast(pBuffer); remainingbytes = pCkData->Read(pSrc, assumedsize, 1); while (remainingsamples && remainingbytes) { @@ -1045,16 +1036,16 @@ const unsigned char* const param_r = pSrc; if (mode_r != 2) pSrc += 12; - Decompress24(mode_l, param_l, 2, pSrc, pDst, + Decompress24(mode_l, param_l, 6, pSrc, pDst24, skipsamples, copysamples, TruncatedBits); - Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1, + Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3, skipsamples, copysamples, TruncatedBits); - pDst += copysamples << 1; + pDst24 += copysamples * 6; } else { // Mono - Decompress24(mode_l, param_l, 1, pSrc, pDst, + Decompress24(mode_l, param_l, 3, pSrc, pDst24, skipsamples, copysamples, TruncatedBits); - pDst += copysamples; + pDst24 += copysamples * 3; } } else { // 16 bit @@ -1161,6 +1152,18 @@ } } + /** + * Returns pointer to the Group this Sample belongs to. In the .gig + * format a sample always belongs to one group. If it wasn't explicitly + * assigned to a certain group, it will be automatically assigned to a + * default group. + * + * @returns Sample's Group (never NULL) + */ + Group* Sample::GetGroup() const { + return pGroup; + } + Sample::~Sample() { Instances--; if (!Instances && InternalDecompressionBuffer.Size) { @@ -1183,12 +1186,14 @@ DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) { Instances++; + pSample = NULL; + memcpy(&Crossfade, &SamplerOptions, 4); if (!pVelocityTables) pVelocityTables = new VelocityTableMap; RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA); if (_3ewa) { // if '3ewa' chunk exists - _3ewa->ReadInt32(); // unknown, always 0x0000008C ? + _3ewa->ReadInt32(); // unknown, always == chunk size ? LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); _3ewa->ReadInt16(); // unknown @@ -1447,6 +1452,7 @@ VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0); SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360)); + VelocityTable = 0; } /** @@ -1467,104 +1473,104 @@ // update '3ewa' chunk with DimensionRegion's current settings - const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ? + const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ? memcpy(&pData[0], &unknown, 4); const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency); memcpy(&pData[4], &lfo3freq, 4); const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack); - memcpy(&pData[4], &eg3attack, 4); + memcpy(&pData[8], &eg3attack, 4); // next 2 bytes unknown - memcpy(&pData[10], &LFO1InternalDepth, 2); + memcpy(&pData[14], &LFO1InternalDepth, 2); // next 2 bytes unknown - memcpy(&pData[14], &LFO3InternalDepth, 2); + memcpy(&pData[18], &LFO3InternalDepth, 2); // next 2 bytes unknown - memcpy(&pData[18], &LFO1ControlDepth, 2); + memcpy(&pData[22], &LFO1ControlDepth, 2); // next 2 bytes unknown - memcpy(&pData[22], &LFO3ControlDepth, 2); + memcpy(&pData[26], &LFO3ControlDepth, 2); const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack); - memcpy(&pData[24], &eg1attack, 4); + memcpy(&pData[28], &eg1attack, 4); const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1); - memcpy(&pData[28], &eg1decay1, 4); + memcpy(&pData[32], &eg1decay1, 4); // next 2 bytes unknown - memcpy(&pData[34], &EG1Sustain, 2); + memcpy(&pData[38], &EG1Sustain, 2); const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release); - memcpy(&pData[36], &eg1release, 4); + memcpy(&pData[40], &eg1release, 4); const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller); - memcpy(&pData[40], &eg1ctl, 1); + memcpy(&pData[44], &eg1ctl, 1); const uint8_t eg1ctrloptions = (EG1ControllerInvert) ? 0x01 : 0x00 | GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) | GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) | GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence); - memcpy(&pData[41], &eg1ctrloptions, 1); + memcpy(&pData[45], &eg1ctrloptions, 1); const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller); - memcpy(&pData[42], &eg2ctl, 1); + memcpy(&pData[46], &eg2ctl, 1); const uint8_t eg2ctrloptions = (EG2ControllerInvert) ? 0x01 : 0x00 | GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) | GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) | GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence); - memcpy(&pData[43], &eg2ctrloptions, 1); + memcpy(&pData[47], &eg2ctrloptions, 1); const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency); - memcpy(&pData[44], &lfo1freq, 4); + memcpy(&pData[48], &lfo1freq, 4); const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack); - memcpy(&pData[48], &eg2attack, 4); + memcpy(&pData[52], &eg2attack, 4); const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1); - memcpy(&pData[52], &eg2decay1, 4); + memcpy(&pData[56], &eg2decay1, 4); // next 2 bytes unknown - memcpy(&pData[58], &EG2Sustain, 2); + memcpy(&pData[62], &EG2Sustain, 2); const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release); - memcpy(&pData[60], &eg2release, 4); + memcpy(&pData[64], &eg2release, 4); // next 2 bytes unknown - memcpy(&pData[66], &LFO2ControlDepth, 2); + memcpy(&pData[70], &LFO2ControlDepth, 2); const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency); - memcpy(&pData[68], &lfo2freq, 4); + memcpy(&pData[72], &lfo2freq, 4); // next 2 bytes unknown - memcpy(&pData[72], &LFO2InternalDepth, 2); + memcpy(&pData[78], &LFO2InternalDepth, 2); const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2); - memcpy(&pData[74], &eg1decay2, 4); + memcpy(&pData[80], &eg1decay2, 4); // next 2 bytes unknown - memcpy(&pData[80], &EG1PreAttack, 2); + memcpy(&pData[86], &EG1PreAttack, 2); const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2); - memcpy(&pData[82], &eg2decay2, 4); + memcpy(&pData[88], &eg2decay2, 4); // next 2 bytes unknown - memcpy(&pData[88], &EG2PreAttack, 2); + memcpy(&pData[94], &EG2PreAttack, 2); { if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4"); @@ -1582,7 +1588,7 @@ default: throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected"); } - memcpy(&pData[90], &velocityresponse, 1); + memcpy(&pData[96], &velocityresponse, 1); } { @@ -1601,16 +1607,16 @@ default: throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected"); } - memcpy(&pData[91], &releasevelocityresponse, 1); + memcpy(&pData[97], &releasevelocityresponse, 1); } - memcpy(&pData[92], &VelocityResponseCurveScaling, 1); + memcpy(&pData[98], &VelocityResponseCurveScaling, 1); - memcpy(&pData[93], &AttenuationControllerThreshold, 1); + memcpy(&pData[99], &AttenuationControllerThreshold, 1); // next 4 bytes unknown - memcpy(&pData[98], &SampleStartOffset, 2); + memcpy(&pData[104], &SampleStartOffset, 2); // next 2 bytes unknown @@ -1629,14 +1635,14 @@ default: throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected"); } - memcpy(&pData[102], &pitchTrackDimensionBypass, 1); + memcpy(&pData[108], &pitchTrackDimensionBypass, 1); } const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit - memcpy(&pData[103], &pan, 1); + memcpy(&pData[109], &pan, 1); const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00; - memcpy(&pData[104], &selfmask, 1); + memcpy(&pData[110], &selfmask, 1); // next byte unknown @@ -1645,18 +1651,18 @@ if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5 if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7 if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6 - memcpy(&pData[106], &lfo3ctrl, 1); + memcpy(&pData[112], &lfo3ctrl, 1); } const uint8_t attenctl = EncodeLeverageController(AttenuationController); - memcpy(&pData[107], &attenctl, 1); + memcpy(&pData[113], &attenctl, 1); { uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7 if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5 if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6 - memcpy(&pData[108], &lfo2ctrl, 1); + memcpy(&pData[114], &lfo2ctrl, 1); } { @@ -1665,64 +1671,64 @@ if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6 if (VCFResonanceController != vcf_res_ctrl_none) lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController); - memcpy(&pData[109], &lfo1ctrl, 1); + memcpy(&pData[115], &lfo1ctrl, 1); } const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */ - memcpy(&pData[110], &eg3depth, 1); + memcpy(&pData[116], &eg3depth, 1); // next 2 bytes unknown const uint8_t channeloffset = ChannelOffset * 4; - memcpy(&pData[113], &channeloffset, 1); + memcpy(&pData[120], &channeloffset, 1); { uint8_t regoptions = 0; if (MSDecode) regoptions |= 0x01; // bit 0 if (SustainDefeat) regoptions |= 0x02; // bit 1 - memcpy(&pData[114], ®options, 1); + memcpy(&pData[121], ®options, 1); } // next 2 bytes unknown - memcpy(&pData[117], &VelocityUpperLimit, 1); + memcpy(&pData[124], &VelocityUpperLimit, 1); // next 3 bytes unknown - memcpy(&pData[121], &ReleaseTriggerDecay, 1); + memcpy(&pData[128], &ReleaseTriggerDecay, 1); // next 2 bytes unknown const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7 - memcpy(&pData[124], &eg1hold, 1); + memcpy(&pData[131], &eg1hold, 1); const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 | /* bit 7 */ - (VCFCutoff) ? 0x7f : 0x00; /* lower 7 bits */ - memcpy(&pData[125], &vcfcutoff, 1); + (VCFCutoff & 0x7f); /* lower 7 bits */ + memcpy(&pData[132], &vcfcutoff, 1); - memcpy(&pData[126], &VCFCutoffController, 1); + memcpy(&pData[133], &VCFCutoffController, 1); const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */ - (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */ - memcpy(&pData[127], &vcfvelscale, 1); + (VCFVelocityScale & 0x7f); /* lower 7 bits */ + memcpy(&pData[134], &vcfvelscale, 1); // next byte unknown const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */ - (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */ - memcpy(&pData[129], &vcfresonance, 1); + (VCFResonance & 0x7f); /* lower 7 bits */ + memcpy(&pData[136], &vcfresonance, 1); const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */ - (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */ - memcpy(&pData[130], &vcfbreakpoint, 1); + (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */ + memcpy(&pData[137], &vcfbreakpoint, 1); const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 | VCFVelocityCurve * 5; - memcpy(&pData[131], &vcfvelocity, 1); + memcpy(&pData[138], &vcfvelocity, 1); const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType; - memcpy(&pData[132], &vcftype, 1); + memcpy(&pData[139], &vcftype, 1); } // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet @@ -1966,6 +1972,7 @@ delete pVelocityTables; pVelocityTables = NULL; } + if (VelocityTable) delete[] VelocityTable; } /** @@ -2063,6 +2070,8 @@ // * Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) { + pInfo->UseFixedLengthStrings = true; + // Initialization Dimensions = 0; for (int i = 0; i < 256; i++) { @@ -2090,7 +2099,6 @@ pDimensionDefinitions[i].bits = 0; pDimensionDefinitions[i].zones = 0; pDimensionDefinitions[i].split_type = split_type_bit; - pDimensionDefinitions[i].ranges = NULL; pDimensionDefinitions[i].zone_size = 0; } else { // active dimension @@ -2100,10 +2108,10 @@ pDimensionDefinitions[i].split_type = (dimension == dimension_layer || dimension == dimension_samplechannel || dimension == dimension_releasetrigger || + dimension == dimension_keyboard || dimension == dimension_roundrobin || dimension == dimension_random) ? split_type_bit : split_type_normal; - pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point pDimensionDefinitions[i].zone_size = (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones : 0; @@ -2114,26 +2122,13 @@ } _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition } + for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0; - // check velocity dimension (if there is one) for custom defined zone ranges - for (uint i = 0; i < Dimensions; i++) { - dimension_def_t* pDimDef = pDimensionDefinitions + i; - if (pDimDef->dimension == dimension_velocity) { - if (pDimensionRegions[0]->VelocityUpperLimit == 0) { - // no custom defined ranges - pDimDef->split_type = split_type_normal; - pDimDef->ranges = NULL; - } - else { // custom defined ranges - pDimDef->split_type = split_type_customvelocity; - pDimDef->ranges = new range_t[pDimDef->zones]; - UpdateVelocityTable(pDimDef); - } - } - } + // if there's a velocity dimension and custom velocity zone splits are used, + // update the VelocityTables in the dimension regions + UpdateVelocityTable(); // jump to start of the wave pool indices (if not already there) - File* file = (File*) GetParent()->GetParent(); if (file->pVersion && file->pVersion->major == 3) _3lnk->SetPos(68); // version 3 has a different 3lnk structure else @@ -2142,8 +2137,18 @@ // load sample references for (uint i = 0; i < DimensionRegions; i++) { uint32_t wavepoolindex = _3lnk->ReadUint32(); - pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); + if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); } + GetSample(); // load global region sample reference + } + + // make sure there is at least one dimension region + if (!DimensionRegions) { + RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG); + if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG); + RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL); + pDimensionRegions[0] = new DimensionRegion(_3ewl); + DimensionRegions = 1; } } @@ -2161,8 +2166,9 @@ DLS::Region::UpdateChunks(); // update dimension region's chunks - for (int i = 0; i < Dimensions; i++) + for (int i = 0; i < DimensionRegions; i++) { pDimensionRegions[i]->UpdateChunks(); + } File* pFile = (File*) GetParent()->GetParent(); const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5; @@ -2177,11 +2183,12 @@ // update dimension definitions in '3lnk' chunk uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData(); + memcpy(&pData[0], &DimensionRegions, 4); for (int i = 0; i < iMaxDimensions; i++) { - pData[i * 8] = (uint8_t) pDimensionDefinitions[i].dimension; - pData[i * 8 + 1] = pDimensionDefinitions[i].bits; + pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension; + pData[5 + i * 8] = pDimensionDefinitions[i].bits; // next 2 bytes unknown - pData[i * 8 + 4] = pDimensionDefinitions[i].zones; + pData[8 + i * 8] = pDimensionDefinitions[i].zones; // next 3 bytes unknown } @@ -2190,12 +2197,14 @@ for (uint i = 0; i < iMaxDimensionRegions; i++) { int iWaveIndex = -1; if (i < DimensionRegions) { - if (!pFile->pSamples) throw gig::Exception("Could not update gig::Region, there are no samples"); - std::list::iterator iter = pFile->pSamples->begin(); - std::list::iterator end = pFile->pSamples->end(); + if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples"); + File::SampleList::iterator iter = pFile->pSamples->begin(); + File::SampleList::iterator end = pFile->pSamples->end(); for (int index = 0; iter != end; ++iter, ++index) { - if (*iter == pDimensionRegions[i]->pSample) iWaveIndex = index; - break; + if (*iter == pDimensionRegions[i]->pSample) { + iWaveIndex = index; + break; + } } if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample"); } @@ -2219,30 +2228,64 @@ } } - void Region::UpdateVelocityTable(dimension_def_t* pDimDef) { - // get dimension's index - int iDimensionNr = -1; - for (int i = 0; i < Dimensions; i++) { - if (&pDimensionDefinitions[i] == pDimDef) { - iDimensionNr = i; + void Region::UpdateVelocityTable() { + // get velocity dimension's index + int veldim = -1; + for (int i = 0 ; i < Dimensions ; i++) { + if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) { + veldim = i; break; } } - if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer"); + if (veldim == -1) return; + + int step = 1; + for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits; + int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step; + int end = step * pDimensionDefinitions[veldim].zones; + + // loop through all dimension regions for all dimensions except the velocity dimension + int dim[8] = { 0 }; + for (int i = 0 ; i < DimensionRegions ; i++) { + + if (pDimensionRegions[i]->VelocityUpperLimit) { + // create the velocity table + uint8_t* table = pDimensionRegions[i]->VelocityTable; + if (!table) { + table = new uint8_t[128]; + pDimensionRegions[i]->VelocityTable = table; + } + int tableidx = 0; + int velocityZone = 0; + for (int k = i ; k < end ; k += step) { + DimensionRegion *d = pDimensionRegions[k]; + for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone; + velocityZone++; + } + } else { + if (pDimensionRegions[i]->VelocityTable) { + delete[] pDimensionRegions[i]->VelocityTable; + pDimensionRegions[i]->VelocityTable = 0; + } + } - uint8_t bits[8] = { 0 }; - int previousUpperLimit = -1; - for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) { - bits[iDimensionNr] = velocityZone; - DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits); - - pDimDef->ranges[velocityZone].low = previousUpperLimit + 1; - pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit; - previousUpperLimit = pDimDef->ranges[velocityZone].high; - // fill velocity table - for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) { - VelocityTable[i] = velocityZone; + int j; + int shift = 0; + for (j = 0 ; j < Dimensions ; j++) { + if (j == veldim) i += skipveldim; // skip velocity dimension + else { + dim[j]++; + if (dim[j] < pDimensionDefinitions[j].zones) break; + else { + // skip unused dimension regions + dim[j] = 0; + i += ((1 << pDimensionDefinitions[j].bits) - + pDimensionDefinitions[j].zones) << shift; + } + } + shift += pDimensionDefinitions[j].bits; } + if (j == Dimensions) break; } } @@ -2297,11 +2340,7 @@ // if this is a layer dimension, update 'Layers' attribute if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones; - // if this is velocity dimension and got custom defined ranges, update velocity table - if (pDimDef->dimension == dimension_velocity && - pDimDef->split_type == split_type_customvelocity) { - UpdateVelocityTable(pDimDef); - } + UpdateVelocityTable(); } /** @brief Delete an existing dimension. @@ -2371,10 +2410,6 @@ pDimensionDefinitions[Dimensions - 1].dimension = dimension_none; pDimensionDefinitions[Dimensions - 1].bits = 0; pDimensionDefinitions[Dimensions - 1].zones = 0; - if (pDimensionDefinitions[Dimensions - 1].ranges) { - delete[] pDimensionDefinitions[Dimensions - 1].ranges; - pDimensionDefinitions[Dimensions - 1].ranges = NULL; - } Dimensions--; @@ -2383,9 +2418,6 @@ } Region::~Region() { - for (uint i = 0; i < Dimensions; i++) { - if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges; - } for (int i = 0; i < 256; i++) { if (pDimensionRegions[i]) delete pDimensionRegions[i]; } @@ -2410,23 +2442,42 @@ * @see Dimensions */ DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) { - uint8_t bits[8] = { 0 }; + uint8_t bits; + int veldim = -1; + int velbitpos; + int bitpos = 0; + int dimregidx = 0; for (uint i = 0; i < Dimensions; i++) { - bits[i] = DimValues[i]; - switch (pDimensionDefinitions[i].split_type) { - case split_type_normal: - bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size); - break; - case split_type_customvelocity: - bits[i] = VelocityTable[bits[i]]; - break; - case split_type_bit: // the value is already the sought dimension bit number - const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff; - bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed - break; + if (pDimensionDefinitions[i].dimension == dimension_velocity) { + // the velocity dimension must be handled after the other dimensions + veldim = i; + velbitpos = bitpos; + } else { + switch (pDimensionDefinitions[i].split_type) { + case split_type_normal: + bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size); + break; + case split_type_bit: // the value is already the sought dimension bit number + const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff; + bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed + break; + } + dimregidx |= bits << bitpos; } + bitpos += pDimensionDefinitions[i].bits; } - return GetDimensionRegionByBit(bits); + DimensionRegion* dimreg = pDimensionRegions[dimregidx]; + if (veldim != -1) { + // (dimreg is now the dimension region for the lowest velocity) + if (dimreg->VelocityUpperLimit) // custom defined zone ranges + bits = dimreg->VelocityTable[DimValues[veldim]]; + else // normal split type + bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size); + + dimregidx |= bits << velbitpos; + dimreg = pDimensionRegions[dimregidx]; + } + return dimreg; } /** @@ -2466,12 +2517,13 @@ Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) { if ((int32_t)WavePoolTableIndex == -1) return NULL; File* file = (File*) GetParent()->GetParent(); + if (!file->pWavePoolTable) return NULL; unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex]; unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex]; Sample* sample = file->GetFirstSample(pProgress); while (sample) { if (sample->ulWavePoolOffset == soughtoffset && - sample->FileNo == soughtfileno) return static_cast(pSample = sample); + sample->FileNo == soughtfileno) return static_cast(sample); sample = file->GetNextSample(); } return NULL; @@ -2483,9 +2535,10 @@ // * Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) { + pInfo->UseFixedLengthStrings = true; + // Initialization for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL; - RegionIndex = -1; // Loading RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART); @@ -2503,17 +2556,14 @@ } } - pRegions = new Region*[Regions]; + if (!pRegions) pRegions = new RegionList; RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN); if (lrgn) { - for (uint i = 0; i < Regions; i++) pRegions[i] = NULL; RIFF::List* rgn = lrgn->GetFirstSubList(); - unsigned int iRegion = 0; while (rgn) { if (rgn->GetListType() == LIST_TYPE_RGN) { - __notify_progress(pProgress, (float) iRegion / (float) Regions); - pRegions[iRegion] = new Region(this, rgn); - iRegion++; + __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); + pRegions->push_back(new Region(this, rgn)); } rgn = lrgn->GetNextSubList(); } @@ -2525,20 +2575,17 @@ } void Instrument::UpdateRegionKeyTable() { - for (uint iReg = 0; iReg < Regions; iReg++) { - for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) { - RegionKeyTable[iKey] = pRegions[iReg]; + RegionList::iterator iter = pRegions->begin(); + RegionList::iterator end = pRegions->end(); + for (; iter != end; ++iter) { + gig::Region* pRegion = static_cast(*iter); + for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) { + RegionKeyTable[iKey] = pRegion; } } } Instrument::~Instrument() { - for (uint i = 0; i < Regions; i++) { - if (pRegions) { - if (pRegions[i]) delete (pRegions[i]); - } - } - if (pRegions) delete[] pRegions; } /** @@ -2555,8 +2602,12 @@ DLS::Instrument::UpdateChunks(); // update Regions' chunks - for (int i = 0; i < Regions; i++) - pRegions[i]->UpdateChunks(); + { + RegionList::iterator iter = pRegions->begin(); + RegionList::iterator end = pRegions->end(); + for (; iter != end; ++iter) + (*iter)->UpdateChunks(); + } // make sure 'lart' RIFF list chunk exists RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART); @@ -2584,8 +2635,9 @@ * there is no Region defined for the given \a Key */ Region* Instrument::GetRegion(unsigned int Key) { - if (!pRegions || Key > 127) return NULL; + if (!pRegions || !pRegions->size() || Key > 127) return NULL; return RegionKeyTable[Key]; + /*for (int i = 0; i < Regions; i++) { if (Key <= pRegions[i]->KeyRange.high && Key >= pRegions[i]->KeyRange.low) return pRegions[i]; @@ -2601,9 +2653,9 @@ * @see GetNextRegion() */ Region* Instrument::GetFirstRegion() { - if (!Regions) return NULL; - RegionIndex = 1; - return pRegions[0]; + if (!pRegions) return NULL; + RegionsIterator = pRegions->begin(); + return static_cast( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL ); } /** @@ -2615,8 +2667,9 @@ * @see GetFirstRegion() */ Region* Instrument::GetNextRegion() { - if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL; - return pRegions[RegionIndex++]; + if (!pRegions) return NULL; + RegionsIterator++; + return static_cast( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL ); } Region* Instrument::AddRegion() { @@ -2625,15 +2678,8 @@ if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN); RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN); Region* pNewRegion = new Region(this, rgn); - // resize 'pRegions' array (increase by one) - Region** pNewRegions = new Region*[Regions + 1]; - memcpy(pNewRegions, pRegions, Regions * sizeof(Region*)); - // add new Region object - pNewRegions[Regions] = pNewRegion; - // replace old 'pRegions' array by the new increased array - if (pRegions) delete[] pRegions; - pRegions = pNewRegions; - Regions++; + pRegions->push_back(pNewRegion); + Regions = pRegions->size(); // update Region key table for fast lookup UpdateRegionKeyTable(); // done @@ -2642,65 +2688,137 @@ void Instrument::DeleteRegion(Region* pRegion) { if (!pRegions) return; - int iOffset = 0; - // resize 'pRegions' array (decrease by one) - Region** pNewRegions = new Region*[Regions - 1]; - for (int i = 0; i < Regions; i++) { - if (pRegions[i] == pRegion) { // found Region to delete - iOffset = 1; - delete pRegion; - } - if (i < Regions - 1) pNewRegions[i] = pRegions[i + iOffset]; - } - if (!iOffset) throw gig::Exception("There is no such gig::Region to delete"); - // replace old 'pRegions' array by the new decreased array - if (pRegions) delete[] pRegions; - pRegions = pNewRegions; - Regions--; + DLS::Instrument::DeleteRegion((DLS::Region*) pRegion); // update Region key table for fast lookup UpdateRegionKeyTable(); } +// *************** Group *************** +// * + + /** @brief Constructor. + * + * @param file - pointer to the gig::File object + * @param ck3gnm - pointer to 3gnm chunk associated with this group or + * NULL if this is a new Group + */ + Group::Group(File* file, RIFF::Chunk* ck3gnm) { + pFile = file; + pNameChunk = ck3gnm; + ::LoadString(pNameChunk, Name); + } + + Group::~Group() { + } + + /** @brief Update chunks with current group settings. + * + * Apply current Group field values to the respective. You have to call + * File::Save() to make changes persistent. + */ + void Group::UpdateChunks() { + // make sure <3gri> and <3gnl> list chunks exist + RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI); + if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI); + RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL); + if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL); + // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk + ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64); + } + + /** + * Returns the first Sample of this Group. You have to call this method + * once before you use GetNextSample(). + * + * Notice: this method might block for a long time, in case the + * samples of this .gig file were not scanned yet + * + * @returns pointer address to first Sample or NULL if there is none + * applied to this Group + * @see GetNextSample() + */ + Sample* Group::GetFirstSample() { + // FIXME: lazy und unsafe implementation, should be an autonomous iterator + for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) { + if (pSample->GetGroup() == this) return pSample; + } + return NULL; + } + + /** + * Returns the next Sample of the Group. You have to call + * GetFirstSample() once before you can use this method. By calling this + * method multiple times it iterates through the Samples assigned to + * this Group. + * + * @returns pointer address to the next Sample of this Group or NULL if + * end reached + * @see GetFirstSample() + */ + Sample* Group::GetNextSample() { + // FIXME: lazy und unsafe implementation, should be an autonomous iterator + for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) { + if (pSample->GetGroup() == this) return pSample; + } + return NULL; + } + + /** + * Move Sample given by \a pSample from another Group to this Group. + */ + void Group::AddSample(Sample* pSample) { + pSample->pGroup = this; + } + + /** + * Move all members of this group to another group (preferably the 1st + * one except this). This method is called explicitly by + * File::DeleteGroup() thus when a Group was deleted. This code was + * intentionally not placed in the destructor! + */ + void Group::MoveAll() { + // get "that" other group first + Group* pOtherGroup = NULL; + for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) { + if (pOtherGroup != this) break; + } + if (!pOtherGroup) throw Exception( + "Could not move samples to another group, since there is no " + "other Group. This is a bug, report it!" + ); + // now move all samples of this group to the other group + for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { + pOtherGroup->AddSample(pSample); + } + } + + + // *************** File *************** // * File::File() : DLS::File() { - pSamples = NULL; - pInstruments = NULL; + pGroups = NULL; + pInfo->UseFixedLengthStrings = true; } File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) { - pSamples = NULL; - pInstruments = NULL; + pGroups = NULL; + pInfo->UseFixedLengthStrings = true; } File::~File() { - // free samples - if (pSamples) { - SamplesIterator = pSamples->begin(); - while (SamplesIterator != pSamples->end() ) { - delete (*SamplesIterator); - SamplesIterator++; - } - pSamples->clear(); - delete pSamples; - - } - // free instruments - if (pInstruments) { - InstrumentsIterator = pInstruments->begin(); - while (InstrumentsIterator != pInstruments->end() ) { - delete (*InstrumentsIterator); - InstrumentsIterator++; - } - pInstruments->clear(); - delete pInstruments; - } - // free extension files - for (std::list::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++) - delete *i; + if (pGroups) { + std::list::iterator iter = pGroups->begin(); + std::list::iterator end = pGroups->end(); + while (iter != end) { + delete *iter; + ++iter; + } + delete pGroups; + } } Sample* File::GetFirstSample(progress_t* pProgress) { @@ -2728,7 +2846,6 @@ __ensureMandatoryChunksExist(); RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL); // create new Sample object and its respective 'wave' list chunk - if (!pSamples) pSamples = new SampleList; RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE); Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/); pSamples->push_back(pSample); @@ -2744,14 +2861,24 @@ * @throws gig::Exception if given sample could not be found */ void File::DeleteSample(Sample* pSample) { - if (!pSamples) throw gig::Exception("Could not delete sample as there are no samples"); - SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample); + if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples"); + SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample); if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample"); pSamples->erase(iter); delete pSample; } + void File::LoadSamples() { + LoadSamples(NULL); + } + void File::LoadSamples(progress_t* pProgress) { + // Groups must be loaded before samples, because samples will try + // to resolve the group they belong to + LoadGroups(); + + if (!pSamples) pSamples = new SampleList; + RIFF::File* file = pRIFF; // just for progress calculation @@ -2779,7 +2906,6 @@ const float subprogress = (float) iSampleIndex / (float) iTotalSamples; __notify_progress(pProgress, subprogress); - if (!pSamples) pSamples = new SampleList; unsigned long waveFileOffset = wave->GetFilePos(); pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo)); @@ -2796,8 +2922,7 @@ name.replace(nameLen, 5, suffix); file = new RIFF::File(name); ExtensionFiles.push_back(file); - } - else throw gig::Exception("Mandatory chunk not found."); + } else break; } __notify_progress(pProgress, 1.0); // notify done @@ -2807,13 +2932,13 @@ if (!pInstruments) LoadInstruments(); if (!pInstruments) return NULL; InstrumentsIterator = pInstruments->begin(); - return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL; + return static_cast( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL ); } Instrument* File::GetNextInstrument() { if (!pInstruments) return NULL; InstrumentsIterator++; - return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL; + return static_cast( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL ); } /** @@ -2846,7 +2971,7 @@ if (!pInstruments) return NULL; InstrumentsIterator = pInstruments->begin(); for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) { - if (i == index) return *InstrumentsIterator; + if (i == index) return static_cast( *InstrumentsIterator ); InstrumentsIterator++; } return NULL; @@ -2862,7 +2987,6 @@ Instrument* File::AddInstrument() { if (!pInstruments) LoadInstruments(); __ensureMandatoryChunksExist(); - if (!pInstruments) pInstruments = new InstrumentList; RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS); RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS); Instrument* pInstrument = new Instrument(this, lstInstr); @@ -2880,13 +3004,18 @@ */ void File::DeleteInstrument(Instrument* pInstrument) { if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments"); - InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument); + InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument); if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument"); pInstruments->erase(iter); delete pInstrument; } + void File::LoadInstruments() { + LoadInstruments(NULL); + } + void File::LoadInstruments(progress_t* pProgress) { + if (!pInstruments) pInstruments = new InstrumentList; RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS); if (lstInstruments) { int iInstrumentIndex = 0; @@ -2901,7 +3030,6 @@ progress_t subprogress; __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex); - if (!pInstruments) pInstruments = new InstrumentList; pInstruments->push_back(new Instrument(this, lstInstr, &subprogress)); iInstrumentIndex++; @@ -2910,7 +3038,79 @@ } __notify_progress(pProgress, 1.0); // notify done } - else throw gig::Exception("Mandatory list chunk not found."); + } + + Group* File::GetFirstGroup() { + if (!pGroups) LoadGroups(); + // there must always be at least one group + GroupsIterator = pGroups->begin(); + return *GroupsIterator; + } + + Group* File::GetNextGroup() { + if (!pGroups) return NULL; + ++GroupsIterator; + return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator; + } + + /** + * Returns the group with the given index. + * + * @param index - number of the sought group (0..n) + * @returns sought group or NULL if there's no such group + */ + Group* File::GetGroup(uint index) { + if (!pGroups) LoadGroups(); + GroupsIterator = pGroups->begin(); + for (uint i = 0; GroupsIterator != pGroups->end(); i++) { + if (i == index) return *GroupsIterator; + ++GroupsIterator; + } + return NULL; + } + + Group* File::AddGroup() { + if (!pGroups) LoadGroups(); + // there must always be at least one group + __ensureMandatoryChunksExist(); + Group* pGroup = new Group(this, NULL); + pGroups->push_back(pGroup); + return pGroup; + } + + void File::DeleteGroup(Group* pGroup) { + if (!pGroups) LoadGroups(); + std::list::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup); + if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group"); + if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!"); + // move all members of this group to another group + pGroup->MoveAll(); + pGroups->erase(iter); + delete pGroup; + } + + void File::LoadGroups() { + if (!pGroups) pGroups = new std::list; + // try to read defined groups from file + RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI); + if (lst3gri) { + RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL); + if (lst3gnl) { + RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk(); + while (ck) { + if (ck->GetChunkID() == CHUNK_ID_3GNM) { + pGroups->push_back(new Group(this, ck)); + } + ck = lst3gnl->GetNextSubChunk(); + } + } + } + // if there were no group(s), create at least the mandatory default group + if (!pGroups->size()) { + Group* pGroup = new Group(this, NULL); + pGroup->Name = "Default Group"; + pGroups->push_back(pGroup); + } }