--- libgig/trunk/src/gig.cpp 2007/05/17 17:24:26 1195 +++ libgig/trunk/src/gig.cpp 2014/06/07 00:00:10 2599 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2007 by Christian Schoenebeck * + * Copyright (C) 2003-2014 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -25,8 +25,10 @@ #include "helper.h" +#include #include #include +#include /// Initial size of the sample buffer which is used for decompression of /// compressed sample wave streams - this value should always be bigger than @@ -255,6 +257,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 *************** // * @@ -303,14 +368,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(); @@ -342,7 +409,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; @@ -388,6 +455,73 @@ } /** + * Make a (semi) deep copy of the Sample object given by @a orig (without + * the actual waveform data) and assign it to this object. + * + * Discussion: copying .gig samples is a bit tricky. It requires three + * steps: + * 1. Copy sample's meta informations (done by CopyAssignMeta()) including + * its new sample waveform data size. + * 2. Saving the file (done by File::Save()) so that it gains correct size + * and layout for writing the actual wave form data directly to disc + * in next step. + * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()). + * + * @param orig - original Sample object to be copied from + */ + void Sample::CopyAssignMeta(const Sample* orig) { + // handle base classes + DLS::Sample::CopyAssignCore(orig); + + // handle actual own attributes of this class + Manufacturer = orig->Manufacturer; + Product = orig->Product; + SamplePeriod = orig->SamplePeriod; + MIDIUnityNote = orig->MIDIUnityNote; + FineTune = orig->FineTune; + SMPTEFormat = orig->SMPTEFormat; + SMPTEOffset = orig->SMPTEOffset; + Loops = orig->Loops; + LoopID = orig->LoopID; + LoopType = orig->LoopType; + LoopStart = orig->LoopStart; + LoopEnd = orig->LoopEnd; + LoopSize = orig->LoopSize; + LoopFraction = orig->LoopFraction; + LoopPlayCount = orig->LoopPlayCount; + + // schedule resizing this sample to the given sample's size + Resize(orig->GetSize()); + } + + /** + * Should be called after CopyAssignMeta() and File::Save() sequence. + * Read more about it in the discussion of CopyAssignMeta(). This method + * copies the actual waveform data by disk streaming. + * + * @e CAUTION: this method is currently not thread safe! During this + * operation the sample must not be used for other purposes by other + * threads! + * + * @param orig - original Sample object to be copied from + */ + void Sample::CopyAssignWave(const Sample* orig) { + const int iReadAtOnce = 32*1024; + char* buf = new char[iReadAtOnce * orig->FrameSize]; + Sample* pOrig = (Sample*) orig; //HACK: remove constness for now + unsigned long restorePos = pOrig->GetPos(); + pOrig->SetPos(0); + SetPos(0); + for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n; + n = pOrig->Read(buf, iReadAtOnce)) + { + Write(buf, n); + } + pOrig->SetPos(restorePos); + delete [] buf; + } + + /** * Apply sample and its settings to the respective RIFF chunks. You have * to call File::Save() to make changes persistent. * @@ -448,6 +582,14 @@ // update '3gix' chunk pData = (uint8_t*) pCk3gix->LoadChunkData(); store16(&pData[0], iSampleGroup); + + // if the library user toggled the "Compressed" attribute from true to + // false, then the EWAV chunk associated with compressed samples needs + // to be deleted + RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV); + if (ewav && !Compressed) { + pWaveList->DeleteSubChunk(ewav); + } } /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points). @@ -611,6 +753,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; @@ -648,6 +791,7 @@ if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart; RAMCache.pStart = NULL; RAMCache.Size = 0; + RAMCache.NullExtensionSize = 0; } /** @brief Resize sample. @@ -740,7 +884,7 @@ /** * Returns the current position in the sample (in sample points). */ - unsigned long Sample::GetPos() { + unsigned long Sample::GetPos() const { if (Compressed) return SamplePos; else return pCkData->GetPos() / FrameSize; } @@ -842,7 +986,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; @@ -1132,6 +1277,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 @@ -1140,7 +1289,29 @@ */ unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) { if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)"); - return DLS::Sample::Write(pBuffer, SampleCount); + + // if this is the first write in this sample, reset the + // checksum calculator + if (pCkData->GetPos() == 0) { + __resetCRC(crc); + } + 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, __encodeCRC(crc)); + } + return res; } /** @@ -1216,12 +1387,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); @@ -1335,7 +1509,7 @@ : vcf_res_ctrl_none; uint16_t eg3depth = _3ewa->ReadUint16(); EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */ - : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */ + : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */ _3ewa->ReadInt16(); // unknown ChannelOffset = _3ewa->ReadUint8() / 4; uint8_t regoptions = _3ewa->ReadUint8(); @@ -1385,9 +1559,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; @@ -1402,18 +1576,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; @@ -1456,42 +1630,120 @@ 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 + + // 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) { + CopyAssign(orig, NULL); + } - // 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; + /** + * Make a (semi) deep copy of the DimensionRegion object given by @a orig + * and assign it to this object. + * + * @param orig - original DimensionRegion object to be copied from + * @param mSamples - crosslink map between the foreign file's samples and + * this file's samples + */ + void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map* mSamples) { + // delete all allocated data first + if (VelocityTable) delete [] VelocityTable; + if (pSampleLoops) delete [] pSampleLoops; + + // backup parent list pointer + RIFF::List* p = pParentList; + + gig::Sample* pOriginalSample = pSample; + gig::Region* pOriginalRegion = pRegion; + + //NOTE: copy code copied from assignment constructor above, see comment there as well + + *this = *orig; // default memberwise shallow copy of all parameters + + // restore members that shall not be altered + pParentList = p; // restore the chunk pointer + pRegion = pOriginalRegion; + + // only take the raw sample reference reference if the + // two DimensionRegion objects are part of the same file + if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) { + pSample = pOriginalSample; + } + + if (mSamples && mSamples->count(orig->pSample)) { + pSample = mSamples->find(orig->pSample)->second; + } + + // 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; } /** @@ -1505,10 +1757,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 @@ -1554,7 +1817,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); @@ -1564,7 +1827,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); @@ -1714,8 +1977,8 @@ } const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth - : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */ - pData[116] = eg3depth; + : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */ + store16(&pData[116], eg3depth); // next 2 bytes unknown @@ -1742,27 +2005,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; @@ -1774,6 +2037,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) { @@ -1789,6 +2086,16 @@ return table; } + Region* DimensionRegion::GetParent() const { + return pRegion; + } + +// show error if some _lev_ctrl_* enum entry is not listed in the following function +// (commented out for now, because "diagnostic push" not supported prior GCC 4.6) +// TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below) +//#pragma GCC diagnostic push +//#pragma GCC diagnostic error "-Wswitch" + leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) { leverage_ctrl_t decodedcontroller; switch (EncodedController) { @@ -1900,12 +2207,255 @@ decodedcontroller.controller_number = 95; break; + // format extension (these controllers are so far only supported by + // LinuxSampler & gigedit) they will *NOT* work with + // Gigasampler/GigaStudio ! + case _lev_ctrl_CC3_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 3; + break; + case _lev_ctrl_CC6_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 6; + break; + case _lev_ctrl_CC7_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 7; + break; + case _lev_ctrl_CC8_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 8; + break; + case _lev_ctrl_CC9_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 9; + break; + case _lev_ctrl_CC10_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 10; + break; + case _lev_ctrl_CC11_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 11; + break; + case _lev_ctrl_CC14_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 14; + break; + case _lev_ctrl_CC15_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 15; + break; + case _lev_ctrl_CC20_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 20; + break; + case _lev_ctrl_CC21_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 21; + break; + case _lev_ctrl_CC22_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 22; + break; + case _lev_ctrl_CC23_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 23; + break; + case _lev_ctrl_CC24_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 24; + break; + case _lev_ctrl_CC25_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 25; + break; + case _lev_ctrl_CC26_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 26; + break; + case _lev_ctrl_CC27_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 27; + break; + case _lev_ctrl_CC28_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 28; + break; + case _lev_ctrl_CC29_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 29; + break; + case _lev_ctrl_CC30_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 30; + break; + case _lev_ctrl_CC31_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 31; + break; + case _lev_ctrl_CC68_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 68; + break; + case _lev_ctrl_CC69_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 69; + break; + case _lev_ctrl_CC70_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 70; + break; + case _lev_ctrl_CC71_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 71; + break; + case _lev_ctrl_CC72_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 72; + break; + case _lev_ctrl_CC73_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 73; + break; + case _lev_ctrl_CC74_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 74; + break; + case _lev_ctrl_CC75_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 75; + break; + case _lev_ctrl_CC76_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 76; + break; + case _lev_ctrl_CC77_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 77; + break; + case _lev_ctrl_CC78_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 78; + break; + case _lev_ctrl_CC79_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 79; + break; + case _lev_ctrl_CC84_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 84; + break; + case _lev_ctrl_CC85_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 85; + break; + case _lev_ctrl_CC86_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 86; + break; + case _lev_ctrl_CC87_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 87; + break; + case _lev_ctrl_CC89_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 89; + break; + case _lev_ctrl_CC90_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 90; + break; + case _lev_ctrl_CC96_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 96; + break; + case _lev_ctrl_CC97_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 97; + break; + case _lev_ctrl_CC102_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 102; + break; + case _lev_ctrl_CC103_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 103; + break; + case _lev_ctrl_CC104_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 104; + break; + case _lev_ctrl_CC105_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 105; + break; + case _lev_ctrl_CC106_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 106; + break; + case _lev_ctrl_CC107_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 107; + break; + case _lev_ctrl_CC108_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 108; + break; + case _lev_ctrl_CC109_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 109; + break; + case _lev_ctrl_CC110_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 110; + break; + case _lev_ctrl_CC111_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 111; + break; + case _lev_ctrl_CC112_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 112; + break; + case _lev_ctrl_CC113_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 113; + break; + case _lev_ctrl_CC114_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 114; + break; + case _lev_ctrl_CC115_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 115; + break; + case _lev_ctrl_CC116_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 116; + break; + case _lev_ctrl_CC117_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 117; + break; + case _lev_ctrl_CC118_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 118; + break; + case _lev_ctrl_CC119_EXT: + decodedcontroller.type = leverage_ctrl_t::type_controlchange; + decodedcontroller.controller_number = 119; + break; + // unknown controller type default: throw gig::Exception("Unknown leverage controller type."); } return decodedcontroller; } + +// see above (diagnostic push not supported prior GCC 4.6) +//#pragma GCC diagnostic pop DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) { _lev_ctrl_t encodedcontroller; @@ -1993,6 +2543,188 @@ case 95: encodedcontroller = _lev_ctrl_effect5depth; break; + + // format extension (these controllers are so far only + // supported by LinuxSampler & gigedit) they will *NOT* + // work with Gigasampler/GigaStudio ! + case 3: + encodedcontroller = _lev_ctrl_CC3_EXT; + break; + case 6: + encodedcontroller = _lev_ctrl_CC6_EXT; + break; + case 7: + encodedcontroller = _lev_ctrl_CC7_EXT; + break; + case 8: + encodedcontroller = _lev_ctrl_CC8_EXT; + break; + case 9: + encodedcontroller = _lev_ctrl_CC9_EXT; + break; + case 10: + encodedcontroller = _lev_ctrl_CC10_EXT; + break; + case 11: + encodedcontroller = _lev_ctrl_CC11_EXT; + break; + case 14: + encodedcontroller = _lev_ctrl_CC14_EXT; + break; + case 15: + encodedcontroller = _lev_ctrl_CC15_EXT; + break; + case 20: + encodedcontroller = _lev_ctrl_CC20_EXT; + break; + case 21: + encodedcontroller = _lev_ctrl_CC21_EXT; + break; + case 22: + encodedcontroller = _lev_ctrl_CC22_EXT; + break; + case 23: + encodedcontroller = _lev_ctrl_CC23_EXT; + break; + case 24: + encodedcontroller = _lev_ctrl_CC24_EXT; + break; + case 25: + encodedcontroller = _lev_ctrl_CC25_EXT; + break; + case 26: + encodedcontroller = _lev_ctrl_CC26_EXT; + break; + case 27: + encodedcontroller = _lev_ctrl_CC27_EXT; + break; + case 28: + encodedcontroller = _lev_ctrl_CC28_EXT; + break; + case 29: + encodedcontroller = _lev_ctrl_CC29_EXT; + break; + case 30: + encodedcontroller = _lev_ctrl_CC30_EXT; + break; + case 31: + encodedcontroller = _lev_ctrl_CC31_EXT; + break; + case 68: + encodedcontroller = _lev_ctrl_CC68_EXT; + break; + case 69: + encodedcontroller = _lev_ctrl_CC69_EXT; + break; + case 70: + encodedcontroller = _lev_ctrl_CC70_EXT; + break; + case 71: + encodedcontroller = _lev_ctrl_CC71_EXT; + break; + case 72: + encodedcontroller = _lev_ctrl_CC72_EXT; + break; + case 73: + encodedcontroller = _lev_ctrl_CC73_EXT; + break; + case 74: + encodedcontroller = _lev_ctrl_CC74_EXT; + break; + case 75: + encodedcontroller = _lev_ctrl_CC75_EXT; + break; + case 76: + encodedcontroller = _lev_ctrl_CC76_EXT; + break; + case 77: + encodedcontroller = _lev_ctrl_CC77_EXT; + break; + case 78: + encodedcontroller = _lev_ctrl_CC78_EXT; + break; + case 79: + encodedcontroller = _lev_ctrl_CC79_EXT; + break; + case 84: + encodedcontroller = _lev_ctrl_CC84_EXT; + break; + case 85: + encodedcontroller = _lev_ctrl_CC85_EXT; + break; + case 86: + encodedcontroller = _lev_ctrl_CC86_EXT; + break; + case 87: + encodedcontroller = _lev_ctrl_CC87_EXT; + break; + case 89: + encodedcontroller = _lev_ctrl_CC89_EXT; + break; + case 90: + encodedcontroller = _lev_ctrl_CC90_EXT; + break; + case 96: + encodedcontroller = _lev_ctrl_CC96_EXT; + break; + case 97: + encodedcontroller = _lev_ctrl_CC97_EXT; + break; + case 102: + encodedcontroller = _lev_ctrl_CC102_EXT; + break; + case 103: + encodedcontroller = _lev_ctrl_CC103_EXT; + break; + case 104: + encodedcontroller = _lev_ctrl_CC104_EXT; + break; + case 105: + encodedcontroller = _lev_ctrl_CC105_EXT; + break; + case 106: + encodedcontroller = _lev_ctrl_CC106_EXT; + break; + case 107: + encodedcontroller = _lev_ctrl_CC107_EXT; + break; + case 108: + encodedcontroller = _lev_ctrl_CC108_EXT; + break; + case 109: + encodedcontroller = _lev_ctrl_CC109_EXT; + break; + case 110: + encodedcontroller = _lev_ctrl_CC110_EXT; + break; + case 111: + encodedcontroller = _lev_ctrl_CC111_EXT; + break; + case 112: + encodedcontroller = _lev_ctrl_CC112_EXT; + break; + case 113: + encodedcontroller = _lev_ctrl_CC113_EXT; + break; + case 114: + encodedcontroller = _lev_ctrl_CC114_EXT; + break; + case 115: + encodedcontroller = _lev_ctrl_CC115_EXT; + break; + case 116: + encodedcontroller = _lev_ctrl_CC116_EXT; + break; + case 117: + encodedcontroller = _lev_ctrl_CC117_EXT; + break; + case 118: + encodedcontroller = _lev_ctrl_CC118_EXT; + break; + case 119: + encodedcontroller = _lev_ctrl_CC119_EXT; + break; + default: throw gig::Exception("leverage controller number is not supported by the gig format"); } @@ -2042,6 +2774,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 @@ -2125,6 +2947,8 @@ // Actual Loading + if (!file->GetAutoLoad()) return; + LoadDimensionRegions(rgnList); RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK); @@ -2133,8 +2957,8 @@ for (int i = 0; i < dimensionBits; i++) { dimension_t dimension = static_cast(_3lnk->ReadUint8()); uint8_t bits = _3lnk->ReadUint8(); - _3lnk->ReadUint8(); // probably the position of the dimension - _3lnk->ReadUint8(); // unknown + _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1]) + _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension) uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits) if (dimension == dimension_none) { // inactive dimension pDimensionDefinitions[i].dimension = dimension_none; @@ -2168,12 +2992,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++) { @@ -2188,7 +3014,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; } } @@ -2218,33 +3044,38 @@ } 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); // move 3prg to last position - pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0); + pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL); } // update dimension definitions in '3lnk' chunk uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData(); store32(&pData[0], DimensionRegions); + int shift = 0; for (int i = 0; i < iMaxDimensions; i++) { pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension; pData[5 + i * 8] = pDimensionDefinitions[i].bits; - // next 2 bytes unknown + 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 + // next 3 bytes unknown, always zero? + + shift += pDimensionDefinitions[i].bits; } // 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) { @@ -2257,7 +3088,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); } @@ -2270,7 +3100,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(); @@ -2279,6 +3109,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; @@ -2365,6 +3202,18 @@ * dimension bits limit is violated */ void Region::AddDimension(dimension_def_t* pDimDef) { + // some initial sanity checks of the given dimension definition + if (pDimDef->zones < 2) + throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two"); + if (pDimDef->bits < 1) + throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one"); + if (pDimDef->dimension == dimension_samplechannel) { + if (pDimDef->zones != 2) + throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type"); + if (pDimDef->bits != 1) + throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type"); + } + // check if max. amount of dimensions reached File* file = (File*) GetParent()->GetParent(); const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5; @@ -2384,22 +3233,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++; @@ -2442,6 +3334,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++) { @@ -2450,6 +3344,8 @@ int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) | iObsoleteBit << iLowerBits | iLowerBit; + + _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList); delete pDimensionRegions[iToDelete]; pDimensionRegions[iToDelete] = NULL; DimensionRegions--; @@ -2470,6 +3366,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]; @@ -2484,6 +3389,303 @@ if (pDimDef->dimension == dimension_layer) Layers = 1; } + /** @brief Delete one split zone of a dimension (decrement zone amount). + * + * Instead of deleting an entire dimensions, this method will only delete + * one particular split zone given by @a zone of the Region's dimension + * given by @a type. So this method will simply decrement the amount of + * zones by one of the dimension in question. To be able to do that, the + * respective dimension must exist on this Region and it must have at least + * 3 zones. All DimensionRegion objects associated with the zone will be + * deleted. + * + * @param type - identifies the dimension where a zone shall be deleted + * @param zone - index of the dimension split zone that shall be deleted + * @throws gig::Exception if requested zone could not be deleted + */ + void Region::DeleteDimensionZone(dimension_t type, int zone) { + dimension_def_t* oldDef = GetDimensionDefinition(type); + if (!oldDef) + throw gig::Exception("Could not delete dimension zone, no such dimension of given type"); + if (oldDef->zones <= 2) + throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone."); + if (zone < 0 || zone >= oldDef->zones) + throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds."); + + const int newZoneSize = oldDef->zones - 1; + + // create a temporary Region which just acts as a temporary copy + // container and will be deleted at the end of this function and will + // also not be visible through the API during this process + gig::Region* tempRgn = NULL; + { + // adding these temporary chunks is probably not even necessary + Instrument* instr = static_cast(GetParent()); + RIFF::List* pCkInstrument = instr->pCkInstrument; + RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN); + if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN); + RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN); + tempRgn = new Region(instr, rgn); + } + + // copy this region's dimensions (with already the dimension split size + // requested by the arguments of this method call) to the temporary + // region, and don't use Region::CopyAssign() here for this task, since + // it would also alter fast lookup helper variables here and there + dimension_def_t newDef; + for (int i = 0; i < Dimensions; ++i) { + dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference + // is this the dimension requested by the method arguments? ... + if (def.dimension == type) { // ... if yes, decrement zone amount by one + def.zones = newZoneSize; + if ((1 << (def.bits - 1)) == def.zones) def.bits--; + newDef = def; + } + tempRgn->AddDimension(&def); + } + + // find the dimension index in the tempRegion which is the dimension + // type passed to this method (paranoidly expecting different order) + int tempReducedDimensionIndex = -1; + for (int d = 0; d < tempRgn->Dimensions; ++d) { + if (tempRgn->pDimensionDefinitions[d].dimension == type) { + tempReducedDimensionIndex = d; + break; + } + } + + // copy dimension regions from this region to the temporary region + for (int iDst = 0; iDst < 256; ++iDst) { + DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst]; + if (!dstDimRgn) continue; + std::map dimCase; + bool isValidZone = true; + for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) { + const int dstBits = tempRgn->pDimensionDefinitions[d].bits; + dimCase[tempRgn->pDimensionDefinitions[d].dimension] = + (iDst >> baseBits) & ((1 << dstBits) - 1); + baseBits += dstBits; + // there are also DimensionRegion objects of unused zones, skip them + if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) { + isValidZone = false; + break; + } + } + if (!isValidZone) continue; + // a bit paranoid: cope with the chance that the dimensions would + // have different order in source and destination regions + const bool isLastZone = (dimCase[type] == newZoneSize - 1); + if (dimCase[type] >= zone) dimCase[type]++; + DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase); + dstDimRgn->CopyAssign(srcDimRgn); + // if this is the upper most zone of the dimension passed to this + // method, then correct (raise) its upper limit to 127 + if (newDef.split_type == split_type_normal && isLastZone) + dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127; + } + + // now tempRegion's dimensions and DimensionRegions basically reflect + // what we wanted to get for this actual Region here, so we now just + // delete and recreate the dimension in question with the new amount + // zones and then copy back from tempRegion + DeleteDimension(oldDef); + AddDimension(&newDef); + for (int iSrc = 0; iSrc < 256; ++iSrc) { + DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc]; + if (!srcDimRgn) continue; + std::map dimCase; + for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) { + const int srcBits = tempRgn->pDimensionDefinitions[d].bits; + dimCase[tempRgn->pDimensionDefinitions[d].dimension] = + (iSrc >> baseBits) & ((1 << srcBits) - 1); + baseBits += srcBits; + } + // a bit paranoid: cope with the chance that the dimensions would + // have different order in source and destination regions + DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase); + if (!dstDimRgn) continue; + dstDimRgn->CopyAssign(srcDimRgn); + } + + // delete temporary region + delete tempRgn; + + UpdateVelocityTable(); + } + + /** @brief Divide split zone of a dimension in two (increment zone amount). + * + * This will increment the amount of zones for the dimension (given by + * @a type) by one. It will do so by dividing the zone (given by @a zone) + * in the middle of its zone range in two. So the two zones resulting from + * the zone being splitted, will be an equivalent copy regarding all their + * articulation informations and sample reference. The two zones will only + * differ in their zone's upper limit + * (DimensionRegion::DimensionUpperLimits). + * + * @param type - identifies the dimension where a zone shall be splitted + * @param zone - index of the dimension split zone that shall be splitted + * @throws gig::Exception if requested zone could not be splitted + */ + void Region::SplitDimensionZone(dimension_t type, int zone) { + dimension_def_t* oldDef = GetDimensionDefinition(type); + if (!oldDef) + throw gig::Exception("Could not split dimension zone, no such dimension of given type"); + if (zone < 0 || zone >= oldDef->zones) + throw gig::Exception("Could not split dimension zone, requested zone index out of bounds."); + + const int newZoneSize = oldDef->zones + 1; + + // create a temporary Region which just acts as a temporary copy + // container and will be deleted at the end of this function and will + // also not be visible through the API during this process + gig::Region* tempRgn = NULL; + { + // adding these temporary chunks is probably not even necessary + Instrument* instr = static_cast(GetParent()); + RIFF::List* pCkInstrument = instr->pCkInstrument; + RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN); + if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN); + RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN); + tempRgn = new Region(instr, rgn); + } + + // copy this region's dimensions (with already the dimension split size + // requested by the arguments of this method call) to the temporary + // region, and don't use Region::CopyAssign() here for this task, since + // it would also alter fast lookup helper variables here and there + dimension_def_t newDef; + for (int i = 0; i < Dimensions; ++i) { + dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference + // is this the dimension requested by the method arguments? ... + if (def.dimension == type) { // ... if yes, increment zone amount by one + def.zones = newZoneSize; + if ((1 << oldDef->bits) < newZoneSize) def.bits++; + newDef = def; + } + tempRgn->AddDimension(&def); + } + + // find the dimension index in the tempRegion which is the dimension + // type passed to this method (paranoidly expecting different order) + int tempIncreasedDimensionIndex = -1; + for (int d = 0; d < tempRgn->Dimensions; ++d) { + if (tempRgn->pDimensionDefinitions[d].dimension == type) { + tempIncreasedDimensionIndex = d; + break; + } + } + + // copy dimension regions from this region to the temporary region + for (int iSrc = 0; iSrc < 256; ++iSrc) { + DimensionRegion* srcDimRgn = pDimensionRegions[iSrc]; + if (!srcDimRgn) continue; + std::map dimCase; + bool isValidZone = true; + for (int d = 0, baseBits = 0; d < Dimensions; ++d) { + const int srcBits = pDimensionDefinitions[d].bits; + dimCase[pDimensionDefinitions[d].dimension] = + (iSrc >> baseBits) & ((1 << srcBits) - 1); + // there are also DimensionRegion objects for unused zones, skip them + if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) { + isValidZone = false; + break; + } + baseBits += srcBits; + } + if (!isValidZone) continue; + // a bit paranoid: cope with the chance that the dimensions would + // have different order in source and destination regions + if (dimCase[type] > zone) dimCase[type]++; + DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase); + dstDimRgn->CopyAssign(srcDimRgn); + // if this is the requested zone to be splitted, then also copy + // the source DimensionRegion to the newly created target zone + // and set the old zones upper limit lower + if (dimCase[type] == zone) { + // lower old zones upper limit + if (newDef.split_type == split_type_normal) { + const int high = + dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex]; + int low = 0; + if (zone > 0) { + std::map lowerCase = dimCase; + lowerCase[type]--; + DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase); + low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex]; + } + dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2; + } + // fill the newly created zone of the divided zone as well + dimCase[type]++; + dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase); + dstDimRgn->CopyAssign(srcDimRgn); + } + } + + // now tempRegion's dimensions and DimensionRegions basically reflect + // what we wanted to get for this actual Region here, so we now just + // delete and recreate the dimension in question with the new amount + // zones and then copy back from tempRegion + DeleteDimension(oldDef); + AddDimension(&newDef); + for (int iSrc = 0; iSrc < 256; ++iSrc) { + DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc]; + if (!srcDimRgn) continue; + std::map dimCase; + for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) { + const int srcBits = tempRgn->pDimensionDefinitions[d].bits; + dimCase[tempRgn->pDimensionDefinitions[d].dimension] = + (iSrc >> baseBits) & ((1 << srcBits) - 1); + baseBits += srcBits; + } + // a bit paranoid: cope with the chance that the dimensions would + // have different order in source and destination regions + DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase); + if (!dstDimRgn) continue; + dstDimRgn->CopyAssign(srcDimRgn); + } + + // delete temporary region + delete tempRgn; + + UpdateVelocityTable(); + } + + DimensionRegion* Region::GetDimensionRegionByBit(const std::map& DimCase) { + uint8_t bits[8] = {}; + for (std::map::const_iterator it = DimCase.begin(); + it != DimCase.end(); ++it) + { + for (int d = 0; d < Dimensions; ++d) { + if (pDimensionDefinitions[d].dimension == it->first) { + bits[d] = it->second; + goto nextDimCaseSlice; + } + } + assert(false); // do crash ... too harsh maybe ? ignore it instead ? + nextDimCaseSlice: + ; // noop + } + return GetDimensionRegionByBit(bits); + } + + /** + * Searches in the current Region for a dimension of the given dimension + * type and returns the precise configuration of that dimension in this + * Region. + * + * @param type - dimension type of the sought dimension + * @returns dimension definition or NULL if there is no dimension with + * sought type in this Region. + */ + dimension_def_t* Region::GetDimensionDefinition(dimension_t type) { + for (int i = 0; i < Dimensions; ++i) + if (pDimensionDefinitions[i].dimension == type) + return &pDimensionDefinitions[i]; + return NULL; + } + Region::~Region() { for (int i = 0; i < 256; i++) { if (pDimensionRegions[i]) delete pDimensionRegions[i]; @@ -2541,20 +3743,72 @@ } bitpos += pDimensionDefinitions[i].bits; } - DimensionRegion* dimreg = pDimensionRegions[dimregidx]; + DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255]; + if (!dimreg) return NULL; if (veldim != -1) { // (dimreg is now the dimension region for the lowest velocity) if (dimreg->VelocityTable) // custom defined zone ranges - bits = dimreg->VelocityTable[DimValues[veldim]]; + bits = dimreg->VelocityTable[DimValues[veldim] & 127]; else // normal split type - bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size); + bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size); - dimregidx |= bits << velbitpos; - dimreg = pDimensionRegions[dimregidx]; + const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1; + dimregidx |= (bits & limiter_mask) << velbitpos; + dimreg = pDimensionRegions[dimregidx & 255]; } return dimreg; } + int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) { + uint8_t bits; + int veldim = -1; + int velbitpos; + int bitpos = 0; + int dimregidx = 0; + for (uint i = 0; i < Dimensions; i++) { + 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: + if (pDimensionRegions[0]->DimensionUpperLimits[i]) { + // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges + for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) { + if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break; + } + } else { + // gig2: evenly sized zones + 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; + } + dimregidx &= 255; + DimensionRegion* dimreg = pDimensionRegions[dimregidx]; + if (!dimreg) return -1; + if (veldim != -1) { + // (dimreg is now the dimension region for the lowest velocity) + if (dimreg->VelocityTable) // custom defined zone ranges + bits = dimreg->VelocityTable[DimValues[veldim] & 127]; + else // normal split type + bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size); + + const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1; + dimregidx |= (bits & limiter_mask) << velbitpos; + dimregidx &= 255; + } + return dimregidx; + } + /** * Returns the appropriate DimensionRegion for the given dimension bit * numbers (zone index). You usually use GetDimensionRegionByValue @@ -2603,19 +3857,459 @@ } 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) { + CopyAssign(orig, NULL); + } + + /** + * Make a (semi) deep copy of the Region object given by @a orig and + * assign it to this object + * + * @param mSamples - crosslink map between the foreign file's samples and + * this file's samples + */ + void Region::CopyAssign(const Region* orig, const std::map* mSamples) { + // handle base classes + DLS::Region::CopyAssign(orig); + + if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) { + pSample = mSamples->find((gig::Sample*)orig->pSample)->second; + } + + // 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], + mSamples + ); + } + } + 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(); + } + } + + MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() : + ControllerNumber(0), + Triggers(0) { + } + + void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const { + pData[32] = 4; + pData[33] = 16; + pData[36] = Triggers; + pData[40] = ControllerNumber; + for (int i = 0 ; i < Triggers ; i++) { + pData[46 + i * 8] = pTriggers[i].TriggerPoint; + pData[47 + i * 8] = pTriggers[i].Descending; + pData[48 + i * 8] = pTriggers[i].VelSensitivity; + pData[49 + i * 8] = pTriggers[i].Key; + pData[50 + i * 8] = pTriggers[i].NoteOff; + pData[51 + i * 8] = pTriggers[i].Velocity; + pData[52 + i * 8] = pTriggers[i].OverridePedal; + } + } + + MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) { + _3ewg->SetPos(36); + LegatoSamples = _3ewg->ReadUint8(); // always 12 + _3ewg->SetPos(40); + BypassUseController = _3ewg->ReadUint8(); + BypassKey = _3ewg->ReadUint8(); + BypassController = _3ewg->ReadUint8(); + ThresholdTime = _3ewg->ReadUint16(); + _3ewg->ReadInt16(); + ReleaseTime = _3ewg->ReadUint16(); + _3ewg->ReadInt16(); + KeyRange.low = _3ewg->ReadUint8(); + KeyRange.high = _3ewg->ReadUint8(); + _3ewg->SetPos(64); + ReleaseTriggerKey = _3ewg->ReadUint8(); + AltSustain1Key = _3ewg->ReadUint8(); + AltSustain2Key = _3ewg->ReadUint8(); + } + + MidiRuleLegato::MidiRuleLegato() : + LegatoSamples(12), + BypassUseController(false), + BypassKey(0), + BypassController(1), + ThresholdTime(20), + ReleaseTime(20), + ReleaseTriggerKey(0), + AltSustain1Key(0), + AltSustain2Key(0) + { + KeyRange.low = KeyRange.high = 0; + } + + void MidiRuleLegato::UpdateChunks(uint8_t* pData) const { + pData[32] = 0; + pData[33] = 16; + pData[36] = LegatoSamples; + pData[40] = BypassUseController; + pData[41] = BypassKey; + pData[42] = BypassController; + store16(&pData[43], ThresholdTime); + store16(&pData[47], ReleaseTime); + pData[51] = KeyRange.low; + pData[52] = KeyRange.high; + pData[64] = ReleaseTriggerKey; + pData[65] = AltSustain1Key; + pData[66] = AltSustain2Key; + } + + MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) { + _3ewg->SetPos(36); + Articulations = _3ewg->ReadUint8(); + int flags = _3ewg->ReadUint8(); + Polyphonic = flags & 8; + Chained = flags & 4; + Selector = (flags & 2) ? selector_controller : + (flags & 1) ? selector_key_switch : selector_none; + Patterns = _3ewg->ReadUint8(); + _3ewg->ReadUint8(); // chosen row + _3ewg->ReadUint8(); // unknown + _3ewg->ReadUint8(); // unknown + _3ewg->ReadUint8(); // unknown + KeySwitchRange.low = _3ewg->ReadUint8(); + KeySwitchRange.high = _3ewg->ReadUint8(); + Controller = _3ewg->ReadUint8(); + PlayRange.low = _3ewg->ReadUint8(); + PlayRange.high = _3ewg->ReadUint8(); + + int n = std::min(int(Articulations), 32); + for (int i = 0 ; i < n ; i++) { + _3ewg->ReadString(pArticulations[i], 32); + } + _3ewg->SetPos(1072); + n = std::min(int(Patterns), 32); + for (int i = 0 ; i < n ; i++) { + _3ewg->ReadString(pPatterns[i].Name, 16); + pPatterns[i].Size = _3ewg->ReadUint8(); + _3ewg->Read(&pPatterns[i][0], 1, 32); + } + } + + MidiRuleAlternator::MidiRuleAlternator() : + Articulations(0), + Patterns(0), + Selector(selector_none), + Controller(0), + Polyphonic(false), + Chained(false) + { + PlayRange.low = PlayRange.high = 0; + KeySwitchRange.low = KeySwitchRange.high = 0; + } + + void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const { + pData[32] = 3; + pData[33] = 16; + pData[36] = Articulations; + pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) | + (Selector == selector_controller ? 2 : + (Selector == selector_key_switch ? 1 : 0)); + pData[38] = Patterns; + + pData[43] = KeySwitchRange.low; + pData[44] = KeySwitchRange.high; + pData[45] = Controller; + pData[46] = PlayRange.low; + pData[47] = PlayRange.high; + + char* str = reinterpret_cast(pData); + int pos = 48; + int n = std::min(int(Articulations), 32); + for (int i = 0 ; i < n ; i++, pos += 32) { + strncpy(&str[pos], pArticulations[i].c_str(), 32); + } + + pos = 1072; + n = std::min(int(Patterns), 32); + for (int i = 0 ; i < n ; i++, pos += 49) { + strncpy(&str[pos], pPatterns[i].Name.c_str(), 16); + pData[pos + 16] = pPatterns[i].Size; + memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32); + } + } + +// *************** Script *************** +// * + + Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) { + pGroup = group; + pChunk = ckScri; + if (ckScri) { // object is loaded from file ... + // read header + uint32_t headerSize = ckScri->ReadUint32(); + Compression = (Compression_t) ckScri->ReadUint32(); + Encoding = (Encoding_t) ckScri->ReadUint32(); + Language = (Language_t) ckScri->ReadUint32(); + Bypass = (Language_t) ckScri->ReadUint32() & 1; + crc = ckScri->ReadUint32(); + uint32_t nameSize = ckScri->ReadUint32(); + Name.resize(nameSize, ' '); + for (int i = 0; i < nameSize; ++i) + Name[i] = ckScri->ReadUint8(); + // to handle potential future extensions of the header + ckScri->SetPos(headerSize - 6*sizeof(int32_t) + nameSize, RIFF::stream_curpos); + // read actual script data + uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos(); + data.resize(scriptSize); + for (int i = 0; i < scriptSize; ++i) + data[i] = ckScri->ReadUint8(); + } else { // this is a new script object, so just initialize it as such ... + Compression = COMPRESSION_NONE; + Encoding = ENCODING_ASCII; + Language = LANGUAGE_NKSP; + Bypass = false; + crc = 0; + Name = "Unnamed Script"; + } + } + + Script::~Script() { + } + + /** + * Returns the current script (i.e. as source code) in text format. + */ + String Script::GetScriptAsText() { + String s; + s.resize(data.size(), ' '); + memcpy(&s[0], &data[0], data.size()); + return s; + } + + /** + * Replaces the current script with the new script source code text given + * by @a text. + * + * @param text - new script source code + */ + void Script::SetScriptAsText(const String& text) { + data.resize(text.size()); + memcpy(&data[0], &text[0], text.size()); + } + + void Script::UpdateChunks() { + // recalculate CRC32 check sum + __resetCRC(crc); + __calculateCRC(&data[0], data.size(), crc); + __encodeCRC(crc); + // make sure chunk exists and has the required size + const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size(); + if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize); + else pChunk->Resize(chunkSize); + // fill the chunk data to be written to disk + uint8_t* pData = (uint8_t*) pChunk->LoadChunkData(); + int pos = 0; + store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size + pos += sizeof(int32_t); + store32(&pData[pos], Compression); + pos += sizeof(int32_t); + store32(&pData[pos], Encoding); + pos += sizeof(int32_t); + store32(&pData[pos], Language); + pos += sizeof(int32_t); + store32(&pData[pos], Bypass ? 1 : 0); + pos += sizeof(int32_t); + store32(&pData[pos], crc); + pos += sizeof(int32_t); + store32(&pData[pos], Name.size()); + pos += sizeof(int32_t); + for (int i = 0; i < Name.size(); ++i, ++pos) + pData[pos] = Name[i]; + for (int i = 0; i < data.size(); ++i, ++pos) + pData[pos] = data[i]; + } + + /** + * Move this script from its current ScriptGroup to another ScriptGroup + * given by @a pGroup. + * + * @param pGroup - script's new group + */ + void Script::SetGroup(ScriptGroup* pGroup) { + if (this->pGroup = pGroup) return; + if (pChunk) + pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList); + this->pGroup = pGroup; + } + + void Script::RemoveAllScriptReferences() { + File* pFile = pGroup->pFile; + for (int i = 0; pFile->GetInstrument(i); ++i) { + Instrument* instr = pFile->GetInstrument(i); + instr->RemoveScript(this); + } + } + +// *************** ScriptGroup *************** +// * + + ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) { + pFile = file; + pList = lstRTIS; + pScripts = NULL; + if (lstRTIS) { + RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM); + ::LoadString(ckName, Name); + } else { + Name = "Default Group"; + } + } + + ScriptGroup::~ScriptGroup() { + if (pScripts) { + std::list::iterator iter = pScripts->begin(); + std::list::iterator end = pScripts->end(); + while (iter != end) { + delete *iter; + ++iter; + } + delete pScripts; + } + } + + void ScriptGroup::UpdateChunks() { + if (pScripts) { + if (!pList) + pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS); + + // now store the name of this group as chunk as subchunk of the list chunk + ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64); + + for (std::list::iterator it = pScripts->begin(); + it != pScripts->end(); ++it) + { + (*it)->UpdateChunks(); + } + } + } + + /** @brief Get instrument script. + * + * Returns the real-time instrument script with the given index. + * + * @param index - number of the sought script (0..n) + * @returns sought script or NULL if there's no such script + */ + Script* ScriptGroup::GetScript(uint index) { + if (!pScripts) LoadScripts(); + std::list::iterator it = pScripts->begin(); + for (uint i = 0; it != pScripts->end(); ++i, ++it) + if (i == index) return *it; + return NULL; + } + + /** @brief Add new instrument script. + * + * Adds a new real-time instrument script to the file. The script is not + * actually used / executed unless it is referenced by an instrument to be + * used. This is similar to samples, which you can add to a file, without + * an instrument necessarily actually using it. + * + * You have to call Save() to make this persistent to the file. + * + * @return new empty script object + */ + Script* ScriptGroup::AddScript() { + if (!pScripts) LoadScripts(); + Script* pScript = new Script(this, NULL); + pScripts->push_back(pScript); + return pScript; + } + + /** @brief Delete an instrument script. + * + * This will delete the given real-time instrument script. References of + * instruments that are using that script will be removed accordingly. + * + * You have to call Save() to make this persistent to the file. + * + * @param pScript - script to delete + * @throws gig::Exception if given script could not be found + */ + void ScriptGroup::DeleteScript(Script* pScript) { + if (!pScripts) LoadScripts(); + std::list::iterator iter = + find(pScripts->begin(), pScripts->end(), pScript); + if (iter == pScripts->end()) + throw gig::Exception("Could not delete script, could not find given script"); + pScripts->erase(iter); + pScript->RemoveAllScriptReferences(); + if (pScript->pChunk) + pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk); + delete pScript; + } + void ScriptGroup::LoadScripts() { + if (pScripts) return; + pScripts = new std::list; + if (!pList) return; + for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck; + ck = pList->GetNextSubChunk()) + { + if (ck->GetChunkID() == CHUNK_ID_SCRI) { + pScripts->push_back(new Script(this, ck)); + } + } + } // *************** 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; @@ -2626,6 +4320,9 @@ PianoReleaseMode = false; DimensionKeyRange.low = 0; DimensionKeyRange.high = 0; + pMidiRules = new MidiRule*[3]; + pMidiRules[0] = NULL; + pScriptRefs = NULL; // Loading RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART); @@ -2640,28 +4337,75 @@ 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 (id2 == 16) { + if (id1 == 4) { + pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg); + } else if (id1 == 0) { + pMidiRules[i++] = new MidiRuleLegato(_3ewg); + } else if (id1 == 3) { + pMidiRules[i++] = new MidiRuleAlternator(_3ewg); + } else { + pMidiRules[i++] = new MidiRuleUnknown; + } + } + else if (id1 != 0 || id2 != 0) { + pMidiRules[i++] = new MidiRuleUnknown; + } + //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(); + } + // Creating Region Key Table for fast lookup + UpdateRegionKeyTable(); + } + } + + // own gig format extensions + RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS); + if (lst3LS) { + RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); + if (ckSCSL) { + int slotCount = ckSCSL->ReadUint32(); + int slotSize = ckSCSL->ReadUint32(); + int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future extensions + for (int i = 0; i < slotCount; ++i) { + _ScriptPooolEntry e; + e.fileOffset = ckSCSL->ReadUint32(); + e.bypass = ckSCSL->ReadUint32() & 1; + if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions + scriptPoolFileOffsets.push_back(e); } - rgn = lrgn->GetNextSubList(); } - // 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) { @@ -2673,6 +4417,11 @@ } Instrument::~Instrument() { + for (int i = 0 ; pMidiRules[i] ; i++) { + delete pMidiRules[i]; + } + delete[] pMidiRules; + if (pScriptRefs) delete pScriptRefs; } /** @@ -2701,17 +4450,54 @@ 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; + + if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) { + pData[32] = 0; + pData[33] = 0; + } else { + for (int i = 0 ; pMidiRules[i] ; i++) { + pMidiRules[i]->UpdateChunks(pData); + } + } + + // own gig format extensions + if (pScriptRefs) { + RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); + if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS); + const int totalSize = pScriptRefs->size() * 2*sizeof(uint32_t); + RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); + if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalSize); + else ckSCSL->Resize(totalSize); + uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData(); + for (int i = 0, pos = 0; i < pScriptRefs->size(); ++i) { + int fileOffset = + (*pScriptRefs)[i].script->pChunk->GetFilePos() - + (*pScriptRefs)[i].script->pChunk->GetPos() - + CHUNK_HEADER_SIZE; + store32(&pData[pos], fileOffset); + pos += sizeof(uint32_t); + store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0); + pos += sizeof(uint32_t); + } + } } /** @@ -2722,7 +4508,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++) { @@ -2780,6 +4566,337 @@ 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]; + } + + /** + * Adds the "controller trigger" MIDI rule to the instrument. + * + * @returns the new MIDI rule + */ + MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() { + delete pMidiRules[0]; + MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger; + pMidiRules[0] = r; + pMidiRules[1] = 0; + return r; + } + + /** + * Adds the legato MIDI rule to the instrument. + * + * @returns the new MIDI rule + */ + MidiRuleLegato* Instrument::AddMidiRuleLegato() { + delete pMidiRules[0]; + MidiRuleLegato* r = new MidiRuleLegato; + pMidiRules[0] = r; + pMidiRules[1] = 0; + return r; + } + + /** + * Adds the alternator MIDI rule to the instrument. + * + * @returns the new MIDI rule + */ + MidiRuleAlternator* Instrument::AddMidiRuleAlternator() { + delete pMidiRules[0]; + MidiRuleAlternator* r = new MidiRuleAlternator; + pMidiRules[0] = r; + pMidiRules[1] = 0; + return r; + } + + /** + * Deletes a MIDI rule from the instrument. + * + * @param i - MIDI rule number + */ + void Instrument::DeleteMidiRule(int i) { + delete pMidiRules[i]; + pMidiRules[i] = 0; + } + + void Instrument::LoadScripts() { + if (pScriptRefs) return; + pScriptRefs = new std::vector<_ScriptPooolRef>; + if (scriptPoolFileOffsets.empty()) return; + File* pFile = (File*) GetParent(); + for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) { + uint32_t offset = scriptPoolFileOffsets[k].fileOffset; + for (uint i = 0; pFile->GetScriptGroup(i); ++i) { + ScriptGroup* group = pFile->GetScriptGroup(i); + for (uint s = 0; group->GetScript(s); ++s) { + Script* script = group->GetScript(s); + if (script->pChunk) { + script->pChunk->SetPos(0); + if (script->pChunk->GetFilePos() - + script->pChunk->GetPos() - + CHUNK_HEADER_SIZE == offset) + { + _ScriptPooolRef ref; + ref.script = script; + ref.bypass = scriptPoolFileOffsets[k].bypass; + pScriptRefs->push_back(ref); + break; + } + } + } + } + } + // we don't need that anymore + scriptPoolFileOffsets.clear(); + } + + /** @brief Get instrument script (gig format extension). + * + * Returns the real-time instrument script of instrument script slot + * @a index. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param index - instrument script slot index + * @returns script or NULL if index is out of bounds + */ + Script* Instrument::GetScriptOfSlot(uint index) { + LoadScripts(); + if (index >= pScriptRefs->size()) return NULL; + return pScriptRefs->at(index).script; + } + + /** @brief Add new instrument script slot (gig format extension). + * + * Add the given real-time instrument script reference to this instrument, + * which shall be executed by the sampler for for this instrument. The + * script will be added to the end of the script list of this instrument. + * The positions of the scripts in the Instrument's Script list are + * relevant, because they define in which order they shall be executed by + * the sampler. For this reason it is also legal to add the same script + * twice to an instrument, for example you might have a script called + * "MyFilter" which performs an event filter task, and you might have + * another script called "MyNoteTrigger" which triggers new notes, then you + * might for example have the following list of scripts on the instrument: + * + * 1. Script "MyFilter" + * 2. Script "MyNoteTrigger" + * 3. Script "MyFilter" + * + * Which would make sense, because the 2nd script launched new events, which + * you might need to filter as well. + * + * There are two ways to disable / "bypass" scripts. You can either disable + * a script locally for the respective script slot on an instrument (i.e. by + * passing @c false to the 2nd argument of this method, or by calling + * SetScriptBypassed()). Or you can disable a script globally for all slots + * and all instruments by setting Script::Bypass. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param pScript - script that shall be executed for this instrument + * @param bypass - if enabled, the sampler shall skip executing this + * script (in the respective list position) + * @see SetScriptBypassed() + */ + void Instrument::AddScriptSlot(Script* pScript, bool bypass) { + LoadScripts(); + _ScriptPooolRef ref = { pScript, bypass }; + pScriptRefs->push_back(ref); + } + + /** @brief Flip two script slots with each other (gig format extension). + * + * Swaps the position of the two given scripts in the Instrument's Script + * list. The positions of the scripts in the Instrument's Script list are + * relevant, because they define in which order they shall be executed by + * the sampler. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param index1 - index of the first script slot to swap + * @param index2 - index of the second script slot to swap + */ + void Instrument::SwapScriptSlots(uint index1, uint index2) { + LoadScripts(); + if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size()) + return; + _ScriptPooolRef tmp = (*pScriptRefs)[index1]; + (*pScriptRefs)[index1] = (*pScriptRefs)[index2]; + (*pScriptRefs)[index2] = tmp; + } + + /** @brief Remove script slot. + * + * Removes the script slot with the given slot index. + * + * @param index - index of script slot to remove + */ + void Instrument::RemoveScriptSlot(uint index) { + LoadScripts(); + if (index >= pScriptRefs->size()) return; + pScriptRefs->erase( pScriptRefs->begin() + index ); + } + + /** @brief Remove reference to given Script (gig format extension). + * + * This will remove all script slots on the instrument which are referencing + * the given script. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param pScript - script reference to remove from this instrument + * @see RemoveScriptSlot() + */ + void Instrument::RemoveScript(Script* pScript) { + LoadScripts(); + for (int i = pScriptRefs->size() - 1; i >= 0; --i) { + if ((*pScriptRefs)[i].script == pScript) { + pScriptRefs->erase( pScriptRefs->begin() + i ); + } + } + } + + /** @brief Instrument's amount of script slots. + * + * This method returns the amount of script slots this instrument currently + * uses. + * + * A script slot is a reference of a real-time instrument script to be + * executed by the sampler. The scripts will be executed by the sampler in + * sequence of the slots. One (same) script may be referenced multiple + * times in different slots. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + */ + uint Instrument::ScriptSlotCount() const { + return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size(); + } + + /** @brief Whether script execution shall be skipped. + * + * Defines locally for the Script reference slot in the Instrument's Script + * list, whether the script shall be skipped by the sampler regarding + * execution. + * + * It is also possible to ignore exeuction of the script globally, for all + * slots and for all instruments by setting Script::Bypass. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param index - index of the script slot on this instrument + * @see Script::Bypass + */ + bool Instrument::IsScriptSlotBypassed(uint index) { + if (index >= ScriptSlotCount()) return false; + return pScriptRefs ? pScriptRefs->at(index).bypass + : scriptPoolFileOffsets.at(index).bypass; + + } + + /** @brief Defines whether execution shall be skipped. + * + * You can call this method to define locally whether or whether not the + * given script slot shall be executed by the sampler. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * gigedit. + * + * @param index - script slot index on this instrument + * @param bBypass - if true, the script slot will be skipped by the sampler + * @see Script::Bypass + */ + void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) { + if (index >= ScriptSlotCount()) return; + if (pScriptRefs) + pScriptRefs->at(index).bypass = bBypass; + else + scriptPoolFileOffsets.at(index).bypass = bBypass; + } + + /** + * 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) { + CopyAssign(orig, NULL); + } + + /** + * Make a (semi) deep copy of the Instrument object given by @a orig + * and assign it to this object. + * + * @param orig - original Instrument object to be copied from + * @param mSamples - crosslink map between the foreign file's samples and + * this file's samples + */ + void Instrument::CopyAssign(const Instrument* orig, const std::map* mSamples) { + // 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; + scriptPoolFileOffsets = orig->scriptPoolFileOffsets; + pScriptRefs = orig->pScriptRefs; + + // 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), + mSamples + ); + } + } + + UpdateRegionKeyTable(); + } // *************** Group *************** @@ -2819,6 +4936,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); } @@ -2894,7 +5022,17 @@ // *************** File *************** // * - const DLS::Info::FixedStringLength File::FixedStringLengths[] = { + /// Reflects Gigasampler file format version 2.0 (1998-06-28). + const DLS::version_t File::VERSION_2 = { + 0, 2, 19980628 & 0xffff, 19980628 >> 16 + }; + + /// Reflects Gigasampler file format version 3.0 (2003-03-31). + const DLS::version_t File::VERSION_3 = { + 0, 3, 20030331 & 0xffff, 20030331 >> 16 + }; + + static const DLS::Info::string_length_t _FileFixedStringLengths[] = { { CHUNK_ID_IARL, 256 }, { CHUNK_ID_IART, 128 }, { CHUNK_ID_ICMS, 128 }, @@ -2916,19 +5054,27 @@ }; File::File() : DLS::File() { + bAutoLoad = true; + *pVersion = VERSION_3; pGroups = NULL; - pInfo->FixedStringLengths = FixedStringLengths; + pScriptGroups = NULL; + 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; + pScriptGroups = NULL; + pInfo->SetFixedStringLengths(_FileFixedStringLengths); } File::~File() { @@ -2941,6 +5087,15 @@ } delete pGroups; } + if (pScriptGroups) { + std::list::iterator iter = pScriptGroups->begin(); + std::list::iterator end = pScriptGroups->end(); + while (iter != end) { + delete *iter; + ++iter; + } + delete pScriptGroups; + } } Sample* File::GetFirstSample(progress_t* pProgress) { @@ -2955,6 +5110,23 @@ SamplesIterator++; return static_cast( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL ); } + + /** + * Returns Sample object of @a index. + * + * @returns sample object or NULL if index is out of bounds + */ + Sample* File::GetSample(uint index) { + if (!pSamples) LoadSamples(); + if (!pSamples) return NULL; + DLS::File::SampleList::iterator it = pSamples->begin(); + for (int i = 0; i < index; ++i) { + ++it; + if (it == pSamples->end()) return NULL; + } + if (it == pSamples->end()) return NULL; + return static_cast( *it ); + } /** @brief Add a new sample. * @@ -2981,8 +5153,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 @@ -2994,6 +5167,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() { @@ -3084,7 +5274,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 @@ -3120,8 +5311,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); @@ -3131,6 +5324,90 @@ 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 Add content of another existing file. + * + * Duplicates the samples, groups and instruments of the original file + * given by @a pFile and adds them to @c this File. In case @c this File is + * a new one that you haven't saved before, then you have to call + * SetFileName() before calling AddContentOf(), because this method will + * automatically save this file during operation, which is required for + * writing the sample waveform data by disk streaming. + * + * @param pFile - original file whose's content shall be copied from + */ + void File::AddContentOf(File* pFile) { + static int iCallCount = -1; + iCallCount++; + std::map mGroups; + std::map mSamples; + + // clone sample groups + for (int i = 0; pFile->GetGroup(i); ++i) { + Group* g = AddGroup(); + g->Name = + "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name; + mGroups[pFile->GetGroup(i)] = g; + } + + // clone samples (not waveform data here yet) + for (int i = 0; pFile->GetSample(i); ++i) { + Sample* s = AddSample(); + s->CopyAssignMeta(pFile->GetSample(i)); + mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s); + mSamples[pFile->GetSample(i)] = s; + } + + //BUG: For some reason this method only works with this additional + // Save() call in between here. + // + // Important: The correct one of the 2 Save() methods has to be called + // here, depending on whether the file is completely new or has been + // saved to disk already, otherwise it will result in data corruption. + if (pRIFF->IsNew()) + Save(GetFileName()); + else + Save(); + + // clone instruments + // (passing the crosslink table here for the cloned samples) + for (int i = 0; pFile->GetInstrument(i); ++i) { + Instrument* instr = AddInstrument(); + instr->CopyAssign(pFile->GetInstrument(i), &mSamples); + } + + // Mandatory: file needs to be saved to disk at this point, so this + // file has the correct size and data layout for writing the samples' + // waveform data to disk. + Save(); + + // clone samples' waveform data + // (using direct read & write disk streaming) + for (int i = 0; pFile->GetSample(i); ++i) { + mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i)); + } + } /** @brief Delete an instrument. * @@ -3178,6 +5455,32 @@ } } + /// 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(); + for (int index = 0; iter != end; ++iter, ++index) { + if (*iter == pSample) { + iWaveIndex = index; + break; + } + } + 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? + _3crc->WriteUint32(&crc); + } + Group* File::GetFirstGroup() { if (!pGroups) LoadGroups(); // there must always be at least one group @@ -3207,6 +5510,24 @@ return NULL; } + /** + * Returns the group with the given group name. + * + * Note: group names don't have to be unique in the gig format! So there + * can be multiple groups with the same name. This method will simply + * return the first group found with the given name. + * + * @param name - name of the sought group + * @returns sought group or NULL if there's no group with that name + */ + Group* File::GetGroup(String name) { + if (!pGroups) LoadGroups(); + GroupsIterator = pGroups->begin(); + for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i) + if ((*GroupsIterator)->Name == name) return *GroupsIterator; + return NULL; + } + Group* File::AddGroup() { if (!pGroups) LoadGroups(); // there must always be at least one group @@ -3270,6 +5591,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(); @@ -3284,6 +5608,93 @@ } } + /** @brief Get instrument script group (by index). + * + * Returns the real-time instrument script group with the given index. + * + * @param index - number of the sought group (0..n) + * @returns sought script group or NULL if there's no such group + */ + ScriptGroup* File::GetScriptGroup(uint index) { + if (!pScriptGroups) LoadScriptGroups(); + std::list::iterator it = pScriptGroups->begin(); + for (uint i = 0; it != pScriptGroups->end(); ++i, ++it) + if (i == index) return *it; + return NULL; + } + + /** @brief Get instrument script group (by name). + * + * Returns the first real-time instrument script group found with the given + * group name. Note that group names may not necessarily be unique. + * + * @param name - name of the sought script group + * @returns sought script group or NULL if there's no such group + */ + ScriptGroup* File::GetScriptGroup(const String& name) { + if (!pScriptGroups) LoadScriptGroups(); + std::list::iterator it = pScriptGroups->begin(); + for (uint i = 0; it != pScriptGroups->end(); ++i, ++it) + if ((*it)->Name == name) return *it; + return NULL; + } + + /** @brief Add new instrument script group. + * + * Adds a new, empty real-time instrument script group to the file. + * + * You have to call Save() to make this persistent to the file. + * + * @return new empty script group + */ + ScriptGroup* File::AddScriptGroup() { + if (!pScriptGroups) LoadScriptGroups(); + ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL); + pScriptGroups->push_back(pScriptGroup); + return pScriptGroup; + } + + /** @brief Delete an instrument script group. + * + * This will delete the given real-time instrument script group and all its + * instrument scripts it contains. References inside instruments that are + * using the deleted scripts will be removed from the respective instruments + * accordingly. + * + * You have to call Save() to make this persistent to the file. + * + * @param pScriptGroup - script group to delete + * @throws gig::Exception if given script group could not be found + */ + void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) { + if (!pScriptGroups) LoadScriptGroups(); + std::list::iterator iter = + find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup); + if (iter == pScriptGroups->end()) + throw gig::Exception("Could not delete script group, could not find given script group"); + pScriptGroups->erase(iter); + for (int i = 0; pScriptGroup->GetScript(i); ++i) + pScriptGroup->DeleteScript(pScriptGroup->GetScript(i)); + if (pScriptGroup->pList) + pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList); + delete pScriptGroup; + } + + void File::LoadScriptGroups() { + if (pScriptGroups) return; + pScriptGroups = new std::list; + RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS); + if (lstLS) { + for (RIFF::List* lst = lstLS->GetFirstSubList(); lst; + lst = lstLS->GetNextSubList()) + { + if (lst->GetListType() == LIST_TYPE_RTIS) { + pScriptGroups->push_back(new ScriptGroup(this, lst)); + } + } + } + } + /** * Apply all the gig file's current instruments, samples, groups and settings * to the respective RIFF chunks. You have to call Save() to make changes @@ -3295,15 +5706,40 @@ * @throws Exception - on errors */ void File::UpdateChunks() { - RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO); + bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL; + + b64BitWavePoolOffsets = pVersion && pVersion->major == 3; + + // update own gig format extension chunks + // (not part of the GigaStudio 4 format) + // + // This must be performed before writing the chunks for instruments, + // because the instruments' script slots will write the file offsets + // of the respective instrument script chunk as reference. + if (pScriptGroups) { + RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS); + if (pScriptGroups->empty()) { + if (lst3LS) pRIFF->DeleteSubChunk(lst3LS); + } else { + if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS); + + // Update instrument script (group) chunks. + + for (std::list::iterator it = pScriptGroups->begin(); + it != pScriptGroups->end(); ++it) + { + (*it)->UpdateChunks(); + } + } + } // first update base class's chunks DLS::File::UpdateChunks(); - if (!info) { + if (newFile) { // INFO was added by Resource::UpdateChunks - make sure it // is placed first in file - info = pRIFF->GetSubList(LIST_TYPE_INFO); + RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO); RIFF::Chunk* first = pRIFF->GetFirstSubChunk(); if (first != info) { pRIFF->MoveSubChunk(info, first); @@ -3312,12 +5748,187 @@ // update group's chunks if (pGroups) { + // make sure '3gri' and '3gnl' list chunks exist + // (before updating the Group chunks) + RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI); + if (!_3gri) { + _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI); + pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL)); + } + RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL); + if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL); + + // v3: make sure the file has 128 3gnm chunks + // (before updating the Group chunks) + if (pVersion && pVersion->major == 3) { + 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(); + } + } + std::list::iterator iter = pGroups->begin(); std::list::iterator end = pGroups->end(); for (; iter != end; ++iter) { (*iter)->UpdateChunks(); } } + + // update einf chunk + + // The einf chunk contains statistics about the gig file, such + // as the number of regions and samples used by each + // instrument. It is divided in equally sized parts, where the + // first part contains information about the whole gig file, + // and the rest of the parts map to each instrument in the + // file. + // + // At the end of each part there is a bit map of each sample + // in the file, where a set bit means that the sample is used + // by the file/instrument. + // + // Note that there are several fields with unknown use. These + // are set to zero. + + int sublen = pSamples->size() / 8 + 49; + int einfSize = (Instruments + 1) * sublen; + + RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF); + if (einf) { + if (einf->GetSize() != einfSize) { + einf->Resize(einfSize); + memset(einf->LoadChunkData(), 0, einfSize); + } + } else if (newFile) { + einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize); + } + if (einf) { + uint8_t* pData = (uint8_t*) einf->LoadChunkData(); + + std::map sampleMap; + int sampleIdx = 0; + for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { + sampleMap[pSample] = sampleIdx++; + } + + int totnbusedsamples = 0; + int totnbusedchannels = 0; + int totnbregions = 0; + int totnbdimregions = 0; + int totnbloops = 0; + int instrumentIdx = 0; + + memset(&pData[48], 0, sublen - 48); + + for (Instrument* instrument = GetFirstInstrument() ; instrument ; + instrument = GetNextInstrument()) { + int nbusedsamples = 0; + int nbusedchannels = 0; + int nbdimregions = 0; + int nbloops = 0; + + memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48); + + for (Region* region = instrument->GetFirstRegion() ; region ; + region = instrument->GetNextRegion()) { + for (int i = 0 ; i < region->DimensionRegions ; i++) { + gig::DimensionRegion *d = region->pDimensionRegions[i]; + if (d->pSample) { + int sampleIdx = sampleMap[d->pSample]; + int byte = 48 + sampleIdx / 8; + int bit = 1 << (sampleIdx & 7); + if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) { + pData[(instrumentIdx + 1) * sublen + byte] |= bit; + nbusedsamples++; + nbusedchannels += d->pSample->Channels; + + if ((pData[byte] & bit) == 0) { + pData[byte] |= bit; + totnbusedsamples++; + totnbusedchannels += d->pSample->Channels; + } + } + } + if (d->SampleLoops) nbloops++; + } + nbdimregions += region->DimensionRegions; + } + // first 4 bytes unknown - sometimes 0, sometimes length of einf part + // store32(&pData[(instrumentIdx + 1) * sublen], sublen); + store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels); + store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples); + store32(&pData[(instrumentIdx + 1) * sublen + 12], 1); + store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions); + store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions); + 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 + // store32(&pData[0], sublen); + store32(&pData[4], totnbusedchannels); + store32(&pData[8], totnbusedsamples); + store32(&pData[12], Instruments); + store32(&pData[16], totnbregions); + store32(&pData[20], totnbdimregions); + store32(&pData[24], totnbloops); + // next 8 bytes unknown + // next 4 bytes unknown, not always 0 + store32(&pData[40], pSamples->size()); + // next 4 bytes unknown + } + + // update 3crc chunk + + // The 3crc chunk contains CRC-32 checksums for the + // samples. The actual checksum values will be filled in + // later, by Sample::Write. + + RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); + if (_3crc) { + _3crc->Resize(pSamples->size() * 8); + } 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; }