--- libgig/trunk/src/gig.cpp 2007/05/20 10:11:39 1199 +++ libgig/trunk/src/gig.cpp 2013/01/07 23:23:58 2394 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2007 by Christian Schoenebeck * + * Copyright (C) 2003-2013 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -25,6 +25,7 @@ #include "helper.h" +#include #include #include @@ -255,6 +256,69 @@ +// *************** Internal CRC-32 (Cyclic Redundancy Check) functions *************** +// * + + static uint32_t* __initCRCTable() { + static uint32_t res[256]; + + for (int i = 0 ; i < 256 ; i++) { + uint32_t c = i; + for (int j = 0 ; j < 8 ; j++) { + c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1; + } + res[i] = c; + } + return res; + } + + static const uint32_t* __CRCTable = __initCRCTable(); + + /** + * Initialize a CRC variable. + * + * @param crc - variable to be initialized + */ + inline static void __resetCRC(uint32_t& crc) { + crc = 0xffffffff; + } + + /** + * Used to calculate checksums of the sample data in a gig file. The + * checksums are stored in the 3crc chunk of the gig file and + * automatically updated when a sample is written with Sample::Write(). + * + * One should call __resetCRC() to initialize the CRC variable to be + * used before calling this function the first time. + * + * After initializing the CRC variable one can call this function + * arbitrary times, i.e. to split the overall CRC calculation into + * steps. + * + * Once the whole data was processed by __calculateCRC(), one should + * call __encodeCRC() to get the final CRC result. + * + * @param buf - pointer to data the CRC shall be calculated of + * @param bufSize - size of the data to be processed + * @param crc - variable the CRC sum shall be stored to + */ + static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) { + for (int i = 0 ; i < bufSize ; i++) { + crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); + } + } + + /** + * Returns the final CRC result. + * + * @param crc - variable previously passed to __calculateCRC() + */ + inline static uint32_t __encodeCRC(const uint32_t& crc) { + return crc ^ 0xffffffff; + } + + + // *************** Other Internal functions *************** // * @@ -278,26 +342,6 @@ -// *************** CRC *************** -// * - - const uint32_t* CRC::table(initTable()); - - uint32_t* CRC::initTable() { - uint32_t* res = new uint32_t[256]; - - for (int i = 0 ; i < 256 ; i++) { - uint32_t c = i; - for (int j = 0 ; j < 8 ; j++) { - c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1; - } - res[i] = c; - } - return res; - } - - - // *************** Sample *************** // * @@ -323,14 +367,16 @@ * is located, 0 otherwise */ Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) { - static const DLS::Info::FixedStringLength fixedStringLengths[] = { + static const DLS::Info::string_length_t fixedStringLengths[] = { { CHUNK_ID_INAM, 64 }, { 0, 0 } }; - pInfo->FixedStringLengths = fixedStringLengths; + pInfo->SetFixedStringLengths(fixedStringLengths); Instances++; FileNo = fileNo; + __resetCRC(crc); + pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX); if (pCk3gix) { uint16_t iSampleGroup = pCk3gix->ReadInt16(); @@ -362,7 +408,7 @@ Manufacturer = 0; Product = 0; SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5); - MIDIUnityNote = 64; + MIDIUnityNote = 60; FineTune = 0; SMPTEFormat = smpte_format_no_offset; SMPTEOffset = 0; @@ -631,6 +677,7 @@ if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal; if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart; unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize; + SetPos(0); // reset read position to begin of sample RAMCache.pStart = new int8_t[allocationsize]; RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize; RAMCache.NullExtensionSize = allocationsize - RAMCache.Size; @@ -668,6 +715,7 @@ if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart; RAMCache.pStart = NULL; RAMCache.Size = 0; + RAMCache.NullExtensionSize = 0; } /** @brief Resize sample. @@ -862,7 +910,8 @@ } // reverse the sample frames for backward playback - SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); + if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above! + SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize); } } while (samplestoread && readsamples); break; @@ -1152,6 +1201,10 @@ * * Note: there is currently no support for writing compressed samples. * + * For 16 bit samples, the data in the source buffer should be + * int16_t (using native endianness). For 24 bit, the buffer + * should contain three bytes per sample, little-endian. + * * @param pBuffer - source buffer * @param SampleCount - number of sample points to write * @throws DLS::Exception if current sample size is too small @@ -1160,15 +1213,27 @@ */ unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) { if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)"); + + // if this is the first write in this sample, reset the + // checksum calculator if (pCkData->GetPos() == 0) { - crc.reset(); + __resetCRC(crc); } - unsigned long res = DLS::Sample::Write(pBuffer, SampleCount); - crc.update((unsigned char *)pBuffer, SampleCount * FrameSize); + if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small"); + unsigned long res; + if (BitDepth == 24) { + res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize; + } else { // 16 bit + res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1 + : pCkData->Write(pBuffer, SampleCount, 2); + } + __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc); + // if this is the last write, update the checksum chunk in the + // file if (pCkData->GetPos() == pCkData->GetSize()) { File* pFile = static_cast(GetParent()); - pFile->SetSampleChecksum(this, crc.getValue()); + pFile->SetSampleChecksum(this, __encodeCRC(crc)); } return res; } @@ -1246,12 +1311,15 @@ uint DimensionRegion::Instances = 0; DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL; - DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) { + DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) { Instances++; pSample = NULL; + pRegion = pParent; + + if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4); + else memset(&Crossfade, 0, 4); - memcpy(&Crossfade, &SamplerOptions, 4); if (!pVelocityTables) pVelocityTables = new VelocityTableMap; RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA); @@ -1415,9 +1483,9 @@ LFO1ControlDepth = 0; LFO3ControlDepth = 0; EG1Attack = 0.0; - EG1Decay1 = 0.0; - EG1Sustain = 0; - EG1Release = 0.0; + EG1Decay1 = 0.005; + EG1Sustain = 1000; + EG1Release = 0.3; EG1Controller.type = eg1_ctrl_t::type_none; EG1Controller.controller_number = 0; EG1ControllerInvert = false; @@ -1432,18 +1500,18 @@ EG2ControllerReleaseInfluence = 0; LFO1Frequency = 1.0; EG2Attack = 0.0; - EG2Decay1 = 0.0; - EG2Sustain = 0; - EG2Release = 0.0; + EG2Decay1 = 0.005; + EG2Sustain = 1000; + EG2Release = 0.3; LFO2ControlDepth = 0; LFO2Frequency = 1.0; LFO2InternalDepth = 0; EG1Decay2 = 0.0; - EG1InfiniteSustain = false; - EG1PreAttack = 1000; + EG1InfiniteSustain = true; + EG1PreAttack = 0; EG2Decay2 = 0.0; - EG2InfiniteSustain = false; - EG2PreAttack = 1000; + EG2InfiniteSustain = true; + EG2PreAttack = 0; VelocityResponseCurve = curve_type_nonlinear; VelocityResponseDepth = 3; ReleaseVelocityResponseCurve = curve_type_nonlinear; @@ -1486,42 +1554,92 @@ VCFVelocityDynamicRange = 0x04; VCFVelocityCurve = curve_type_linear; VCFType = vcf_type_lowpass; - memset(DimensionUpperLimits, 0, 8); + memset(DimensionUpperLimits, 127, 8); } pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve, VelocityResponseDepth, VelocityResponseCurveScaling); - curve_type_t curveType = ReleaseVelocityResponseCurve; - uint8_t depth = ReleaseVelocityResponseDepth; + pVelocityReleaseTable = GetReleaseVelocityTable( + ReleaseVelocityResponseCurve, + ReleaseVelocityResponseDepth + ); + + pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, + VCFVelocityDynamicRange, + VCFVelocityScale, + VCFCutoffController); - // this models a strange behaviour or bug in GSt: two of the - // velocity response curves for release time are not used even - // if specified, instead another curve is chosen. - if ((curveType == curve_type_nonlinear && depth == 0) || - (curveType == curve_type_special && depth == 4)) { - curveType = curve_type_nonlinear; - depth = 3; - } - pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0); + SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360)); + VelocityTable = 0; + } - curveType = VCFVelocityCurve; - depth = VCFVelocityDynamicRange; + /* + * Constructs a DimensionRegion by copying all parameters from + * another DimensionRegion + */ + DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) { + Instances++; + //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method + *this = src; // default memberwise shallow copy of all parameters + pParentList = _3ewl; // restore the chunk pointer - // even stranger GSt: two of the velocity response curves for - // filter cutoff are not used, instead another special curve - // is chosen. This curve is not used anywhere else. - if ((curveType == curve_type_nonlinear && depth == 0) || - (curveType == curve_type_special && depth == 4)) { - curveType = curve_type_special; - depth = 5; + // deep copy of owned structures + if (src.VelocityTable) { + VelocityTable = new uint8_t[128]; + for (int k = 0 ; k < 128 ; k++) + VelocityTable[k] = src.VelocityTable[k]; + } + if (src.pSampleLoops) { + pSampleLoops = new DLS::sample_loop_t[src.SampleLoops]; + for (int k = 0 ; k < src.SampleLoops ; k++) + pSampleLoops[k] = src.pSampleLoops[k]; + } + } + + /** + * Make a (semi) deep copy of the DimensionRegion object given by @a orig + * and assign it to this object. + * + * Note that all sample pointers referenced by @a orig are simply copied as + * memory address. Thus the respective samples are shared, not duplicated! + * + * @param orig - original DimensionRegion object to be copied from + */ + void DimensionRegion::CopyAssign(const DimensionRegion* orig) { + // delete all allocated data first + if (VelocityTable) delete [] VelocityTable; + if (pSampleLoops) delete [] pSampleLoops; + + // backup parent list pointer + RIFF::List* p = pParentList; + + //NOTE: copy code copied from assignment constructor above, see comment there as well + + *this = *orig; // default memberwise shallow copy of all parameters + pParentList = p; // restore the chunk pointer + + // deep copy of owned structures + if (orig->VelocityTable) { + VelocityTable = new uint8_t[128]; + for (int k = 0 ; k < 128 ; k++) + VelocityTable[k] = orig->VelocityTable[k]; + } + if (orig->pSampleLoops) { + pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops]; + for (int k = 0 ; k < orig->SampleLoops ; k++) + pSampleLoops[k] = orig->pSampleLoops[k]; } - pVelocityCutoffTable = GetVelocityTable(curveType, depth, - VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0); + } + /** + * Updates the respective member variable and updates @c SampleAttenuation + * which depends on this value. + */ + void DimensionRegion::SetGain(int32_t gain) { + DLS::Sampler::SetGain(gain); SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360)); - VelocityTable = 0; } /** @@ -1535,10 +1653,21 @@ // first update base class's chunk DLS::Sampler::UpdateChunks(); + RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP); + uint8_t* pData = (uint8_t*) wsmp->LoadChunkData(); + pData[12] = Crossfade.in_start; + pData[13] = Crossfade.in_end; + pData[14] = Crossfade.out_start; + pData[15] = Crossfade.out_end; + // make sure '3ewa' chunk exists RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA); - if (!_3ewa) _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140); - uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData(); + if (!_3ewa) { + File* pFile = (File*) GetParent()->GetParent()->GetParent(); + bool version3 = pFile->pVersion && pFile->pVersion->major == 3; + _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140); + } + pData = (uint8_t*) _3ewa->LoadChunkData(); // update '3ewa' chunk with DimensionRegion's current settings @@ -1584,7 +1713,7 @@ pData[44] = eg1ctl; const uint8_t eg1ctrloptions = - (EG1ControllerInvert) ? 0x01 : 0x00 | + (EG1ControllerInvert ? 0x01 : 0x00) | GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) | GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) | GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence); @@ -1594,7 +1723,7 @@ pData[46] = eg2ctl; const uint8_t eg2ctrloptions = - (EG2ControllerInvert) ? 0x01 : 0x00 | + (EG2ControllerInvert ? 0x01 : 0x00) | GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) | GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) | GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence); @@ -1745,7 +1874,7 @@ const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */ - pData[116] = eg3depth; + store16(&pData[116], eg3depth); // next 2 bytes unknown @@ -1772,27 +1901,27 @@ const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7 pData[131] = eg1hold; - const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 | /* bit 7 */ + const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */ (VCFCutoff & 0x7f); /* lower 7 bits */ pData[132] = vcfcutoff; pData[133] = VCFCutoffController; - const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */ + const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */ (VCFVelocityScale & 0x7f); /* lower 7 bits */ pData[134] = vcfvelscale; // next byte unknown - const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */ + const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */ (VCFResonance & 0x7f); /* lower 7 bits */ pData[136] = vcfresonance; - const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */ + const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */ (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */ pData[137] = vcfbreakpoint; - const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 | + const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 + VCFVelocityCurve * 5; pData[138] = vcfvelocity; @@ -1804,6 +1933,40 @@ } } + double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) { + curve_type_t curveType = releaseVelocityResponseCurve; + uint8_t depth = releaseVelocityResponseDepth; + // this models a strange behaviour or bug in GSt: two of the + // velocity response curves for release time are not used even + // if specified, instead another curve is chosen. + if ((curveType == curve_type_nonlinear && depth == 0) || + (curveType == curve_type_special && depth == 4)) { + curveType = curve_type_nonlinear; + depth = 3; + } + return GetVelocityTable(curveType, depth, 0); + } + + double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve, + uint8_t vcfVelocityDynamicRange, + uint8_t vcfVelocityScale, + vcf_cutoff_ctrl_t vcfCutoffController) + { + curve_type_t curveType = vcfVelocityCurve; + uint8_t depth = vcfVelocityDynamicRange; + // even stranger GSt: two of the velocity response curves for + // filter cutoff are not used, instead another special curve + // is chosen. This curve is not used anywhere else. + if ((curveType == curve_type_nonlinear && depth == 0) || + (curveType == curve_type_special && depth == 4)) { + curveType = curve_type_special; + depth = 5; + } + return GetVelocityTable(curveType, depth, + (vcfCutoffController <= vcf_cutoff_ctrl_none2) + ? vcfVelocityScale : 0); + } + // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) { @@ -1819,6 +1982,10 @@ return table; } + Region* DimensionRegion::GetParent() const { + return pRegion; + } + leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) { leverage_ctrl_t decodedcontroller; switch (EncodedController) { @@ -2072,6 +2239,96 @@ return pVelocityCutoffTable[MIDIKeyVelocity]; } + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) { + pVelocityAttenuationTable = + GetVelocityTable( + curve, VelocityResponseDepth, VelocityResponseCurveScaling + ); + VelocityResponseCurve = curve; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) { + pVelocityAttenuationTable = + GetVelocityTable( + VelocityResponseCurve, depth, VelocityResponseCurveScaling + ); + VelocityResponseDepth = depth; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) { + pVelocityAttenuationTable = + GetVelocityTable( + VelocityResponseCurve, VelocityResponseDepth, scaling + ); + VelocityResponseCurveScaling = scaling; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) { + pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth); + ReleaseVelocityResponseCurve = curve; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) { + pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth); + ReleaseVelocityResponseDepth = depth; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) { + pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller); + VCFCutoffController = controller; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) { + pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController); + VCFVelocityCurve = curve; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) { + pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController); + VCFVelocityDynamicRange = range; + } + + /** + * Updates the respective member variable and the lookup table / cache + * that depends on this value. + */ + void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) { + pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController); + VCFVelocityScale = scaling; + } + double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) { // line-segment approximations of the 15 velocity curves @@ -2155,6 +2412,8 @@ // Actual Loading + if (!file->GetAutoLoad()) return; + LoadDimensionRegions(rgnList); RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK); @@ -2198,12 +2457,14 @@ else _3lnk->SetPos(44); - // load sample references - for (uint i = 0; i < DimensionRegions; i++) { - uint32_t wavepoolindex = _3lnk->ReadUint32(); - if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); + // load sample references (if auto loading is enabled) + if (file->GetAutoLoad()) { + for (uint i = 0; i < DimensionRegions; i++) { + uint32_t wavepoolindex = _3lnk->ReadUint32(); + if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); + } + GetSample(); // load global region sample reference } - GetSample(); // load global region sample reference } else { DimensionRegions = 0; for (int i = 0 ; i < 8 ; i++) { @@ -2218,7 +2479,7 @@ 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); + pDimensionRegions[0] = new DimensionRegion(this, _3ewl); DimensionRegions = 1; } } @@ -2248,13 +2509,14 @@ } File* pFile = (File*) GetParent()->GetParent(); - const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5; - const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32; + bool version3 = pFile->pVersion && pFile->pVersion->major == 3; + const int iMaxDimensions = version3 ? 8 : 5; + const int iMaxDimensionRegions = version3 ? 256 : 32; // make sure '3lnk' chunk exists RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK); if (!_3lnk) { - const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172; + const int _3lnkChunkSize = version3 ? 1092 : 172; _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize); memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize); @@ -2269,7 +2531,7 @@ for (int i = 0; i < iMaxDimensions; i++) { pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension; pData[5 + i * 8] = pDimensionDefinitions[i].bits; - pData[6 + i * 8] = shift; + pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift; pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift); pData[8 + i * 8] = pDimensionDefinitions[i].zones; // next 3 bytes unknown, always zero? @@ -2278,7 +2540,7 @@ } // update wave pool table in '3lnk' chunk - const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44; + const int iWavePoolOffset = version3 ? 68 : 44; for (uint i = 0; i < iMaxDimensionRegions; i++) { int iWaveIndex = -1; if (i < DimensionRegions) { @@ -2291,7 +2553,6 @@ break; } } - if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample"); } store32(&pData[iWavePoolOffset + i * 4], iWaveIndex); } @@ -2304,7 +2565,7 @@ RIFF::List* _3ewl = _3prg->GetFirstSubList(); while (_3ewl) { if (_3ewl->GetListType() == LIST_TYPE_3EWL) { - pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl); + pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl); dimensionRegionNr++; } _3ewl = _3prg->GetNextSubList(); @@ -2313,6 +2574,13 @@ } } + void Region::SetKeyRange(uint16_t Low, uint16_t High) { + // update KeyRange struct and make sure regions are in correct order + DLS::Region::SetKeyRange(Low, High); + // update Region key table for fast lookup + ((gig::Instrument*)GetParent())->UpdateRegionKeyTable(); + } + void Region::UpdateVelocityTable() { // get velocity dimension's index int veldim = -1; @@ -2418,22 +2686,65 @@ if (pDimensionDefinitions[i].dimension == pDimDef->dimension) throw gig::Exception("Could not add new dimension, there is already a dimension of the same type"); + // pos is where the new dimension should be placed, normally + // last in list, except for the samplechannel dimension which + // has to be first in list + int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions; + int bitpos = 0; + for (int i = 0 ; i < pos ; i++) + bitpos += pDimensionDefinitions[i].bits; + + // make room for the new dimension + for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1]; + for (int i = 0 ; i < (1 << iCurrentBits) ; i++) { + for (int j = Dimensions ; j > pos ; j--) { + pDimensionRegions[i]->DimensionUpperLimits[j] = + pDimensionRegions[i]->DimensionUpperLimits[j - 1]; + } + } + // assign definition of new dimension - pDimensionDefinitions[Dimensions] = *pDimDef; + pDimensionDefinitions[pos] = *pDimDef; // auto correct certain dimension definition fields (where possible) - pDimensionDefinitions[Dimensions].split_type = - __resolveSplitType(pDimensionDefinitions[Dimensions].dimension); - pDimensionDefinitions[Dimensions].zone_size = - __resolveZoneSize(pDimensionDefinitions[Dimensions]); - - // create new dimension region(s) for this new dimension - for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) { - //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values - RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG); - RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL); - pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk); - DimensionRegions++; + pDimensionDefinitions[pos].split_type = + __resolveSplitType(pDimensionDefinitions[pos].dimension); + pDimensionDefinitions[pos].zone_size = + __resolveZoneSize(pDimensionDefinitions[pos]); + + // create new dimension region(s) for this new dimension, and make + // sure that the dimension regions are placed correctly in both the + // RIFF list and the pDimensionRegions array + RIFF::Chunk* moveTo = NULL; + RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG); + for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) { + for (int k = 0 ; k < (1 << bitpos) ; k++) { + pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k]; + } + for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) { + for (int k = 0 ; k < (1 << bitpos) ; k++) { + RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL); + if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo); + // create a new dimension region and copy all parameter values from + // an existing dimension region + pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] = + new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]); + + DimensionRegions++; + } + } + moveTo = pDimensionRegions[i]->pParentList; + } + + // initialize the upper limits for this dimension + int mask = (1 << bitpos) - 1; + for (int z = 0 ; z < pDimDef->zones ; z++) { + uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1); + for (int i = 0 ; i < 1 << iCurrentBits ; i++) { + pDimensionRegions[((i & ~mask) << pDimDef->bits) | + (z << bitpos) | + (i & mask)]->DimensionUpperLimits[pos] = upperLimit; + } } Dimensions++; @@ -2476,6 +2787,8 @@ for (int i = iDimensionNr + 1; i < Dimensions; i++) iUpperBits += pDimensionDefinitions[i].bits; + RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG); + // delete dimension regions which belong to the given dimension // (that is where the dimension's bit > 0) for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) { @@ -2484,6 +2797,8 @@ int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) | iObsoleteBit << iLowerBits | iLowerBit; + + _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList); delete pDimensionRegions[iToDelete]; pDimensionRegions[iToDelete] = NULL; DimensionRegions--; @@ -2504,6 +2819,15 @@ } } + // remove the this dimension from the upper limits arrays + for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) { + DimensionRegion* d = pDimensionRegions[j]; + for (int i = iDimensionNr + 1; i < Dimensions; i++) { + d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i]; + } + d->DimensionUpperLimits[Dimensions - 1] = 127; + } + // 'remove' dimension definition for (int i = iDimensionNr + 1; i < Dimensions; i++) { pDimensionDefinitions[i - 1] = pDimensionDefinitions[i]; @@ -2637,19 +2961,74 @@ } return NULL; } + + /** + * Make a (semi) deep copy of the Region object given by @a orig + * and assign it to this object. + * + * Note that all sample pointers referenced by @a orig are simply copied as + * memory address. Thus the respective samples are shared, not duplicated! + * + * @param orig - original Region object to be copied from + */ + void Region::CopyAssign(const Region* orig) { + // handle base classes + DLS::Region::CopyAssign(orig); + + // handle own member variables + for (int i = Dimensions - 1; i >= 0; --i) { + DeleteDimension(&pDimensionDefinitions[i]); + } + Layers = 0; // just to be sure + for (int i = 0; i < orig->Dimensions; i++) { + // we need to copy the dim definition here, to avoid the compiler + // complaining about const-ness issue + dimension_def_t def = orig->pDimensionDefinitions[i]; + AddDimension(&def); + } + for (int i = 0; i < 256; i++) { + if (pDimensionRegions[i] && orig->pDimensionRegions[i]) { + pDimensionRegions[i]->CopyAssign( + orig->pDimensionRegions[i] + ); + } + } + Layers = orig->Layers; + } + + +// *************** MidiRule *************** +// * +MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) { + _3ewg->SetPos(36); + Triggers = _3ewg->ReadUint8(); + _3ewg->SetPos(40); + ControllerNumber = _3ewg->ReadUint8(); + _3ewg->SetPos(46); + for (int i = 0 ; i < Triggers ; i++) { + pTriggers[i].TriggerPoint = _3ewg->ReadUint8(); + pTriggers[i].Descending = _3ewg->ReadUint8(); + pTriggers[i].VelSensitivity = _3ewg->ReadUint8(); + pTriggers[i].Key = _3ewg->ReadUint8(); + pTriggers[i].NoteOff = _3ewg->ReadUint8(); + pTriggers[i].Velocity = _3ewg->ReadUint8(); + pTriggers[i].OverridePedal = _3ewg->ReadUint8(); + _3ewg->ReadUint8(); + } +} // *************** Instrument *************** // * Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) { - static const DLS::Info::FixedStringLength fixedStringLengths[] = { + static const DLS::Info::string_length_t fixedStringLengths[] = { { CHUNK_ID_INAM, 64 }, { CHUNK_ID_ISFT, 12 }, { 0, 0 } }; - pInfo->FixedStringLengths = fixedStringLengths; + pInfo->SetFixedStringLengths(fixedStringLengths); // Initialization for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL; @@ -2660,6 +3039,8 @@ PianoReleaseMode = false; DimensionKeyRange.low = 0; DimensionKeyRange.high = 0; + pMidiRules = new MidiRule*[3]; + pMidiRules[0] = NULL; // Loading RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART); @@ -2674,28 +3055,46 @@ PianoReleaseMode = dimkeystart & 0x01; DimensionKeyRange.low = dimkeystart >> 1; DimensionKeyRange.high = _3ewg->ReadUint8(); + + if (_3ewg->GetSize() > 32) { + // read MIDI rules + int i = 0; + _3ewg->SetPos(32); + uint8_t id1 = _3ewg->ReadUint8(); + uint8_t id2 = _3ewg->ReadUint8(); + + if (id1 == 4 && id2 == 16) { + pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg); + } + //TODO: all the other types of rules + + pMidiRules[i] = NULL; + } } } - if (!pRegions) pRegions = new RegionList; - RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN); - if (lrgn) { - RIFF::List* rgn = lrgn->GetFirstSubList(); - while (rgn) { - if (rgn->GetListType() == LIST_TYPE_RGN) { - __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); - pRegions->push_back(new Region(this, rgn)); + if (pFile->GetAutoLoad()) { + if (!pRegions) pRegions = new RegionList; + RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN); + if (lrgn) { + RIFF::List* rgn = lrgn->GetFirstSubList(); + while (rgn) { + if (rgn->GetListType() == LIST_TYPE_RGN) { + __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); + pRegions->push_back(new Region(this, rgn)); + } + rgn = lrgn->GetNextSubList(); } - rgn = lrgn->GetNextSubList(); + // Creating Region Key Table for fast lookup + UpdateRegionKeyTable(); } - // Creating Region Key Table for fast lookup - UpdateRegionKeyTable(); } __notify_progress(pProgress, 1.0f); // notify done } void Instrument::UpdateRegionKeyTable() { + for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL; RegionList::iterator iter = pRegions->begin(); RegionList::iterator end = pRegions->end(); for (; iter != end; ++iter) { @@ -2707,6 +3106,10 @@ } Instrument::~Instrument() { + for (int i = 0 ; pMidiRules[i] ; i++) { + delete pMidiRules[i]; + } + delete[] pMidiRules; } /** @@ -2735,14 +3138,21 @@ if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART); // make sure '3ewg' RIFF chunk exists RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG); - if (!_3ewg) _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12); + if (!_3ewg) { + File* pFile = (File*) GetParent(); + + // 3ewg is bigger in gig3, as it includes the iMIDI rules + int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12; + _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size); + memset(_3ewg->LoadChunkData(), 0, size); + } // update '3ewg' RIFF chunk uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData(); store16(&pData[0], EffectSend); store32(&pData[2], Attenuation); store16(&pData[6], FineTune); store16(&pData[8], PitchbendRange); - const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 | + const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) | DimensionKeyRange.low << 1; pData[10] = dimkeystart; pData[11] = DimensionKeyRange.high; @@ -2756,7 +3166,7 @@ * there is no Region defined for the given \a Key */ Region* Instrument::GetRegion(unsigned int Key) { - if (!pRegions || !pRegions->size() || Key > 127) return NULL; + if (!pRegions || pRegions->empty() || Key > 127) return NULL; return RegionKeyTable[Key]; /*for (int i = 0; i < Regions; i++) { @@ -2814,6 +3224,65 @@ UpdateRegionKeyTable(); } + /** + * Returns a MIDI rule of the instrument. + * + * The list of MIDI rules, at least in gig v3, always contains at + * most two rules. The second rule can only be the DEF filter + * (which currently isn't supported by libgig). + * + * @param i - MIDI rule number + * @returns pointer address to MIDI rule number i or NULL if there is none + */ + MidiRule* Instrument::GetMidiRule(int i) { + return pMidiRules[i]; + } + + /** + * Make a (semi) deep copy of the Instrument object given by @a orig + * and assign it to this object. + * + * Note that all sample pointers referenced by @a orig are simply copied as + * memory address. Thus the respective samples are shared, not duplicated! + * + * @param orig - original Instrument object to be copied from + */ + void Instrument::CopyAssign(const Instrument* orig) { + // handle base class + // (without copying DLS region stuff) + DLS::Instrument::CopyAssignCore(orig); + + // handle own member variables + Attenuation = orig->Attenuation; + EffectSend = orig->EffectSend; + FineTune = orig->FineTune; + PitchbendRange = orig->PitchbendRange; + PianoReleaseMode = orig->PianoReleaseMode; + DimensionKeyRange = orig->DimensionKeyRange; + + // free old midi rules + for (int i = 0 ; pMidiRules[i] ; i++) { + delete pMidiRules[i]; + } + //TODO: MIDI rule copying + pMidiRules[0] = NULL; + + // delete all old regions + while (Regions) DeleteRegion(GetFirstRegion()); + // create new regions and copy them from original + { + RegionList::const_iterator it = orig->pRegions->begin(); + for (int i = 0; i < orig->Regions; ++i, ++it) { + Region* dstRgn = AddRegion(); + //NOTE: Region does semi-deep copy ! + dstRgn->CopyAssign( + static_cast(*it) + ); + } + } + + UpdateRegionKeyTable(); + } // *************** Group *************** @@ -2853,6 +3322,17 @@ } RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL); if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL); + + if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) { + // v3 has a fixed list of 128 strings, find a free one + for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) { + if (strcmp(static_cast(ck->LoadChunkData()), "") == 0) { + pNameChunk = ck; + break; + } + } + } + // 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); } @@ -2928,17 +3408,17 @@ // *************** File *************** // * - // File version 2.0, 1998-06-28 + /// Reflects Gigasampler file format version 2.0 (1998-06-28). const DLS::version_t File::VERSION_2 = { 0, 2, 19980628 & 0xffff, 19980628 >> 16 }; - // File version 3.0, 2003-03-31 + /// Reflects Gigasampler file format version 3.0 (2003-03-31). const DLS::version_t File::VERSION_3 = { 0, 3, 20030331 & 0xffff, 20030331 >> 16 }; - const DLS::Info::FixedStringLength File::FixedStringLengths[] = { + static const DLS::Info::string_length_t _FileFixedStringLengths[] = { { CHUNK_ID_IARL, 256 }, { CHUNK_ID_IART, 128 }, { CHUNK_ID_ICMS, 128 }, @@ -2960,19 +3440,25 @@ }; File::File() : DLS::File() { + bAutoLoad = true; + *pVersion = VERSION_3; pGroups = NULL; - pInfo->FixedStringLengths = FixedStringLengths; + pInfo->SetFixedStringLengths(_FileFixedStringLengths); pInfo->ArchivalLocation = String(256, ' '); // add some mandatory chunks to get the file chunks in right // order (INFO chunk will be moved to first position later) pRIFF->AddSubChunk(CHUNK_ID_VERS, 8); pRIFF->AddSubChunk(CHUNK_ID_COLH, 4); + pRIFF->AddSubChunk(CHUNK_ID_DLID, 16); + + GenerateDLSID(); } File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) { + bAutoLoad = true; pGroups = NULL; - pInfo->FixedStringLengths = FixedStringLengths; + pInfo->SetFixedStringLengths(_FileFixedStringLengths); } File::~File() { @@ -3025,8 +3511,9 @@ /** @brief Delete a sample. * - * This will delete the given Sample object from the gig file. You have - * to call Save() to make this persistent to the file. + * This will delete the given Sample object from the gig file. Any + * references to this sample from Regions and DimensionRegions will be + * removed. You have to call Save() to make this persistent to the file. * * @param pSample - sample to delete * @throws gig::Exception if given sample could not be found @@ -3038,6 +3525,23 @@ if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation pSamples->erase(iter); delete pSample; + + SampleList::iterator tmp = SamplesIterator; + // remove all references to the sample + for (Instrument* instrument = GetFirstInstrument() ; instrument ; + instrument = GetNextInstrument()) { + for (Region* region = instrument->GetFirstRegion() ; region ; + region = instrument->GetNextRegion()) { + + if (region->GetSample() == pSample) region->SetSample(NULL); + + for (int i = 0 ; i < region->DimensionRegions ; i++) { + gig::DimensionRegion *d = region->pDimensionRegions[i]; + if (d->pSample == pSample) d->pSample = NULL; + } + } + } + SamplesIterator = tmp; // restore iterator } void File::LoadSamples() { @@ -3128,7 +3632,8 @@ progress_t subprogress; __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask __notify_progress(&subprogress, 0.0f); - GetFirstSample(&subprogress); // now force all samples to be loaded + if (GetAutoLoad()) + GetFirstSample(&subprogress); // now force all samples to be loaded __notify_progress(&subprogress, 1.0f); // instrument loading subtask @@ -3164,8 +3669,10 @@ // add mandatory chunks to get the chunks in right order lstInstr->AddSubList(LIST_TYPE_INFO); + lstInstr->AddSubChunk(CHUNK_ID_DLID, 16); Instrument* pInstrument = new Instrument(this, lstInstr); + pInstrument->GenerateDLSID(); lstInstr->AddSubChunk(CHUNK_ID_INSH, 12); @@ -3175,6 +3682,27 @@ pInstruments->push_back(pInstrument); return pInstrument; } + + /** @brief Add a duplicate of an existing instrument. + * + * Duplicates the instrument definition given by @a orig and adds it + * to this file. This allows in an instrument editor application to + * easily create variations of an instrument, which will be stored in + * the same .gig file, sharing i.e. the same samples. + * + * Note that all sample pointers referenced by @a orig are simply copied as + * memory address. Thus the respective samples are shared, not duplicated! + * + * You have to call Save() to make this persistent to the file. + * + * @param orig - original instrument to be copied + * @returns duplicated copy of the given instrument + */ + Instrument* File::AddDuplicateInstrument(const Instrument* orig) { + Instrument* instr = AddInstrument(); + instr->CopyAssign(orig); + return instr; + } /** @brief Delete an instrument. * @@ -3222,9 +3750,14 @@ } } + /// Updates the 3crc chunk with the checksum of a sample. The + /// update is done directly to disk, as this method is called + /// after File::Save() void File::SetSampleChecksum(Sample* pSample, uint32_t crc) { RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); if (!_3crc) return; + + // get the index of the sample int iWaveIndex = -1; File::SampleList::iterator iter = pSamples->begin(); File::SampleList::iterator end = pSamples->end(); @@ -3236,6 +3769,7 @@ } if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample"); + // write the CRC-32 checksum to disk _3crc->SetPos(iWaveIndex * 8); uint32_t tmp = 1; _3crc->WriteUint32(&tmp); // unknown, always 1? @@ -3334,6 +3868,9 @@ RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk(); while (ck) { if (ck->GetChunkID() == CHUNK_ID_3GNM) { + if (pVersion && pVersion->major == 3 && + strcmp(static_cast(ck->LoadChunkData()), "") == 0) break; + pGroups->push_back(new Group(this, ck)); } ck = lst3gnl->GetNextSubChunk(); @@ -3361,6 +3898,8 @@ void File::UpdateChunks() { bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL; + b64BitWavePoolOffsets = pVersion && pVersion->major == 3; + // first update base class's chunks DLS::File::UpdateChunks(); @@ -3381,6 +3920,16 @@ for (; iter != end; ++iter) { (*iter)->UpdateChunks(); } + + // v3: make sure the file has 128 3gnm chunks + if (pVersion && pVersion->major == 3) { + RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL); + RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk(); + for (int i = 0 ; i < 128 ; i++) { + if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); + if (_3gnm) _3gnm = _3gnl->GetNextSubChunk(); + } + } } // update einf chunk @@ -3424,6 +3973,7 @@ int totnbusedchannels = 0; int totnbregions = 0; int totnbdimregions = 0; + int totnbloops = 0; int instrumentIdx = 0; memset(&pData[48], 0, sublen - 48); @@ -3433,6 +3983,7 @@ int nbusedsamples = 0; int nbusedchannels = 0; int nbdimregions = 0; + int nbloops = 0; memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48); @@ -3456,6 +4007,7 @@ } } } + if (d->SampleLoops) nbloops++; } nbdimregions += region->DimensionRegions; } @@ -3466,13 +4018,15 @@ store32(&pData[(instrumentIdx + 1) * sublen + 12], 1); store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions); store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions); - // next 12 bytes unknown + store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops); + // next 8 bytes unknown store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx); store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size()); // next 4 bytes unknown totnbregions += instrument->Regions; totnbdimregions += nbdimregions; + totnbloops += nbloops; instrumentIdx++; } // first 4 bytes unknown - sometimes 0, sometimes length of einf part @@ -3482,8 +4036,9 @@ store32(&pData[12], Instruments); store32(&pData[16], totnbregions); store32(&pData[20], totnbdimregions); - // next 12 bytes unknown - // next 4 bytes unknown, always 0? + store32(&pData[24], totnbloops); + // next 8 bytes unknown + // next 4 bytes unknown, not always 0 store32(&pData[40], pSamples->size()); // next 4 bytes unknown } @@ -3500,9 +4055,39 @@ } else if (newFile) { _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8); _3crc->LoadChunkData(); + + // the order of einf and 3crc is not the same in v2 and v3 + if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf); } } + /** + * Enable / disable automatic loading. By default this properyt is + * enabled and all informations are loaded automatically. However + * loading all Regions, DimensionRegions and especially samples might + * take a long time for large .gig files, and sometimes one might only + * be interested in retrieving very superficial informations like the + * amount of instruments and their names. In this case one might disable + * automatic loading to avoid very slow response times. + * + * @e CAUTION: by disabling this property many pointers (i.e. sample + * references) and informations will have invalid or even undefined + * data! This feature is currently only intended for retrieving very + * superficial informations in a very fast way. Don't use it to retrieve + * details like synthesis informations or even to modify .gig files! + */ + void File::SetAutoLoad(bool b) { + bAutoLoad = b; + } + + /** + * Returns whether automatic loading is enabled. + * @see SetAutoLoad() + */ + bool File::GetAutoLoad() { + return bAutoLoad; + } + // *************** Exception ***************