--- libgig/trunk/src/gig.cpp 2009/03/26 13:32:59 1875 +++ libgig/trunk/src/gig.cpp 2021/06/18 15:46:44 3945 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2009 by Christian Schoenebeck * + * Copyright (C) 2003-2021 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -24,10 +24,16 @@ #include "gig.h" #include "helper.h" +#include "Serialization.h" #include #include #include +#include + +/// libgig's current file format version (for extending the original Giga file +/// format with libgig's own custom data / custom features). +#define GIG_FILE_EXT_VERSION 2 /// Initial size of the sample buffer which is used for decompression of /// compressed sample wave streams - this value should always be bigger than @@ -50,39 +56,10 @@ #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3) #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5) -namespace gig { - -// *************** progress_t *************** -// * - - progress_t::progress_t() { - callback = NULL; - custom = NULL; - __range_min = 0.0f; - __range_max = 1.0f; - } - - // private helper function to convert progress of a subprocess into the global progress - static void __notify_progress(progress_t* pProgress, float subprogress) { - if (pProgress && pProgress->callback) { - const float totalrange = pProgress->__range_max - pProgress->__range_min; - const float totalprogress = pProgress->__range_min + subprogress * totalrange; - pProgress->factor = totalprogress; - pProgress->callback(pProgress); // now actually notify about the progress - } - } - - // private helper function to divide a progress into subprogresses - static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) { - if (pParentProgress && pParentProgress->callback) { - const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min; - pSubProgress->callback = pParentProgress->callback; - pSubProgress->custom = pParentProgress->custom; - pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks; - pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks; - } - } +#define SRLZ(member) \ + archive->serializeMember(*this, member, #member); +namespace gig { // *************** Internal functions for sample decompression *************** // * @@ -122,8 +99,8 @@ void Decompress16(int compressionmode, const unsigned char* params, int srcStep, int dstStep, const unsigned char* pSrc, int16_t* pDst, - unsigned long currentframeoffset, - unsigned long copysamples) + file_offset_t currentframeoffset, + file_offset_t copysamples) { switch (compressionmode) { case 0: // 16 bit uncompressed @@ -159,8 +136,8 @@ void Decompress24(int compressionmode, const unsigned char* params, int dstStep, const unsigned char* pSrc, uint8_t* pDst, - unsigned long currentframeoffset, - unsigned long copysamples, int truncatedBits) + file_offset_t currentframeoffset, + file_offset_t copysamples, int truncatedBits) { int y, dy, ddy, dddy; @@ -296,14 +273,14 @@ * steps. * * Once the whole data was processed by __calculateCRC(), one should - * call __encodeCRC() to get the final CRC result. + * call __finalizeCRC() 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++) { + static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) { + for (size_t i = 0 ; i < bufSize ; i++) { crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); } } @@ -313,8 +290,8 @@ * * @param crc - variable previously passed to __calculateCRC() */ - inline static uint32_t __encodeCRC(const uint32_t& crc) { - return crc ^ 0xffffffff; + inline static void __finalizeCRC(uint32_t& crc) { + crc ^= 0xffffffff; } @@ -342,10 +319,53 @@ +// *************** leverage_ctrl_t *************** +// * + + void leverage_ctrl_t::serialize(Serialization::Archive* archive) { + SRLZ(type); + SRLZ(controller_number); + } + + + +// *************** crossfade_t *************** +// * + + void crossfade_t::serialize(Serialization::Archive* archive) { + SRLZ(in_start); + SRLZ(in_end); + SRLZ(out_start); + SRLZ(out_end); + } + + + +// *************** eg_opt_t *************** +// * + + eg_opt_t::eg_opt_t() { + AttackCancel = true; + AttackHoldCancel = true; + Decay1Cancel = true; + Decay2Cancel = true; + ReleaseCancel = true; + } + + void eg_opt_t::serialize(Serialization::Archive* archive) { + SRLZ(AttackCancel); + SRLZ(AttackHoldCancel); + SRLZ(Decay1Cancel); + SRLZ(Decay2Cancel); + SRLZ(ReleaseCancel); + } + + + // *************** Sample *************** // * - unsigned int Sample::Instances = 0; + size_t Sample::Instances = 0; buffer_t Sample::InternalDecompressionBuffer; /** @brief Constructor. @@ -365,8 +385,11 @@ * ('wvpl') list chunk * @param fileNo - number of an extension file where this sample * is located, 0 otherwise + * @param index - wave pool index of sample (may be -1 on new sample) */ - Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) { + Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index) + : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) + { static const DLS::Info::string_length_t fixedStringLengths[] = { { CHUNK_ID_INAM, 64 }, { 0, 0 } @@ -376,9 +399,21 @@ FileNo = fileNo; __resetCRC(crc); + // if this is not a new sample, try to get the sample's already existing + // CRC32 checksum from disk, this checksum will reflect the sample's CRC32 + // checksum of the time when the sample was consciously modified by the + // user for the last time (by calling Sample::Write() that is). + if (index >= 0) { // not a new file ... + try { + uint32_t crc = pFile->GetSampleChecksumByIndex(index); + this->crc = crc; + } catch (...) {} + } pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX); if (pCk3gix) { + pCk3gix->SetPos(0); + uint16_t iSampleGroup = pCk3gix->ReadInt16(); pGroup = pFile->GetGroup(iSampleGroup); } else { // '3gix' chunk missing @@ -388,6 +423,8 @@ pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL); if (pCkSmpl) { + pCkSmpl->SetPos(0); + Manufacturer = pCkSmpl->ReadInt32(); Product = pCkSmpl->ReadInt32(); SamplePeriod = pCkSmpl->ReadInt32(); @@ -434,8 +471,10 @@ Dithered = false; TruncatedBits = 0; if (Compressed) { + ewav->SetPos(0); + uint32_t version = ewav->ReadInt32(); - if (version == 3 && BitDepth == 24) { + if (version > 2 && BitDepth == 24) { Dithered = ewav->ReadInt32(); ewav->SetPos(Channels == 2 ? 84 : 64); TruncatedBits = ewav->ReadInt32(); @@ -443,8 +482,8 @@ ScanCompressedSample(); } - // we use a buffer for decompression and for truncating 24 bit samples to 16 bit - if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) { + // we use a buffer for decompression only + if (Compressed && !InternalDecompressionBuffer.Size) { InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE]; InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE; } @@ -454,19 +493,87 @@ } /** + * 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 + file_offset_t restorePos = pOrig->GetPos(); + pOrig->SetPos(0); + SetPos(0); + for (file_offset_t 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. * * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. * + * @param pProgress - callback function for progress notification * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data * was provided yet * @throws gig::Exception if there is any invalid sample setting */ - void Sample::UpdateChunks() { + void Sample::UpdateChunks(progress_t* pProgress) { // first update base class's chunks - DLS::Sample::UpdateChunks(); + DLS::Sample::UpdateChunks(pProgress); // make sure 'smpl' chunk exists pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL); @@ -502,8 +609,8 @@ uint16_t iSampleGroup = 0; // 0 refers to default sample group File* pFile = static_cast(pParent); if (pFile->pGroups) { - std::list::iterator iter = pFile->pGroups->begin(); - std::list::iterator end = pFile->pGroups->end(); + std::vector::iterator iter = pFile->pGroups->begin(); + std::vector::iterator end = pFile->pGroups->end(); for (int i = 0; iter != end; i++, iter++) { if (*iter == pGroup) { iSampleGroup = i; @@ -514,13 +621,21 @@ // 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). void Sample::ScanCompressedSample() { //TODO: we have to add some more scans here (e.g. determine compression rate) this->SamplesTotal = 0; - std::list frameOffsets; + std::list frameOffsets; SamplesPerFrame = BitDepth == 24 ? 256 : 2048; WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag @@ -536,7 +651,7 @@ const int mode_l = pCkData->ReadUint8(); const int mode_r = pCkData->ReadUint8(); if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode"); - const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r]; + const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r]; if (pCkData->RemainingBytes() <= frameSize) { SamplesInLastFrame = @@ -555,7 +670,7 @@ const int mode = pCkData->ReadUint8(); if (mode > 5) throw gig::Exception("Unknown compression mode"); - const unsigned long frameSize = bytesPerFrame[mode]; + const file_offset_t frameSize = bytesPerFrame[mode]; if (pCkData->RemainingBytes() <= frameSize) { SamplesInLastFrame = @@ -571,9 +686,9 @@ // Build the frames table (which is used for fast resolving of a frame's chunk offset) if (FrameTable) delete[] FrameTable; - FrameTable = new unsigned long[frameOffsets.size()]; - std::list::iterator end = frameOffsets.end(); - std::list::iterator iter = frameOffsets.begin(); + FrameTable = new file_offset_t[frameOffsets.size()]; + std::list::iterator end = frameOffsets.end(); + std::list::iterator iter = frameOffsets.begin(); for (int i = 0; iter != end; i++, iter++) { FrameTable[i] = *iter; } @@ -614,7 +729,7 @@ * the cached sample data in bytes * @see ReleaseSampleData(), Read(), SetPos() */ - buffer_t Sample::LoadSampleData(unsigned long SampleCount) { + buffer_t Sample::LoadSampleData(file_offset_t SampleCount) { return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples } @@ -673,10 +788,10 @@ * size of the cached sample data in bytes * @see ReleaseSampleData(), Read(), SetPos() */ - buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) { + buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) { if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal; if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart; - unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize; + file_offset_t 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; @@ -740,17 +855,17 @@ * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with * other formats will fail! * - * @param iNewSize - new sample wave data size in sample points (must be - * greater than zero) + * @param NewSize - new sample wave data size in sample points (must be + * greater than zero) * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM - * or if \a iNewSize is less than 1 + * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large * @throws gig::Exception if existing sample is compressed * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize, * DLS::Sample::FormatTag, File::Save() */ - void Sample::Resize(int iNewSize) { + void Sample::Resize(file_offset_t NewSize) { if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)"); - DLS::Sample::Resize(iNewSize); + DLS::Sample::Resize(NewSize); } /** @@ -774,7 +889,7 @@ * @returns the new sample position * @see Read() */ - unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) { + file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) { if (Compressed) { switch (Whence) { case RIFF::stream_curpos: @@ -792,14 +907,14 @@ } if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal; - unsigned long frame = this->SamplePos / 2048; // to which frame to jump + file_offset_t frame = this->SamplePos / 2048; // to which frame to jump this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame return this->SamplePos; } else { // not compressed - unsigned long orderedBytes = SampleCount * this->FrameSize; - unsigned long result = pCkData->SetPos(orderedBytes, Whence); + file_offset_t orderedBytes = SampleCount * this->FrameSize; + file_offset_t result = pCkData->SetPos(orderedBytes, Whence); return (result == orderedBytes) ? SampleCount : result / this->FrameSize; } @@ -808,7 +923,7 @@ /** * Returns the current position in the sample (in sample points). */ - unsigned long Sample::GetPos() { + file_offset_t Sample::GetPos() const { if (Compressed) return SamplePos; else return pCkData->GetPos() / FrameSize; } @@ -847,9 +962,9 @@ * @returns number of successfully read sample points * @see CreateDecompressionBuffer() */ - unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, + file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState, DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) { - unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend; + file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend; uint8_t* pDst = (uint8_t*) pBuffer; SetPos(pPlaybackState->position); // recover position from the last time @@ -887,10 +1002,10 @@ // reading, swap all sample frames so it reflects // backward playback - unsigned long swapareastart = totalreadsamples; - unsigned long loopoffset = GetPos() - loop.LoopStart; - unsigned long samplestoreadinloop = Min(samplestoread, loopoffset); - unsigned long reverseplaybackend = GetPos() - samplestoreadinloop; + file_offset_t swapareastart = totalreadsamples; + file_offset_t loopoffset = GetPos() - loop.LoopStart; + file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset); + file_offset_t reverseplaybackend = GetPos() - samplestoreadinloop; SetPos(reverseplaybackend); @@ -938,11 +1053,11 @@ // reading, swap all sample frames so it reflects // backward playback - unsigned long swapareastart = totalreadsamples; - unsigned long loopoffset = GetPos() - loop.LoopStart; - unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset) + file_offset_t swapareastart = totalreadsamples; + file_offset_t loopoffset = GetPos() - loop.LoopStart; + file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset) : samplestoread; - unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength); + file_offset_t reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength); SetPos(reverseplaybackend); @@ -1022,7 +1137,7 @@ * @returns number of successfully read sample points * @see SetPos(), CreateDecompressionBuffer() */ - unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) { + file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) { if (SampleCount == 0) return 0; if (!Compressed) { if (BitDepth == 24) { @@ -1037,7 +1152,7 @@ else { if (this->SamplePos >= this->SamplesTotal) return 0; //TODO: efficiency: maybe we should test for an average compression rate - unsigned long assumedsize = GuessSize(SampleCount), + file_offset_t assumedsize = GuessSize(SampleCount), remainingbytes = 0, // remaining bytes in the local buffer remainingsamples = SampleCount, copysamples, skipsamples, @@ -1060,8 +1175,8 @@ remainingbytes = pCkData->Read(pSrc, assumedsize, 1); while (remainingsamples && remainingbytes) { - unsigned long framesamples = SamplesPerFrame; - unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset; + file_offset_t framesamples = SamplesPerFrame; + file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset; int mode_l = *pSrc++, mode_r = 0; @@ -1211,7 +1326,7 @@ * @throws gig::Exception if sample is compressed * @see DLS::LoadSampleData() */ - unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) { + file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) { if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)"); // if this is the first write in this sample, reset the @@ -1220,7 +1335,7 @@ __resetCRC(crc); } if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small"); - unsigned long res; + file_offset_t res; if (BitDepth == 24) { res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize; } else { // 16 bit @@ -1232,8 +1347,9 @@ // if this is the last write, update the checksum chunk in the // file if (pCkData->GetPos() == pCkData->GetSize()) { + __finalizeCRC(crc); File* pFile = static_cast(GetParent()); - pFile->SetSampleChecksum(this, __encodeCRC(crc)); + pFile->SetSampleChecksum(this, crc); } return res; } @@ -1254,11 +1370,11 @@ * @returns allocated decompression buffer * @see DestroyDecompressionBuffer() */ - buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) { + buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) { buffer_t result; const double worstCaseHeaderOverhead = (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0; - result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead); + result.Size = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead); result.pStart = new int8_t[result.Size]; result.NullExtensionSize = 0; return result; @@ -1292,6 +1408,72 @@ return pGroup; } + /** + * Returns the CRC-32 checksum of the sample's raw wave form data at the + * time when this sample's wave form data was modified for the last time + * by calling Write(). This checksum only covers the raw wave form data, + * not any meta informations like i.e. bit depth or loop points. Since + * this method just returns the checksum stored for this sample i.e. when + * the gig file was loaded, this method returns immediately. So it does no + * recalcuation of the checksum with the currently available sample wave + * form data. + * + * @see VerifyWaveData() + */ + uint32_t Sample::GetWaveDataCRC32Checksum() { + return crc; + } + + /** + * Checks the integrity of this sample's raw audio wave data. Whenever a + * Sample's raw wave data is intentionally modified (i.e. by calling + * Write() and supplying the new raw audio wave form data) a CRC32 checksum + * is calculated and stored/updated for this sample, along to the sample's + * meta informations. + * + * Now by calling this method the current raw audio wave data is checked + * against the already stored CRC32 check sum in order to check whether the + * sample data had been damaged unintentionally for some reason. Since by + * calling this method always the entire raw audio wave data has to be + * read, verifying all samples this way may take a long time accordingly. + * And that's also the reason why the sample integrity is not checked by + * default whenever a gig file is loaded. So this method must be called + * explicitly to fulfill this task. + * + * @param pActually - (optional) if provided, will be set to the actually + * calculated checksum of the current raw wave form data, + * you can get the expected checksum instead by calling + * GetWaveDataCRC32Checksum() + * @returns true if sample is OK or false if the sample is damaged + * @throws Exception if no checksum had been stored to disk for this + * sample yet, or on I/O issues + * @see GetWaveDataCRC32Checksum() + */ + bool Sample::VerifyWaveData(uint32_t* pActually) { + //File* pFile = static_cast(GetParent()); + uint32_t crc = CalculateWaveDataChecksum(); + if (pActually) *pActually = crc; + return crc == this->crc; + } + + uint32_t Sample::CalculateWaveDataChecksum() { + const size_t sz = 20*1024; // 20kB buffer size + std::vector buffer(sz); + buffer.resize(sz); + + const size_t n = sz / FrameSize; + SetPos(0); + uint32_t crc = 0; + __resetCRC(crc); + while (true) { + file_offset_t nRead = Read(&buffer[0], n); + if (nRead <= 0) break; + __calculateCRC(&buffer[0], nRead * FrameSize, crc); + } + __finalizeCRC(crc); + return crc; + } + Sample::~Sample() { Instances--; if (!Instances && InternalDecompressionBuffer.Size) { @@ -1308,7 +1490,7 @@ // *************** DimensionRegion *************** // * - uint DimensionRegion::Instances = 0; + size_t DimensionRegion::Instances = 0; DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL; DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) { @@ -1324,6 +1506,8 @@ RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA); if (_3ewa) { // if '3ewa' chunk exists + _3ewa->SetPos(0); + _3ewa->ReadInt32(); // unknown, always == chunk size ? LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); @@ -1433,7 +1617,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(); @@ -1502,7 +1686,7 @@ EG2Attack = 0.0; EG2Decay1 = 0.005; EG2Sustain = 1000; - EG2Release = 0.3; + EG2Release = 60; LFO2ControlDepth = 0; LFO2Frequency = 1.0; LFO2InternalDepth = 0; @@ -1557,6 +1741,54 @@ memset(DimensionUpperLimits, 127, 8); } + // chunk for own format extensions, these will *NOT* work with Gigasampler/GigaStudio ! + RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE); + if (lsde) { // format extension for EG behavior options + lsde->SetPos(0); + + eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options }; + for (int i = 0; i < 2; ++i) { // NOTE: we reserved a 3rd byte for a potential future EG3 option + unsigned char byte = lsde->ReadUint8(); + pEGOpts[i]->AttackCancel = byte & 1; + pEGOpts[i]->AttackHoldCancel = byte & (1 << 1); + pEGOpts[i]->Decay1Cancel = byte & (1 << 2); + pEGOpts[i]->Decay2Cancel = byte & (1 << 3); + pEGOpts[i]->ReleaseCancel = byte & (1 << 4); + } + } + // format extension for sustain pedal up effect on release trigger samples + if (lsde && lsde->GetSize() > 3) { // NOTE: we reserved the 3rd byte for a potential future EG3 option + lsde->SetPos(3); + uint8_t byte = lsde->ReadUint8(); + SustainReleaseTrigger = static_cast(byte & 0x03); + NoNoteOffReleaseTrigger = byte >> 7; + } else { + SustainReleaseTrigger = sust_rel_trg_none; + NoNoteOffReleaseTrigger = false; + } + // format extension for LFOs' wave form, phase displacement and for + // LFO3's flip phase + if (lsde && lsde->GetSize() > 4) { + lsde->SetPos(4); + LFO1WaveForm = static_cast( lsde->ReadUint16() ); + LFO2WaveForm = static_cast( lsde->ReadUint16() ); + LFO3WaveForm = static_cast( lsde->ReadUint16() ); + lsde->ReadUint16(); // unused 16 bits, reserved for potential future use + LFO1Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + LFO2Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + LFO3Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + const uint32_t flags = lsde->ReadInt32(); + LFO3FlipPhase = flags & 1; + } else { + LFO1WaveForm = lfo_wave_sine; + LFO2WaveForm = lfo_wave_sine; + LFO3WaveForm = lfo_wave_sine; + LFO1Phase = 0.0; + LFO2Phase = 0.0; + LFO3Phase = 0.0; + LFO3FlipPhase = false; + } + pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve, VelocityResponseDepth, VelocityResponseCurveScaling); @@ -1581,6 +1813,7 @@ */ 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 @@ -1596,6 +1829,169 @@ 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); + } + + /** + * 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]; + } + } + + void DimensionRegion::serialize(Serialization::Archive* archive) { + // in case this class will become backward incompatible one day, + // then set a version and minimum version for this class like: + //archive->setVersion(*this, 2); + //archive->setMinVersion(*this, 1); + + SRLZ(VelocityUpperLimit); + SRLZ(EG1PreAttack); + SRLZ(EG1Attack); + SRLZ(EG1Decay1); + SRLZ(EG1Decay2); + SRLZ(EG1InfiniteSustain); + SRLZ(EG1Sustain); + SRLZ(EG1Release); + SRLZ(EG1Hold); + SRLZ(EG1Controller); + SRLZ(EG1ControllerInvert); + SRLZ(EG1ControllerAttackInfluence); + SRLZ(EG1ControllerDecayInfluence); + SRLZ(EG1ControllerReleaseInfluence); + SRLZ(LFO1WaveForm); + SRLZ(LFO1Frequency); + SRLZ(LFO1Phase); + SRLZ(LFO1InternalDepth); + SRLZ(LFO1ControlDepth); + SRLZ(LFO1Controller); + SRLZ(LFO1FlipPhase); + SRLZ(LFO1Sync); + SRLZ(EG2PreAttack); + SRLZ(EG2Attack); + SRLZ(EG2Decay1); + SRLZ(EG2Decay2); + SRLZ(EG2InfiniteSustain); + SRLZ(EG2Sustain); + SRLZ(EG2Release); + SRLZ(EG2Controller); + SRLZ(EG2ControllerInvert); + SRLZ(EG2ControllerAttackInfluence); + SRLZ(EG2ControllerDecayInfluence); + SRLZ(EG2ControllerReleaseInfluence); + SRLZ(LFO2WaveForm); + SRLZ(LFO2Frequency); + SRLZ(LFO2Phase); + SRLZ(LFO2InternalDepth); + SRLZ(LFO2ControlDepth); + SRLZ(LFO2Controller); + SRLZ(LFO2FlipPhase); + SRLZ(LFO2Sync); + SRLZ(EG3Attack); + SRLZ(EG3Depth); + SRLZ(LFO3WaveForm); + SRLZ(LFO3Frequency); + SRLZ(LFO3Phase); + SRLZ(LFO3InternalDepth); + SRLZ(LFO3ControlDepth); + SRLZ(LFO3Controller); + SRLZ(LFO3FlipPhase); + SRLZ(LFO3Sync); + SRLZ(VCFEnabled); + SRLZ(VCFType); + SRLZ(VCFCutoffController); + SRLZ(VCFCutoffControllerInvert); + SRLZ(VCFCutoff); + SRLZ(VCFVelocityCurve); + SRLZ(VCFVelocityScale); + SRLZ(VCFVelocityDynamicRange); + SRLZ(VCFResonance); + SRLZ(VCFResonanceDynamic); + SRLZ(VCFResonanceController); + SRLZ(VCFKeyboardTracking); + SRLZ(VCFKeyboardTrackingBreakpoint); + SRLZ(VelocityResponseCurve); + SRLZ(VelocityResponseDepth); + SRLZ(VelocityResponseCurveScaling); + SRLZ(ReleaseVelocityResponseCurve); + SRLZ(ReleaseVelocityResponseDepth); + SRLZ(ReleaseTriggerDecay); + SRLZ(Crossfade); + SRLZ(PitchTrack); + SRLZ(DimensionBypass); + SRLZ(Pan); + SRLZ(SelfMask); + SRLZ(AttenuationController); + SRLZ(InvertAttenuationController); + SRLZ(AttenuationControllerThreshold); + SRLZ(ChannelOffset); + SRLZ(SustainDefeat); + SRLZ(MSDecode); + //SRLZ(SampleStartOffset); + SRLZ(SampleAttenuation); + SRLZ(EG1Options); + SRLZ(EG2Options); + SRLZ(SustainReleaseTrigger); + SRLZ(NoNoteOffReleaseTrigger); + + // derived attributes from DLS::Sampler + SRLZ(FineTune); + SRLZ(Gain); + } /** * Updates the respective member variable and updates @c SampleAttenuation @@ -1612,10 +2008,12 @@ * * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. + * + * @param pProgress - callback function for progress notification */ - void DimensionRegion::UpdateChunks() { + void DimensionRegion::UpdateChunks(progress_t* pProgress) { // first update base class's chunk - DLS::Sampler::UpdateChunks(); + DLS::Sampler::UpdateChunks(pProgress); RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP); uint8_t* pData = (uint8_t*) wsmp->LoadChunkData(); @@ -1628,14 +2026,14 @@ RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA); 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); + bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2; + _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, versiongt2 ? 148 : 140); } pData = (uint8_t*) _3ewa->LoadChunkData(); // update '3ewa' chunk with DimensionRegion's current settings - const uint32_t chunksize = _3ewa->GetNewSize(); + const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize(); store32(&pData[0], chunksize); // unknown, always chunk size? const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency); @@ -1837,7 +2235,7 @@ } const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth - : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */ + : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */ store16(&pData[116], eg3depth); // next 2 bytes unknown @@ -1885,7 +2283,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; @@ -1895,6 +2293,82 @@ if (chunksize >= 148) { memcpy(&pData[140], DimensionUpperLimits, 8); } + + // chunk for own format extensions, these will *NOT* work with + // Gigasampler/GigaStudio ! + RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE); + const int lsdeSize = + 3 /* EG cancel options */ + + 1 /* sustain pedal up on release trigger option */ + + 8 /* LFOs' wave forms */ + 12 /* LFOs' phase */ + 4 /* flags (LFO3FlipPhase) */; + if (!lsde && UsesAnyGigFormatExtension()) { + // only add this "LSDE" chunk if there is some (format extension) + // setting effective that would require our "LSDE" format extension + // chunk to be stored + lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize); + // move LSDE chunk to the end of parent list + pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL); + } + if (lsde) { + if (lsde->GetNewSize() < lsdeSize) + lsde->Resize(lsdeSize); + // format extension for EG behavior options + unsigned char* pData = (unsigned char*) lsde->LoadChunkData(); + eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options }; + for (int i = 0; i < 2; ++i) { // NOTE: we reserved the 3rd byte for a potential future EG3 option + pData[i] = + (pEGOpts[i]->AttackCancel ? 1 : 0) | + (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) | + (pEGOpts[i]->Decay1Cancel ? (1<<2) : 0) | + (pEGOpts[i]->Decay2Cancel ? (1<<3) : 0) | + (pEGOpts[i]->ReleaseCancel ? (1<<4) : 0); + } + // format extension for release trigger options + pData[3] = static_cast(SustainReleaseTrigger) | (NoNoteOffReleaseTrigger ? (1<<7) : 0); + // format extension for LFOs' wave form, phase displacement and for + // LFO3's flip phase + store16(&pData[4], LFO1WaveForm); + store16(&pData[6], LFO2WaveForm); + store16(&pData[8], LFO3WaveForm); + //NOTE: 16 bits reserved here for potential future use ! + const int32_t lfo1Phase = (int32_t) GIG_EXP_ENCODE(LFO1Phase); + const int32_t lfo2Phase = (int32_t) GIG_EXP_ENCODE(LFO2Phase); + const int32_t lfo3Phase = (int32_t) GIG_EXP_ENCODE(LFO3Phase); + store32(&pData[12], lfo1Phase); + store32(&pData[16], lfo2Phase); + store32(&pData[20], lfo3Phase); + const int32_t flags = LFO3FlipPhase ? 1 : 0; + store32(&pData[24], flags); + + // compile time sanity check: is our last store access here + // consistent with the initial lsdeSize value assignment? + static_assert(lsdeSize == 28, "Inconsistency in assumed 'LSDE' RIFF chunk size"); + } + } + + /** + * Returns @c true in case this DimensionRegion object uses any gig format + * extension, that is whether this DimensionRegion object currently has any + * setting effective that would require our "LSDE" RIFF chunk to be stored + * to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any + * format extension being used. Right now this method really just serves to + * answer the question whether an LSDE chunk is required, for the public API + * purpose this method would also need to check whether any other setting + * stored to the regular value '3ewa' chunk, is actually a format extension + * as well. + */ + bool DimensionRegion::UsesAnyGigFormatExtension() const { + eg_opt_t defaultOpt; + return memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) || + memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)) || + SustainReleaseTrigger || NoNoteOffReleaseTrigger || + LFO1WaveForm || LFO2WaveForm || LFO3WaveForm || + LFO1Phase || LFO2Phase || LFO3Phase || + LFO3FlipPhase; } double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) { @@ -1934,6 +2408,33 @@ // 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) { + // sanity check input parameters + // (fallback to some default parameters on ill input) + switch (curveType) { + case curve_type_nonlinear: + case curve_type_linear: + if (depth > 4) { + printf("Warning: Invalid depth (0x%x) for velocity curve type (0x%x).\n", depth, curveType); + depth = 0; + scaling = 0; + } + break; + case curve_type_special: + if (depth > 5) { + printf("Warning: Invalid depth (0x%x) for velocity curve type 'special'.\n", depth); + depth = 0; + scaling = 0; + } + break; + case curve_type_unknown: + default: + printf("Warning: Unknown velocity curve type (0x%x).\n", curveType); + curveType = curve_type_linear; + depth = 0; + scaling = 0; + break; + } + double* table; uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling; if (pVelocityTables->count(tableKey)) { // if key exists @@ -1950,6 +2451,12 @@ 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) { @@ -2061,12 +2568,258 @@ 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."); + decodedcontroller.type = leverage_ctrl_t::type_none; + decodedcontroller.controller_number = 0; + printf("Warning: Unknown leverage controller type (0x%x).\n", EncodedController); + break; } 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; @@ -2154,6 +2907,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"); } @@ -2372,7 +3307,7 @@ } Layers = 1; File* file = (File*) GetParent()->GetParent(); - int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5; + int dimensionBits = (file->pVersion && file->pVersion->major > 2) ? 8 : 5; // Actual Loading @@ -2382,6 +3317,8 @@ RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK); if (_3lnk) { + _3lnk->SetPos(0); + DimensionRegions = _3lnk->ReadUint32(); for (int i = 0; i < dimensionBits; i++) { dimension_t dimension = static_cast(_3lnk->ReadUint8()); @@ -2416,7 +3353,7 @@ UpdateVelocityTable(); // jump to start of the wave pool indices (if not already there) - if (file->pVersion && file->pVersion->major == 3) + if (file->pVersion && file->pVersion->major > 2) _3lnk->SetPos(68); // version 3 has a different 3lnk structure else _3lnk->SetPos(44); @@ -2425,7 +3362,8 @@ if (file->GetAutoLoad()) { for (uint i = 0; i < DimensionRegions; i++) { uint32_t wavepoolindex = _3lnk->ReadUint32(); - if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); + if (file->pWavePoolTable && pDimensionRegions[i]) + pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); } GetSample(); // load global region sample reference } @@ -2455,9 +3393,10 @@ * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. * + * @param pProgress - callback function for progress notification * @throws gig::Exception if samples cannot be dereferenced */ - void Region::UpdateChunks() { + void Region::UpdateChunks(progress_t* pProgress) { // in the gig format we don't care about the Region's sample reference // but we still have to provide some existing one to not corrupt the // file, so to avoid the latter we simply always assign the sample of @@ -2465,27 +3404,27 @@ pSample = pDimensionRegions[0]->pSample; // first update base class's chunks - DLS::Region::UpdateChunks(); + DLS::Region::UpdateChunks(pProgress); // update dimension region's chunks for (int i = 0; i < DimensionRegions; i++) { - pDimensionRegions[i]->UpdateChunks(); + pDimensionRegions[i]->UpdateChunks(pProgress); } File* pFile = (File*) GetParent()->GetParent(); - bool version3 = pFile->pVersion && pFile->pVersion->major == 3; - const int iMaxDimensions = version3 ? 8 : 5; - const int iMaxDimensionRegions = version3 ? 256 : 32; + const bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2; + const int iMaxDimensions = versiongt2 ? 8 : 5; + const int iMaxDimensionRegions = versiongt2 ? 256 : 32; // make sure '3lnk' chunk exists RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK); if (!_3lnk) { - const int _3lnkChunkSize = version3 ? 1092 : 172; + const int _3lnkChunkSize = versiongt2 ? 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 @@ -2504,7 +3443,7 @@ } // update wave pool table in '3lnk' chunk - const int iWavePoolOffset = version3 ? 68 : 44; + const int iWavePoolOffset = versiongt2 ? 68 : 44; for (uint i = 0; i < iMaxDimensionRegions; i++) { int iWaveIndex = -1; if (i < DimensionRegions) { @@ -2520,19 +3459,53 @@ } store32(&pData[iWavePoolOffset + i * 4], iWaveIndex); } + + // The following chunks are just added for compatibility with the + // GigaStudio software, which would show a warning if these were + // missing. However currently these chunks don't cover any useful + // data. So if this gig file uses any of our own gig format + // extensions which would cause this gig file to be unloadable + // with GSt software anyway, then just skip these GSt compatibility + // chunks here as well. + if (versiongt2 && !UsesAnyGigFormatExtension()) { + // add 3dnm list which always seems to be empty + RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM); + if (!_3dnm) _3dnm = pCkRegion->AddSubList(LIST_TYPE_3DNM); + + // add 3ddp chunk which always seems to have 16 bytes of 0xFF + RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP); + if (!_3ddp) _3ddp = pCkRegion->AddSubChunk(CHUNK_ID_3DDP, 16); + uint8_t* pData = (uint8_t*) _3ddp->LoadChunkData(); + for (int i = 0; i < 16; i += 4) { + store32(&pData[i], 0xFFFFFFFF); + } + + // move 3dnm and 3ddp to the end of the region list + pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3DNM), (RIFF::Chunk*)NULL); + pCkRegion->MoveSubChunk(pCkRegion->GetSubChunk(CHUNK_ID_3DDP), (RIFF::Chunk*)NULL); + } else { + // this is intended for the user switching from GSt >= 3 version + // back to an older format version, delete GSt3 chunks ... + RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM); + if (_3dnm) pCkRegion->DeleteSubChunk(_3dnm); + + RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP); + if (_3ddp) pCkRegion->DeleteSubChunk(_3ddp); + } } void Region::LoadDimensionRegions(RIFF::List* rgn) { RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG); if (_3prg) { int dimensionRegionNr = 0; - RIFF::List* _3ewl = _3prg->GetFirstSubList(); - while (_3ewl) { + size_t i = 0; + for (RIFF::List* _3ewl = _3prg->GetSubListAt(i); _3ewl; + _3ewl = _3prg->GetSubListAt(++i)) + { if (_3ewl->GetListType() == LIST_TYPE_3EWL) { pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl); dimensionRegionNr++; } - _3ewl = _3prg->GetNextSubList(); } if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found."); } @@ -2559,12 +3532,13 @@ int step = 1; for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits; int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step; - int end = step * pDimensionDefinitions[veldim].zones; // loop through all dimension regions for all dimensions except the velocity dimension int dim[8] = { 0 }; for (int i = 0 ; i < DimensionRegions ; i++) { + const int end = i + step * pDimensionDefinitions[veldim].zones; + // create a velocity table for all cases where the velocity zone is zero if (pDimensionRegions[i]->DimensionUpperLimits[veldim] || pDimensionRegions[i]->VelocityUpperLimit) { // create the velocity table @@ -2595,6 +3569,7 @@ } } + // jump to the next case where the velocity zone is zero int j; int shift = 0; for (j = 0 ; j < Dimensions ; j++) { @@ -2631,9 +3606,21 @@ * 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; + const int iMaxDimensions = (file->pVersion && file->pVersion->major > 2) ? 8 : 5; if (Dimensions >= iMaxDimensions) throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached"); // check if max. amount of dimension bits reached @@ -2806,6 +3793,370 @@ 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) { + if (!Dimensions) + throw gig::Exception("Could not delete dimension zone, because there is no dimension at all."); + 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); + } + // silence clang sanitizer warning + if (newDef.dimension == dimension_none) + throw gig::Exception("Unexpected internal failure resolving dimension in DeleteDimensionZone() [this is a bug]."); + + // 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. we're actually deleting and + // recreating all dimensions here, to avoid altering the precise order + // of the dimensions (which would not be an error per se, but it would + // cause usability issues with instrument editors) + { + std::vector oldDefs; + for (int i = 0; i < Dimensions; ++i) + oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference + for (int i = Dimensions - 1; i >= 0; --i) + DeleteDimension(&pDimensionDefinitions[i]); + for (int i = 0; i < oldDefs.size(); ++i) { + dimension_def_t& def = oldDefs[i]; + AddDimension( + (def.dimension == newDef.dimension) ? &newDef : &def + ); + } + } + 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 + tempRgn->DeleteChunks(); + 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) { + if (!Dimensions) + throw gig::Exception("Could not split dimension zone, because there is no dimension at all."); + 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); + } + // silence clang sanitizer warning + if (newDef.dimension == dimension_none) + throw gig::Exception("Unexpected internal failure resolving dimension in SplitDimensionZone() [this is a bug]."); + + // 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. we're actually deleting and + // recreating all dimensions here, to avoid altering the precise order + // of the dimensions (which would not be an error per se, but it would + // cause usability issues with instrument editors) + { + std::vector oldDefs; + for (int i = 0; i < Dimensions; ++i) + oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference + for (int i = Dimensions - 1; i >= 0; --i) + DeleteDimension(&pDimensionDefinitions[i]); + for (int i = 0; i < oldDefs.size(); ++i) { + dimension_def_t& def = oldDefs[i]; + AddDimension( + (def.dimension == newDef.dimension) ? &newDef : &def + ); + } + } + 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 + tempRgn->DeleteChunks(); + delete tempRgn; + + UpdateVelocityTable(); + } + + /** @brief Change type of an existing dimension. + * + * Alters the dimension type of a dimension already existing on this + * region. If there is currently no dimension on this Region with type + * @a oldType, then this call with throw an Exception. Likewise there are + * cases where the requested dimension type cannot be performed. For example + * if the new dimension type shall be gig::dimension_samplechannel, and the + * current dimension has more than 2 zones. In such cases an Exception is + * thrown as well. + * + * @param oldType - identifies the existing dimension to be changed + * @param newType - to which dimension type it should be changed to + * @throws gig::Exception if requested change cannot be performed + */ + void Region::SetDimensionType(dimension_t oldType, dimension_t newType) { + if (oldType == newType) return; + dimension_def_t* def = GetDimensionDefinition(oldType); + if (!def) + throw gig::Exception("No dimension with provided old dimension type exists on this region"); + if (newType == dimension_samplechannel && def->zones != 2) + throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones"); + if (GetDimensionDefinition(newType)) + throw gig::Exception("There is already a dimension with requested new dimension type on this region"); + def->dimension = newType; + def->split_type = __resolveSplitType(newType); + } + + 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]; @@ -2833,7 +4184,7 @@ DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) { uint8_t bits; int veldim = -1; - int velbitpos; + int velbitpos = 0; int bitpos = 0; int dimregidx = 0; for (uint i = 0; i < Dimensions; i++) { @@ -2863,20 +4214,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 = 0; + 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 @@ -2915,39 +4318,606 @@ if ((int32_t)WavePoolTableIndex == -1) return NULL; File* file = (File*) GetParent()->GetParent(); if (!file->pWavePoolTable) return NULL; - unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex]; - unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex]; - Sample* sample = file->GetFirstSample(pProgress); - while (sample) { - if (sample->ulWavePoolOffset == soughtoffset && - sample->FileNo == soughtfileno) return static_cast(sample); - sample = file->GetNextSample(); + if (WavePoolTableIndex + 1 > file->WavePoolCount) return NULL; + // for new files or files >= 2 GB use 64 bit wave pool offsets + if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) { + // use 64 bit wave pool offsets (treating this as large file) + uint64_t soughtoffset = + uint64_t(file->pWavePoolTable[WavePoolTableIndex]) | + uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32; + size_t i = 0; + for (Sample* sample = file->GetSample(i, pProgress); sample; + sample = file->GetSample(++i)) + { + if (sample->ullWavePoolOffset == soughtoffset) + return sample; + } + } else { + // use extension files and 32 bit wave pool offsets + file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex]; + file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex]; + size_t i = 0; + for (Sample* sample = file->GetSample(i, pProgress); sample; + sample = file->GetSample(++i)) + { + if (sample->ullWavePoolOffset == soughtoffset && + sample->FileNo == soughtfileno) return sample; + } } 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; + } + + /** + * Returns @c true in case this Region object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool Region::UsesAnyGigFormatExtension() const { + for (int i = 0; i < 256; i++) { + if (pDimensionRegions[i]) { + if (pDimensionRegions[i]->UsesAnyGigFormatExtension()) + return true; + } + } + return false; + } // *************** 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(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 ... + ckScri->SetPos(0); + + // read header + uint32_t headerSize = ckScri->ReadUint32(); + Compression = (Compression_t) ckScri->ReadUint32(); + Encoding = (Encoding_t) ckScri->ReadUint32(); + Language = (Language_t) ckScri->ReadUint32(); + Bypass = 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(); + // check if an uuid was already stored along with this script + if (headerSize >= 6*sizeof(int32_t) + nameSize + 16) { // yes ... + for (uint i = 0; i < 16; ++i) { + Uuid[i] = ckScri->ReadUint8(); + } + } else { // no uuid yet, generate one now ... + GenerateUuid(); + } + // to handle potential future extensions of the header + ckScri->SetPos(sizeof(int32_t) + headerSize); + // read actual script data + uint32_t scriptSize = uint32_t(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"; + GenerateUuid(); + } + } + + 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()); + } + + /** @brief Remove all RIFF chunks associated with this Script object. + * + * At the moment Script::DeleteChunks() does nothing. It is + * recommended to call this method explicitly though from deriving classes's + * own overridden implementation of this method to avoid potential future + * compatiblity issues. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void Script::DeleteChunks() { + } + + /** + * Apply this script to the respective RIFF chunks. You have to call + * File::Save() to make changes persistent. + * + * Usually there is absolutely no need to call this method explicitly. + * It will be called automatically when File::Save() was called. + * + * @param pProgress - callback function for progress notification + */ + void Script::UpdateChunks(progress_t* pProgress) { + // recalculate CRC32 check sum + __resetCRC(crc); + __calculateCRC(&data[0], data.size(), crc); + __finalizeCRC(crc); + // make sure chunk exists and has the required size + const file_offset_t chunkSize = + (file_offset_t) 7*sizeof(int32_t) + Name.size() + 16 + 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], uint32_t(6*sizeof(int32_t) + Name.size() + 16)); // 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], (uint32_t) Name.size()); + pos += sizeof(int32_t); + for (int i = 0; i < Name.size(); ++i, ++pos) + pData[pos] = Name[i]; + for (int i = 0; i < 16; ++i, ++pos) + pData[pos] = Uuid[i]; + for (int i = 0; i < data.size(); ++i, ++pos) + pData[pos] = data[i]; + } + + /** + * Generate a new Universally Unique Identifier (UUID) for this script. + */ + void Script::GenerateUuid() { + DLS::dlsid_t dlsid; + DLS::Resource::GenerateDLSID(&dlsid); + Uuid[0] = dlsid.ulData1 & 0xff; + Uuid[1] = dlsid.ulData1 >> 8 & 0xff; + Uuid[2] = dlsid.ulData1 >> 16 & 0xff; + Uuid[3] = dlsid.ulData1 >> 24 & 0xff; + Uuid[4] = dlsid.usData2 & 0xff; + Uuid[5] = dlsid.usData2 >> 8 & 0xff; + Uuid[6] = dlsid.usData3 & 0xff; + Uuid[7] = dlsid.usData3 >> 8 & 0xff; + Uuid[8] = dlsid.abData[0]; + Uuid[9] = dlsid.abData[1]; + Uuid[10] = dlsid.abData[2]; + Uuid[11] = dlsid.abData[3]; + Uuid[12] = dlsid.abData[4]; + Uuid[13] = dlsid.abData[5]; + Uuid[14] = dlsid.abData[6]; + Uuid[15] = dlsid.abData[7]; + } + + /** + * 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; + } + + /** + * Returns the script group this script currently belongs to. Each script + * is a member of exactly one ScriptGroup. + * + * @returns current script group + */ + ScriptGroup* Script::GetGroup() const { + return pGroup; + } + + /** + * Make a (semi) deep copy of the Script object given by @a orig + * and assign it to this object. Note: the ScriptGroup this Script + * object belongs to remains untouched by this call. + * + * @param orig - original Script object to be copied from + */ + void Script::CopyAssign(const Script* orig) { + Name = orig->Name; + Compression = orig->Compression; + Encoding = orig->Encoding; + Language = orig->Language; + Bypass = orig->Bypass; + data = orig->data; + } + + 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; + } + } + + /** @brief Remove all RIFF chunks associated with this ScriptGroup object. + * + * At the moment ScriptGroup::DeleteChunks() does nothing. It is + * recommended to call this method explicitly though from deriving classes's + * own overridden implementation of this method to avoid potential future + * compatiblity issues. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void ScriptGroup::DeleteChunks() { + } + + /** + * Apply this script group to the respective RIFF chunks. You have to call + * File::Save() to make changes persistent. + * + * Usually there is absolutely no need to call this method explicitly. + * It will be called automatically when File::Save() was called. + * + * @param pProgress - callback function for progress notification + */ + void ScriptGroup::UpdateChunks(progress_t* pProgress) { + 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(pProgress); + } + } + } + + /** @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; + + size_t i = 0; + for (RIFF::Chunk* ck = pList->GetSubChunkAt(i); ck; + ck = pList->GetSubChunkAt(++i)) + { + if (ck->GetChunkID() == CHUNK_ID_SCRI) { + pScripts->push_back(new Script(this, ck)); + } + } + } // *************** Instrument *************** // * @@ -2965,18 +4935,21 @@ EffectSend = 0; Attenuation = 0; FineTune = 0; - PitchbendRange = 0; + PitchbendRange = 2; 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); if (lart) { RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG); if (_3ewg) { + _3ewg->SetPos(0); + EffectSend = _3ewg->ReadUint16(); Attenuation = _3ewg->ReadInt32(); FineTune = _3ewg->ReadInt16(); @@ -2993,8 +4966,19 @@ uint8_t id1 = _3ewg->ReadUint8(); uint8_t id2 = _3ewg->ReadUint8(); - if (id1 == 4 && id2 == 16) { - pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg); + 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 @@ -3007,20 +4991,86 @@ if (!pRegions) pRegions = new RegionList; RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN); if (lrgn) { - RIFF::List* rgn = lrgn->GetFirstSubList(); - while (rgn) { + size_t i = 0; + for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn; + rgn = lrgn->GetSubListAt(++i)) + { if (rgn->GetListType() == LIST_TYPE_RGN) { - __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); + if (pProgress) + __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(); } } - __notify_progress(pProgress, 1.0f); // notify done + // own gig format extensions + RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS); + if (lst3LS) { + // script slots (that is references to instrument scripts) + RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); + if (ckSCSL) { + ckSCSL->SetPos(0); + + int headerSize = ckSCSL->ReadUint32(); + int slotCount = ckSCSL->ReadUint32(); + if (slotCount) { + int slotSize = ckSCSL->ReadUint32(); + ckSCSL->SetPos(headerSize); // in case of future header extensions + int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot 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); + } + } + } + + // overridden script 'patch' variables + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (ckSCPV) { + ckSCPV->SetPos(0); + + int nScripts = ckSCPV->ReadUint32(); + for (int iScript = 0; iScript < nScripts; ++iScript) { + _UUID uuid; + for (int i = 0; i < 16; ++i) + uuid[i] = ckSCPV->ReadUint8(); + uint slot = ckSCPV->ReadUint32(); + ckSCPV->ReadUint32(); // unused, reserved 32 bit + int nVars = ckSCPV->ReadUint32(); + for (int iVar = 0; iVar < nVars; ++iVar) { + uint8_t type = ckSCPV->ReadUint8(); + ckSCPV->ReadUint8(); // unused, reserved byte + int blobSize = ckSCPV->ReadUint16(); + RIFF::file_offset_t pos = ckSCPV->GetPos(); + // assuming 1st bit is set in 'type', otherwise blob not + // supported for decoding + if (type & 1) { + String name, value; + int len = ckSCPV->ReadUint16(); + for (int i = 0; i < len; ++i) + name += (char) ckSCPV->ReadUint8(); + len = ckSCPV->ReadUint16(); + for (int i = 0; i < len; ++i) + value += (char) ckSCPV->ReadUint8(); + if (!name.empty()) // 'name' should never be empty, but just to be sure + scriptVars[uuid][slot][name] = value; + } + // also for potential future extensions: seek forward + // according to blob size + ckSCPV->SetPos(pos + blobSize); + } + } + } + } + + if (pProgress) + __notify_progress(pProgress, 1.0f); // notify done } void Instrument::UpdateRegionKeyTable() { @@ -3029,14 +5079,20 @@ RegionList::iterator end = pRegions->end(); for (; iter != end; ++iter) { gig::Region* pRegion = static_cast(*iter); - for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) { + const int low = std::max(int(pRegion->KeyRange.low), 0); + const int high = std::min(int(pRegion->KeyRange.high), 127); + for (int iKey = low; iKey <= high; iKey++) { RegionKeyTable[iKey] = pRegion; } } } Instrument::~Instrument() { + for (int i = 0 ; pMidiRules[i] ; i++) { + delete pMidiRules[i]; + } delete[] pMidiRules; + if (pScriptRefs) delete pScriptRefs; } /** @@ -3046,18 +5102,19 @@ * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. * + * @param pProgress - callback function for progress notification * @throws gig::Exception if samples cannot be dereferenced */ - void Instrument::UpdateChunks() { + void Instrument::UpdateChunks(progress_t* pProgress) { // first update base classes' chunks - DLS::Instrument::UpdateChunks(); + DLS::Instrument::UpdateChunks(pProgress); // update Regions' chunks { RegionList::iterator iter = pRegions->begin(); RegionList::iterator end = pRegions->end(); for (; iter != end; ++iter) - (*iter)->UpdateChunks(); + (*iter)->UpdateChunks(pProgress); } // make sure 'lart' RIFF list chunk exists @@ -3069,7 +5126,7 @@ 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; + int size = (pFile->pVersion && pFile->pVersion->major > 2) ? 16416 : 12; _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size); memset(_3ewg->LoadChunkData(), 0, size); } @@ -3083,6 +5140,148 @@ 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 (ScriptSlotCount()) { + // make sure we have converted the original loaded script file + // offsets into valid Script object pointers + LoadScripts(); + + RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); + if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS); + + // save script slots (that is references to instrument scripts) + const int slotCount = (int) pScriptRefs->size(); + const int headerSize = 3 * sizeof(uint32_t); + const int slotSize = 2 * sizeof(uint32_t); + const int totalChunkSize = headerSize + slotCount * slotSize; + RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); + if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize); + else ckSCSL->Resize(totalChunkSize); + uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData(); + int pos = 0; + store32(&pData[pos], headerSize); + pos += sizeof(uint32_t); + store32(&pData[pos], slotCount); + pos += sizeof(uint32_t); + store32(&pData[pos], slotSize); + pos += sizeof(uint32_t); + for (int i = 0; i < slotCount; ++i) { + // arbitrary value, the actual file offset will be updated in + // UpdateScriptFileOffsets() after the file has been resized + int bogusFileOffset = 0; + store32(&pData[pos], bogusFileOffset); + pos += sizeof(uint32_t); + store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0); + pos += sizeof(uint32_t); + } + + // save overridden script 'patch' variables ... + + // the actual 'scriptVars' member variable might contain variables of + // scripts which are currently no longer assigned to any script slot + // of this instrument, we need to get rid of these variables here to + // prevent saving those persistently, however instead of touching the + // member variable 'scriptVars' directly, rather strip a separate + // copy such that the overridden values are not lost during an + // instrument editor session (i.e. if script might be re-assigned) + _VarsByScript vars = stripScriptVars(); + if (!vars.empty()) { + // determine total size required for 'SCPV' RIFF chunk, and the + // total amount of scripts being overridden (the latter is + // required because a script might be used on several script + // slots, hence vars.size() could then not be used here instead) + size_t totalChunkSize = 4; + size_t totalScriptsOverridden = 0; + for (const auto& script : vars) { + for (const auto& slot : script.second) { + totalScriptsOverridden++; + totalChunkSize += 16 + 4 + 4 + 4; + for (const auto& var : slot.second) { + totalChunkSize += 4 + 2 + var.first.length() + + 2 + var.second.length(); + } + } + } + + // ensure 'SCPV' RIFF chunk exists (with required size) + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (!ckSCPV) ckSCPV = lst3LS->AddSubChunk(CHUNK_ID_SCPV, totalChunkSize); + else ckSCPV->Resize(totalChunkSize); + + // store the actual data to 'SCPV' RIFF chunk + uint8_t* pData = (uint8_t*) ckSCPV->LoadChunkData(); + int pos = 0; + store32(&pData[pos], (uint32_t) totalScriptsOverridden); // scripts count + pos += 4; + for (const auto& script : vars) { + for (const auto& slot : script.second) { + for (int i = 0; i < 16; ++i) + pData[pos+i] = script.first[i]; // uuid + pos += 16; + store32(&pData[pos], (uint32_t) slot.first); // slot index + pos += 4; + store32(&pData[pos], (uint32_t) 0); // unused, reserved 32 bit + pos += 4; + store32(&pData[pos], (uint32_t) slot.second.size()); // variables count + pos += 4; + for (const auto& var : slot.second) { + pData[pos++] = 1; // type + pData[pos++] = 0; // reserved byte + store16(&pData[pos], 2 + var.first.size() + 2 + var.second.size()); // blob size + pos += 2; + store16(&pData[pos], var.first.size()); // variable name length + pos += 2; + for (int i = 0; i < var.first.size(); ++i) + pData[pos++] = var.first[i]; + store16(&pData[pos], var.second.size()); // variable value length + pos += 2; + for (int i = 0; i < var.second.size(); ++i) + pData[pos++] = var.second[i]; + } + } + } + } else { + // no script variable overridden by this instrument, so get rid + // of 'SCPV' RIFF chunk (if any) + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (ckSCPV) lst3LS->DeleteSubChunk(ckSCPV); + } + } else { + // no script slots, so get rid of any LS custom RIFF chunks (if any) + RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); + if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS); + } + } + + void Instrument::UpdateScriptFileOffsets() { + // own gig format extensions + if (pScriptRefs && pScriptRefs->size() > 0) { + RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); + RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); + const int slotCount = (int) pScriptRefs->size(); + const int headerSize = 3 * sizeof(uint32_t); + ckSCSL->SetPos(headerSize); + for (int i = 0; i < slotCount; ++i) { + uint32_t fileOffset = uint32_t( + (*pScriptRefs)[i].script->pChunk->GetFilePos() - + (*pScriptRefs)[i].script->pChunk->GetPos() - + CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize()) + ); + ckSCSL->WriteUint32(&fileOffset); + // jump over flags entry (containing the bypass flag) + ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos); + } + } } /** @@ -3104,11 +5303,28 @@ } /** + * Returns Region at supplied @a pos position within the region list of + * this instrument. If supplied @a pos is out of bounds then @c NULL is + * returned. + * + * @param pos - position of sought Region in region list + * @returns pointer address to requested region or @c NULL if @a pos is + * out of bounds + */ + Region* Instrument::GetRegionAt(size_t pos) { + if (!pRegions) return NULL; + if (pos >= pRegions->size()) return NULL; + return static_cast( (*pRegions)[pos] ); + } + + /** * Returns the first Region of the instrument. You have to call this * method once before you use GetNextRegion(). * * @returns pointer address to first region or NULL if there is none * @see GetNextRegion() + * @deprecated This method is not reentrant-safe, use GetRegionAt() + * instead. */ Region* Instrument::GetFirstRegion() { if (!pRegions) return NULL; @@ -3123,6 +5339,8 @@ * * @returns pointer address to the next region or NULL if end reached * @see GetFirstRegion() + * @deprecated This method is not reentrant-safe, use GetRegionAt() + * instead. */ Region* Instrument::GetNextRegion() { if (!pRegions) return NULL; @@ -3137,7 +5355,7 @@ RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN); Region* pNewRegion = new Region(this, rgn); pRegions->push_back(pNewRegion); - Regions = pRegions->size(); + Regions = (uint32_t) pRegions->size(); // update Region key table for fast lookup UpdateRegionKeyTable(); // done @@ -3152,6 +5370,70 @@ } /** + * Move this instrument at the position before @arg dst. + * + * This method can be used to reorder the sequence of instruments in a + * .gig file. This might be helpful especially on large .gig files which + * contain a large number of instruments within the same .gig file. So + * grouping such instruments to similar ones, can help to keep track of them + * when working with such complex .gig files. + * + * When calling this method, this instrument will be removed from in its + * current position in the instruments list and moved to the requested + * target position provided by @param dst. You may also pass NULL as + * argument to this method, in that case this intrument will be moved to the + * very end of the .gig file's instrument list. + * + * You have to call Save() to make the order change persistent to the .gig + * file. + * + * Currently this method is limited to moving the instrument within the same + * .gig file. Trying to move it to another .gig file by calling this method + * will throw an exception. + * + * @param dst - destination instrument at which this instrument will be + * moved to, or pass NULL for moving to end of list + * @throw gig::Exception if this instrument and target instrument are not + * part of the same file, as well as on unexpected + * internal error + */ + void Instrument::MoveTo(Instrument* dst) { + if (dst && GetParent() != dst->GetParent()) + throw Exception( + "gig::Instrument::MoveTo() can only be used for moving within " + "the same gig file." + ); + + File* pFile = (File*) GetParent(); + + // move this instrument within the instrument list + { + File::InstrumentList& list = *pFile->pInstruments; + + File::InstrumentList::iterator itFrom = + std::find(list.begin(), list.end(), static_cast(this)); + if (itFrom == list.end()) + throw Exception( + "gig::Instrument::MoveTo(): unexpected missing membership " + "of this instrument." + ); + list.erase(itFrom); + + File::InstrumentList::iterator itTo = + std::find(list.begin(), list.end(), static_cast(dst)); + + list.insert(itTo, this); + } + + // move the instrument's actual list RIFF chunk appropriately + RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS); + lstCkInstruments->MoveSubChunk( + this->pCkInstrument, + (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL) + ); + } + + /** * Returns a MIDI rule of the instrument. * * The list of MIDI rules, at least in gig v3, always contains at @@ -3165,6 +5447,616 @@ 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 soughtOffset = 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) { + uint32_t offset = uint32_t( + script->pChunk->GetFilePos() - + script->pChunk->GetPos() - + CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize()) + ); + if (offset == soughtOffset) + { + _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 (ssize_t 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 uint(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; + } + + /// type cast (by copy) uint8_t[16] -> std::array + inline std::array _UUIDFromCArray(const uint8_t* pData) { + std::array uuid; + memcpy(&uuid[0], pData, 16); + return uuid; + } + + /** + * Returns true if this @c Instrument has any script slot which references + * the @c Script identified by passed @p uuid. + */ + bool Instrument::ReferencesScriptWithUuid(const _UUID& uuid) { + const uint nSlots = ScriptSlotCount(); + for (uint iSlot = 0; iSlot < nSlots; ++iSlot) + if (_UUIDFromCArray(&GetScriptOfSlot(iSlot)->Uuid[0]) == uuid) + return true; + return false; + } + + /** @brief Checks whether a certain script 'patch' variable value is set. + * + * Returns @c true if the initial value for the requested script variable is + * currently overridden by this instrument. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @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 slot - script slot index of the variable to be retrieved + * @param variable - name of the 'patch' variable in that script + */ + bool Instrument::IsScriptPatchVariableSet(int slot, String variable) { + if (variable.empty()) return false; + Script* script = GetScriptOfSlot(slot); + if (!script) return false; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return false; + const _VarsBySlot& slots = scriptVars.find(uuid)->second; + if (slots.empty()) return false; + if (slots.count(slot)) + return slots.find(slot)->second.count(variable); + else + return slots.begin()->second.count(variable); + } + + /** @brief Get all overridden script 'patch' variables. + * + * Returns map of key-value pairs reflecting all patch variables currently + * being overridden by this instrument for the given script @p slot, where + * key is the variable name and value is the hereby currently overridden + * value for that variable. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @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 slot - script slot index of the variable to be retrieved + */ + std::map Instrument::GetScriptPatchVariables(int slot) { + Script* script = GetScriptOfSlot(slot); + if (!script) return std::map(); + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return std::map(); + const _VarsBySlot& slots = scriptVars.find(uuid)->second; + if (slots.empty()) return std::map(); + const _PatchVars& vars = + (slots.count(slot)) ? + slots.find(slot)->second : slots.begin()->second; + return vars; + } + + /** @brief Get overridden initial value for 'patch' variable. + * + * Returns current initial value for the requested script variable being + * overridden by this instrument. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @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 slot - script slot index of the variable to be retrieved + * @param variable - name of the 'patch' variable in that script + */ + String Instrument::GetScriptPatchVariable(int slot, String variable) { + std::map vars = GetScriptPatchVariables(slot); + return (vars.count(variable)) ? vars.find(variable)->second : ""; + } + + /** @brief Override initial value for 'patch' variable. + * + * Overrides initial value for the requested script variable for this + * instrument with the passed value. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @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 slot - script slot index of the variable to be set + * @param variable - name of the 'patch' variable in that script + * @param value - overridden initial value for that script variable + * @throws gig::Exception if given script @p slot index is invalid or given + * @p variable name is empty + */ + void Instrument::SetScriptPatchVariable(int slot, String variable, String value) { + if (variable.empty()) + throw Exception("Variable name must not be empty"); + Script* script = GetScriptOfSlot(slot); + if (!script) + throw Exception("No script slot with index " + ToString(slot)); + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + scriptVars[uuid][slot][variable] = value; + } + + /** @brief Drop overridden initial value(s) for 'patch' variable(s). + * + * Reverts initial value(s) for requested script variable(s) back to their + * default initial value(s) defined in the script itself. + * + * Both arguments of this method are optional. The most obvious use case of + * this method would be passing a valid script @p slot index and a + * (non-emtpy string as) @p variable name to this method, which would cause + * that single variable to be unset for that specific script slot (on this + * @c Instrument level). + * + * Not passing a value (or @c -1 for @p slot and/or empty string for + * @p variable) means 'wildcard'. So accordingly absence of argument(s) will + * cause all variables and/or for all script slots being unset. Hence this + * method serves 2^2 = 4 possible use cases in total and accordingly covers + * 4 different behaviours in one method. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @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 slot - script slot index of the variable to be unset + * @param variable - name of the 'patch' variable in that script + */ + void Instrument::UnsetScriptPatchVariable(int slot, String variable) { + Script* script = GetScriptOfSlot(slot); + + // option 1: unset a particular variable of one particular script slot + if (slot != -1 && !variable.empty()) { + if (!script) return; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return; + if (!scriptVars[uuid].count(slot)) return; + if (scriptVars[uuid][slot].count(variable)) + scriptVars[uuid][slot].erase( + scriptVars[uuid][slot].find(variable) + ); + if (scriptVars[uuid][slot].empty()) + scriptVars[uuid].erase( scriptVars[uuid].find(slot) ); + if (scriptVars[uuid].empty()) + scriptVars.erase( scriptVars.find(uuid) ); + return; + } + + // option 2: unset all variables of all script slots + if (slot == -1 && variable.empty()) { + scriptVars.clear(); + return; + } + + // option 3: unset all variables of one particular script slot only + if (slot != -1) { + if (!script) return; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (scriptVars.count(uuid)) + scriptVars.erase( scriptVars.find(uuid) ); + return; + } + + // option 4: unset a particular variable of all script slots + _VarsByScript::iterator itScript = scriptVars.begin(); + _VarsByScript::iterator endScript = scriptVars.end(); + while (itScript != endScript) { + _VarsBySlot& slots = itScript->second; + _VarsBySlot::iterator itSlot = slots.begin(); + _VarsBySlot::iterator endSlot = slots.end(); + while (itSlot != endSlot) { + _PatchVars& vars = itSlot->second; + if (vars.count(variable)) + vars.erase( vars.find(variable) ); + if (vars.empty()) + slots.erase(itSlot++); // postfix increment to avoid iterator invalidation + else + ++itSlot; + } + if (slots.empty()) + scriptVars.erase(itScript++); // postfix increment to avoid iterator invalidation + else + ++itScript; + } + } + + /** + * Returns stripped version of member variable @c scriptVars, where scripts + * no longer referenced by this @c Instrument are filtered out, and so are + * variables of meanwhile obsolete slots (i.e. a script still being + * referenced, but previously overridden on a script slot which either no + * longer exists or is hosting another script now). + */ + Instrument::_VarsByScript Instrument::stripScriptVars() { + _VarsByScript vars; + _VarsByScript::const_iterator itScript = scriptVars.begin(); + _VarsByScript::const_iterator endScript = scriptVars.end(); + for (; itScript != endScript; ++itScript) { + const _UUID& uuid = itScript->first; + if (!ReferencesScriptWithUuid(uuid)) + continue; + const _VarsBySlot& slots = itScript->second; + _VarsBySlot::const_iterator itSlot = slots.begin(); + _VarsBySlot::const_iterator endSlot = slots.end(); + for (; itSlot != endSlot; ++itSlot) { + Script* script = GetScriptOfSlot(itSlot->first); + if (!script) continue; + if (_UUIDFromCArray(&script->Uuid[0]) != uuid) continue; + if (itSlot->second.empty()) continue; + vars[uuid][itSlot->first] = itSlot->second; + } + } + return vars; + } + + /** + * 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; + // deep copy of pScriptRefs required (to avoid undefined behaviour) + if (pScriptRefs) delete pScriptRefs; + pScriptRefs = new std::vector<_ScriptPooolRef>; + if (orig->pScriptRefs) + *pScriptRefs = *orig->pScriptRefs; + scriptVars = orig->scriptVars; + + // 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(GetRegionAt(0)); + // 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(); + } + + /** + * Returns @c true in case this Instrument object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool Instrument::UsesAnyGigFormatExtension() const { + if (!pRegions) return false; + if (!scriptVars.empty()) return true; + RegionList::const_iterator iter = pRegions->begin(); + RegionList::const_iterator end = pRegions->end(); + for (; iter != end; ++iter) { + gig::Region* rgn = static_cast(*iter); + if (rgn->UsesAnyGigFormatExtension()) + return true; + } + return false; + } + // *************** Group *************** // * @@ -3178,12 +6070,27 @@ Group::Group(File* file, RIFF::Chunk* ck3gnm) { pFile = file; pNameChunk = ck3gnm; + SamplesIterator = 0; ::LoadString(pNameChunk, Name); } + /** @brief Destructor. + * + * Currently this destructor implementation does nothing. + */ Group::~Group() { - // remove the chunk associated with this group (if any) - if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk); + } + + /** @brief Remove all RIFF chunks associated with this Group object. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void Group::DeleteChunks() { + // handle own RIFF chunks + if (pNameChunk) { + pNameChunk->GetParent()->DeleteSubChunk(pNameChunk); + pNameChunk = NULL; + } } /** @brief Update chunks with current group settings. @@ -3193,8 +6100,10 @@ * * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. + * + * @param pProgress - callback function for progress notification */ - void Group::UpdateChunks() { + void Group::UpdateChunks(progress_t* pProgress) { // make sure <3gri> and <3gnl> list chunks exist RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI); if (!_3gri) { @@ -3204,9 +6113,10 @@ RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL); if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL); - if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) { + if (!pNameChunk && pFile->pVersion && pFile->pVersion->major > 2) { // v3 has a fixed list of 128 strings, find a free one - for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) { + size_t i = 0; + for (RIFF::Chunk* ck = _3gnl->GetSubChunkAt(i); ck; ck = _3gnl->GetSubChunkAt(++i)) { if (strcmp(static_cast(ck->LoadChunkData()), "") == 0) { pNameChunk = ck; break; @@ -3219,6 +6129,26 @@ } /** + * Returns Sample object at @a index of this sample group. + * + * @param index - position of sample in this sample group's sample list + * (0..n) + * @returns sample object or NULL if index is out of bounds + */ + Sample* Group::GetSample(size_t index) { + if (pFile->pSamples && index >= pFile->pSamples->size()) return NULL; + size_t indexInFile = 0; + size_t indexInGroup = 0; + for (Sample* pSample = pFile->GetSample(indexInFile); pSample; + pSample = pFile->GetSample(++indexInFile)) + { + if (pSample->GetGroup() != this) continue; + if (indexInGroup++ == index) return pSample; + } + return NULL; + } + + /** * Returns the first Sample of this Group. You have to call this method * once before you use GetNextSample(). * @@ -3228,11 +6158,17 @@ * @returns pointer address to first Sample or NULL if there is none * applied to this Group * @see GetNextSample() + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. */ Sample* Group::GetFirstSample() { - // FIXME: lazy und unsafe implementation, should be an autonomous iterator - for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) { - if (pSample->GetGroup() == this) return pSample; + size_t& i = this->SamplesIterator; + i = 0; + for (Sample* pSample = pFile->GetSample(i); pSample; + pSample = pFile->GetSample(++i)) + { + if (pSample->GetGroup() == this) + return pSample; } return NULL; } @@ -3246,11 +6182,16 @@ * @returns pointer address to the next Sample of this Group or NULL if * end reached * @see GetFirstSample() + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. */ Sample* Group::GetNextSample() { - // FIXME: lazy und unsafe implementation, should be an autonomous iterator - for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) { - if (pSample->GetGroup() == this) return pSample; + size_t& i = this->SamplesIterator; + for (Sample* pSample = pFile->GetSample(++i); pSample; + pSample = pFile->GetSample(++i)) + { + if (pSample->GetGroup() == this) + return pSample; } return NULL; } @@ -3270,8 +6211,11 @@ */ void Group::MoveAll() { // get "that" other group first + size_t i = 0; Group* pOtherGroup = NULL; - for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) { + for (pOtherGroup = pFile->GetGroup(i); pOtherGroup; + pOtherGroup = pFile->GetGroup(++i)) + { if (pOtherGroup != this) break; } if (!pOtherGroup) throw Exception( @@ -3279,7 +6223,8 @@ "other Group. This is a bug, report it!" ); // now move all samples of this group to the other group - for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { + Sample* pSample; + while ((pSample = GetSample(0))) { pOtherGroup->AddSample(pSample); } } @@ -3299,6 +6244,11 @@ 0, 3, 20030331 & 0xffff, 20030331 >> 16 }; + /// Reflects Gigasampler file format version 4.0 (2007-10-12). + const DLS::version_t File::VERSION_4 = { + 0, 4, 20071012 & 0xffff, 20071012 >> 16 + }; + static const DLS::Info::string_length_t _FileFixedStringLengths[] = { { CHUNK_ID_IARL, 256 }, { CHUNK_ID_IART, 128 }, @@ -3324,6 +6274,7 @@ bAutoLoad = true; *pVersion = VERSION_3; pGroups = NULL; + pScriptGroups = NULL; pInfo->SetFixedStringLengths(_FileFixedStringLengths); pInfo->ArchivalLocation = String(256, ' '); @@ -3339,21 +6290,39 @@ File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) { bAutoLoad = true; pGroups = NULL; + pScriptGroups = NULL; pInfo->SetFixedStringLengths(_FileFixedStringLengths); } File::~File() { if (pGroups) { - std::list::iterator iter = pGroups->begin(); - std::list::iterator end = pGroups->end(); + std::vector::iterator iter = pGroups->begin(); + std::vector::iterator end = pGroups->end(); while (iter != end) { delete *iter; ++iter; } delete pGroups; } + if (pScriptGroups) { + std::list::iterator iter = pScriptGroups->begin(); + std::list::iterator end = pScriptGroups->end(); + while (iter != end) { + delete *iter; + ++iter; + } + delete pScriptGroups; + } } + /** + * Returns a pointer to the first Sample object of the file, + * NULL otherwise. + * + * @param pProgress - optional: callback function for progress notification + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. + */ Sample* File::GetFirstSample(progress_t* pProgress) { if (!pSamples) LoadSamples(pProgress); if (!pSamples) return NULL; @@ -3361,11 +6330,46 @@ return static_cast( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL ); } + /** + * Returns a pointer to the next Sample object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. + */ Sample* File::GetNextSample() { if (!pSamples) return NULL; SamplesIterator++; return static_cast( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL ); } + + /** + * Returns Sample object of @a index. + * + * @param index - position of sample in sample list (0..n) + * @param pProgress - optional: callback function for progress notification + * @returns sample object or NULL if index is out of bounds + */ + Sample* File::GetSample(size_t index, progress_t* pProgress) { + if (!pSamples) LoadSamples(pProgress); + if (!pSamples) return NULL; + if (index >= pSamples->size()) return NULL; + return static_cast( (*pSamples)[index] ); + } + + /** + * Returns the total amount of samples of this gig file. + * + * Note that this method might block for a long time in case it is required + * to load the sample info for the first time. + * + * @returns total amount of samples + */ + size_t File::CountSamples() { + if (!pSamples) LoadSamples(); + if (!pSamples) return 0; + return pSamples->size(); + } /** @brief Add a new sample. * @@ -3405,15 +6409,19 @@ if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample"); if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation pSamples->erase(iter); + pSample->DeleteChunks(); 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()) { - + size_t iIns = 0; + for (Instrument* instrument = GetInstrument(iIns); instrument; + instrument = GetInstrument(++iIns)) + { + size_t iRgn = 0; + for (Region* region = instrument->GetRegionAt(iRgn); region; + region = instrument->GetRegionAt(++iRgn)) + { if (region->GetSample() == pSample) region->SetSample(NULL); for (int i = 0 ; i < region->DimensionRegions ; i++) { @@ -3436,55 +6444,117 @@ if (!pSamples) pSamples = new SampleList; - RIFF::File* file = pRIFF; - // just for progress calculation int iSampleIndex = 0; int iTotalSamples = WavePoolCount; - // check if samples should be loaded from extension files - int lastFileNo = 0; - for (int i = 0 ; i < WavePoolCount ; i++) { - if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i]; - } - String name(pRIFF->GetFileName()); - int nameLen = name.length(); - char suffix[6]; - if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4; - - for (int fileNo = 0 ; ; ) { + // just for assembling path of optional extension files to be read + const std::string folder = parentPath(pRIFF->GetFileName()); + const std::string baseName = pathWithoutExtension(pRIFF->GetFileName()); + + // the main gig file and the extension files (.gx01, ... , .gx98) may + // contain wave data (wave pool) + std::vector poolFiles; + poolFiles.push_back(pRIFF); + + // get info about all extension files + RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL); + if (ckXfil) { // there are extension files (.gx01, ... , .gx98) ... + const uint32_t n = ckXfil->ReadInt32(); + for (int i = 0; i < n; i++) { + // read the filename and load the extension file + std::string name; + ckXfil->ReadString(name, 128); + std::string path = concatPath(folder, name); + RIFF::File* pExtFile = new RIFF::File(path); + // check that the dlsids match + RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID); + if (ckDLSID) { + ::DLS::dlsid_t idExpected; + idExpected.ulData1 = ckXfil->ReadInt32(); + idExpected.usData2 = ckXfil->ReadInt16(); + idExpected.usData3 = ckXfil->ReadInt16(); + ckXfil->Read(idExpected.abData, 8, 1); + ::DLS::dlsid_t idFound; + ckDLSID->Read(&idFound.ulData1, 1, 4); + ckDLSID->Read(&idFound.usData2, 1, 2); + ckDLSID->Read(&idFound.usData3, 1, 2); + ckDLSID->Read(idFound.abData, 8, 1); + if (memcmp(&idExpected, &idFound, 16) != 0) + throw gig::Exception("dlsid mismatch for extension file: %s", path.c_str()); + } + poolFiles.push_back(pExtFile); + ExtensionFiles.push_back(pExtFile); + } + } + + // check if a .gx99 (GigaPulse) file exists + RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF); + if (ckDoxf) { // there is a .gx99 (GigaPulse) file ... + std::string path = baseName + ".gx99"; + RIFF::File* pExtFile = new RIFF::File(path); + + // skip unused int and filename + ckDoxf->SetPos(132, RIFF::stream_curpos); + + // check that the dlsids match + RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID); + if (ckDLSID) { + ::DLS::dlsid_t idExpected; + idExpected.ulData1 = ckDoxf->ReadInt32(); + idExpected.usData2 = ckDoxf->ReadInt16(); + idExpected.usData3 = ckDoxf->ReadInt16(); + ckDoxf->Read(idExpected.abData, 8, 1); + ::DLS::dlsid_t idFound; + ckDLSID->Read(&idFound.ulData1, 1, 4); + ckDLSID->Read(&idFound.usData2, 1, 2); + ckDLSID->Read(&idFound.usData3, 1, 2); + ckDLSID->Read(idFound.abData, 8, 1); + if (memcmp(&idExpected, &idFound, 16) != 0) + throw gig::Exception("dlsid mismatch for GigaPulse file: %s", path.c_str()); + } + poolFiles.push_back(pExtFile); + ExtensionFiles.push_back(pExtFile); + } + + // load samples from extension files (if required) + for (int i = 0; i < poolFiles.size(); i++) { + RIFF::File* file = poolFiles[i]; RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL); if (wvpl) { - unsigned long wvplFileOffset = wvpl->GetFilePos(); - RIFF::List* wave = wvpl->GetFirstSubList(); - while (wave) { + file_offset_t wvplFileOffset = wvpl->GetFilePos() - + wvpl->GetPos(); // should be zero, but just to be sure + size_t i = 0; + for (RIFF::List* wave = wvpl->GetSubListAt(i); wave; + wave = wvpl->GetSubListAt(++i)) + { if (wave->GetListType() == LIST_TYPE_WAVE) { // notify current progress - const float subprogress = (float) iSampleIndex / (float) iTotalSamples; - __notify_progress(pProgress, subprogress); + if (pProgress) { + const float subprogress = (float) iSampleIndex / (float) iTotalSamples; + __notify_progress(pProgress, subprogress); + } - unsigned long waveFileOffset = wave->GetFilePos(); - pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo)); + file_offset_t waveFileOffset = wave->GetFilePos(); + pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex)); iSampleIndex++; } - wave = wvpl->GetNextSubList(); } - - if (fileNo == lastFileNo) break; - - // open extension file (*.gx01, *.gx02, ...) - fileNo++; - sprintf(suffix, ".gx%02d", fileNo); - name.replace(nameLen, 5, suffix); - file = new RIFF::File(name); - ExtensionFiles.push_back(file); - } else break; + } } - __notify_progress(pProgress, 1.0); // notify done + if (pProgress) + __notify_progress(pProgress, 1.0); // notify done } + /** + * Returns a pointer to the first Instrument object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetInstrument() + * instead. + */ Instrument* File::GetFirstInstrument() { if (!pInstruments) LoadInstruments(); if (!pInstruments) return NULL; @@ -3492,6 +6562,13 @@ return static_cast( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL ); } + /** + * Returns a pointer to the next Instrument object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetInstrument() + * instead. + */ Instrument* File::GetNextInstrument() { if (!pInstruments) return NULL; InstrumentsIterator++; @@ -3499,40 +6576,59 @@ } /** + * Returns the total amount of instruments of this gig file. + * + * Note that this method might block for a long time in case it is required + * to load the instruments info for the first time. + * + * @returns total amount of instruments + */ + size_t File::CountInstruments() { + if (!pInstruments) LoadInstruments(); + if (!pInstruments) return 0; + return pInstruments->size(); + } + + /** * Returns the instrument with the given index. * * @param index - number of the sought instrument (0..n) * @param pProgress - optional: callback function for progress notification * @returns sought instrument or NULL if there's no such instrument */ - Instrument* File::GetInstrument(uint index, progress_t* pProgress) { + Instrument* File::GetInstrument(size_t index, progress_t* pProgress) { if (!pInstruments) { // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM) - // sample loading subtask - progress_t subprogress; - __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask - __notify_progress(&subprogress, 0.0f); - if (GetAutoLoad()) - GetFirstSample(&subprogress); // now force all samples to be loaded - __notify_progress(&subprogress, 1.0f); - - // instrument loading subtask - if (pProgress && pProgress->callback) { - subprogress.__range_min = subprogress.__range_max; - subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask - } - __notify_progress(&subprogress, 0.0f); - LoadInstruments(&subprogress); - __notify_progress(&subprogress, 1.0f); + if (pProgress) { + // sample loading subtask + progress_t subprogress; + __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask + __notify_progress(&subprogress, 0.0f); + if (GetAutoLoad()) + GetSample(0, &subprogress); // now force all samples to be loaded + __notify_progress(&subprogress, 1.0f); + + // instrument loading subtask + if (pProgress->callback) { + subprogress.__range_min = subprogress.__range_max; + subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask + } + __notify_progress(&subprogress, 0.0f); + LoadInstruments(&subprogress); + __notify_progress(&subprogress, 1.0f); + } else { + // sample loading subtask + if (GetAutoLoad()) + GetSample(0); // now force all samples to be loaded + + // instrument loading subtask + LoadInstruments(); + } } if (!pInstruments) return NULL; - InstrumentsIterator = pInstruments->begin(); - for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) { - if (i == index) return static_cast( *InstrumentsIterator ); - InstrumentsIterator++; - } - return NULL; + if (index >= pInstruments->size()) return NULL; + return static_cast( (*pInstruments)[index] ); } /** @brief Add a new instrument definition. @@ -3563,6 +6659,102 @@ 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; + } + + // clone script groups and their scripts + for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) { + ScriptGroup* sg = pFile->GetScriptGroup(iGroup); + ScriptGroup* dg = AddScriptGroup(); + dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name; + for (int iScript = 0; sg->GetScript(iScript); ++iScript) { + Script* ss = sg->GetScript(iScript); + Script* ds = dg->AddScript(); + ds->CopyAssign(ss); + } + } + + //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. * @@ -3577,6 +6769,7 @@ InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument); if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument"); pInstruments->erase(iter); + pInstrument->DeleteChunks(); delete pInstrument; } @@ -3589,24 +6782,30 @@ RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS); if (lstInstruments) { int iInstrumentIndex = 0; - RIFF::List* lstInstr = lstInstruments->GetFirstSubList(); - while (lstInstr) { + size_t i = 0; + for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i); + lstInstr; lstInstr = lstInstruments->GetSubListAt(++i)) + { if (lstInstr->GetListType() == LIST_TYPE_INS) { - // notify current progress - const float localProgress = (float) iInstrumentIndex / (float) Instruments; - __notify_progress(pProgress, localProgress); - - // divide local progress into subprogress for loading current Instrument - progress_t subprogress; - __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex); + if (pProgress) { + // notify current progress + const float localProgress = (float) iInstrumentIndex / (float) Instruments; + __notify_progress(pProgress, localProgress); - pInstruments->push_back(new Instrument(this, lstInstr, &subprogress)); + // divide local progress into subprogress for loading current Instrument + progress_t subprogress; + __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex); + + pInstruments->push_back(new Instrument(this, lstInstr, &subprogress)); + } else { + pInstruments->push_back(new Instrument(this, lstInstr)); + } iInstrumentIndex++; } - lstInstr = lstInstruments->GetNextSubList(); } - __notify_progress(pProgress, 1.0); // notify done + if (pProgress) + __notify_progress(pProgress, 1.0); // notify done } } @@ -3618,24 +6817,154 @@ 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; - } - } + int iWaveIndex = GetWaveTableIndexOf(pSample); 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? + uint32_t one = 1; + _3crc->WriteUint32(&one); // always 1 _3crc->WriteUint32(&crc); } + uint32_t File::GetSampleChecksum(Sample* pSample) { + // get the index of the sample + int iWaveIndex = GetWaveTableIndexOf(pSample); + if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index"); + + return GetSampleChecksumByIndex(iWaveIndex); + } + + uint32_t File::GetSampleChecksumByIndex(int index) { + if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample"); + + RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); + if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet"); + uint8_t* pData = (uint8_t*) _3crc->LoadChunkData(); + if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet"); + + // read the CRC-32 checksum directly from disk + size_t pos = index * 8; + if (pos + 8 > _3crc->GetNewSize()) + throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk"); + + uint32_t one = load32(&pData[pos]); // always 1 + if (one != 1) + throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged"); + + return load32(&pData[pos+4]); + } + + int File::GetWaveTableIndexOf(gig::Sample* pSample) { + if (!pSamples) GetSample(0); // make sure sample chunks were scanned + File::SampleList::iterator iter = pSamples->begin(); + File::SampleList::iterator end = pSamples->end(); + for (int index = 0; iter != end; ++iter, ++index) + if (*iter == pSample) + return index; + return -1; + } + + /** + * Checks whether the file's "3CRC" chunk was damaged. This chunk contains + * the CRC32 check sums of all samples' raw wave data. + * + * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged + */ + bool File::VerifySampleChecksumTable() { + RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); + if (!_3crc) return false; + if (_3crc->GetNewSize() <= 0) return false; + if (_3crc->GetNewSize() % 8) return false; + if (!pSamples) GetSample(0); // make sure sample chunks were scanned + if (_3crc->GetNewSize() != pSamples->size() * 8) return false; + + const file_offset_t n = _3crc->GetNewSize() / 8; + + uint32_t* pData = (uint32_t*) _3crc->LoadChunkData(); + if (!pData) return false; + + for (file_offset_t i = 0; i < n; ++i) { + uint32_t one = pData[i*2]; + if (one != 1) return false; + } + + return true; + } + + /** + * Recalculates CRC32 checksums for all samples and rebuilds this gig + * file's checksum table with those new checksums. This might usually + * just be necessary if the checksum table was damaged. + * + * @e IMPORTANT: The current implementation of this method only works + * with files that have not been modified since it was loaded, because + * it expects that no externally caused file structure changes are + * required! + * + * Due to the expectation above, this method is currently protected + * and actually only used by the command line tool "gigdump" yet. + * + * @returns true if Save() is required to be called after this call, + * false if no further action is required + */ + bool File::RebuildSampleChecksumTable() { + // make sure sample chunks were scanned + if (!pSamples) GetSample(0); + + bool bRequiresSave = false; + + // make sure "3CRC" chunk exists with required size + RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); + if (!_3crc) { + _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8); + // the order of einf and 3crc is not the same in v2 and v3 + RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF); + if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf); + bRequiresSave = true; + } else if (_3crc->GetNewSize() != pSamples->size() * 8) { + _3crc->Resize(pSamples->size() * 8); + bRequiresSave = true; + } + + if (bRequiresSave) { // refill CRC table for all samples in RAM ... + uint32_t* pData = (uint32_t*) _3crc->LoadChunkData(); + { + File::SampleList::iterator iter = pSamples->begin(); + File::SampleList::iterator end = pSamples->end(); + for (; iter != end; ++iter) { + gig::Sample* pSample = (gig::Sample*) *iter; + int index = GetWaveTableIndexOf(pSample); + if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved"); + pData[index*2] = 1; // always 1 + pData[index*2+1] = pSample->CalculateWaveDataChecksum(); + } + } + } else { // no file structure changes necessary, so directly write to disk and we are done ... + // make sure file is in write mode + pRIFF->SetMode(RIFF::stream_mode_read_write); + { + File::SampleList::iterator iter = pSamples->begin(); + File::SampleList::iterator end = pSamples->end(); + for (; iter != end; ++iter) { + gig::Sample* pSample = (gig::Sample*) *iter; + int index = GetWaveTableIndexOf(pSample); + if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved"); + pSample->crc = pSample->CalculateWaveDataChecksum(); + SetSampleChecksum(pSample, pSample->crc); + } + } + } + + return bRequiresSave; + } + + /** + * Returns a pointer to the first Group object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetGroup() instead. + */ Group* File::GetFirstGroup() { if (!pGroups) LoadGroups(); // there must always be at least one group @@ -3643,6 +6972,12 @@ return *GroupsIterator; } + /** + * Returns a pointer to the next Group object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetGroup() instead. + */ Group* File::GetNextGroup() { if (!pGroups) return NULL; ++GroupsIterator; @@ -3655,13 +6990,27 @@ * @param index - number of the sought group (0..n) * @returns sought group or NULL if there's no such group */ - Group* File::GetGroup(uint index) { + Group* File::GetGroup(size_t index) { if (!pGroups) LoadGroups(); - GroupsIterator = pGroups->begin(); - for (uint i = 0; GroupsIterator != pGroups->end(); i++) { - if (i == index) return *GroupsIterator; - ++GroupsIterator; - } + if (index >= pGroups->size()) return NULL; + return (*pGroups)[index]; + } + + /** + * 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(); + size_t i = 0; + for (Group* pGroup = GetGroup(i); pGroup; pGroup = GetGroup(++i)) + if (pGroup->Name == name) return pGroup; return NULL; } @@ -3685,15 +7034,18 @@ */ void File::DeleteGroup(Group* pGroup) { if (!pGroups) LoadGroups(); - std::list::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup); + std::vector::iterator iter = + find(pGroups->begin(), pGroups->end(), pGroup); if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group"); if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!"); // delete all members of this group - for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) { + Sample* pSample; + while ((pSample = pGroup->GetSample(0))) { DeleteSample(pSample); } // now delete this group object pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } @@ -3709,31 +7061,34 @@ */ void File::DeleteGroupOnly(Group* pGroup) { if (!pGroups) LoadGroups(); - std::list::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup); + std::vector::iterator iter = + find(pGroups->begin(), pGroups->end(), pGroup); if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group"); if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!"); // move all members of this group to another group pGroup->MoveAll(); pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } void File::LoadGroups() { - if (!pGroups) pGroups = new std::list; + if (!pGroups) pGroups = new std::vector; // try to read defined groups from file RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI); if (lst3gri) { RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL); if (lst3gnl) { - RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk(); - while (ck) { + size_t i = 0; + for (RIFF::Chunk* ck = lst3gnl->GetSubChunkAt(i); ck; + ck = lst3gnl->GetSubChunkAt(++i)) + { if (ck->GetChunkID() == CHUNK_ID_3GNM) { - if (pVersion && pVersion->major == 3 && + if (pVersion && pVersion->major > 2 && strcmp(static_cast(ck->LoadChunkData()), "") == 0) break; pGroups->push_back(new Group(this, ck)); } - ck = lst3gnl->GetNextSubChunk(); } } } @@ -3745,6 +7100,95 @@ } } + /** @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); + pScriptGroup->DeleteChunks(); + delete pScriptGroup; + } + + void File::LoadScriptGroups() { + if (pScriptGroups) return; + pScriptGroups = new std::list; + RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS); + if (lstLS) { + size_t i = 0; + for (RIFF::List* lst = lstLS->GetSubListAt(i); lst; + lst = lstLS->GetSubListAt(++i)) + { + 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 @@ -3753,21 +7197,51 @@ * Usually there is absolutely no need to call this method explicitly. * It will be called automatically when File::Save() was called. * + * @param pProgress - callback function for progress notification * @throws Exception - on errors */ - void File::UpdateChunks() { + void File::UpdateChunks(progress_t* pProgress) { 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) + RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS); + if (!lst3LS) { + lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS); + } + // Make sure <3LS > chunk is placed before chunk. The precise + // location of <3LS > is irrelevant, however it should be located + // before the actual wave data + RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL); + pRIFF->MoveSubChunk(lst3LS, ckPTBL); + + // 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) { + // Update instrument script (group) chunks. + for (std::list::iterator it = pScriptGroups->begin(); + it != pScriptGroups->end(); ++it) + { + (*it)->UpdateChunks(pProgress); + } + } + + // in case no libgig custom format data was added, then remove the + // custom "3LS " chunk again + if (!lst3LS->CountSubChunks()) { + pRIFF->DeleteSubChunk(lst3LS); + lst3LS = NULL; + } // first update base class's chunks - DLS::File::UpdateChunks(); + DLS::File::UpdateChunks(pProgress); if (newFile) { // INFO was added by Resource::UpdateChunks - make sure it // is placed first in file RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO); - RIFF::Chunk* first = pRIFF->GetFirstSubChunk(); + RIFF::Chunk* first = pRIFF->GetSubChunkAt(0); if (first != info) { pRIFF->MoveSubChunk(info, first); } @@ -3775,21 +7249,34 @@ // update group's chunks if (pGroups) { - std::list::iterator iter = pGroups->begin(); - std::list::iterator end = pGroups->end(); - for (; iter != end; ++iter) { - (*iter)->UpdateChunks(); + // 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 - if (pVersion && pVersion->major == 3) { - RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL); - RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk(); - for (int i = 0 ; i < 128 ; i++) { - if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); - if (_3gnm) _3gnm = _3gnl->GetNextSubChunk(); + // (before updating the Group chunks) + if (pVersion && pVersion->major > 2) { + size_t i = 0; + for (RIFF::Chunk* _3gnm = _3gnl->GetSubChunkAt(i); i < 128; + _3gnm = _3gnl->GetSubChunkAt(++i)) + { + // create 128 empty placeholder strings which will either + // be filled by Group::UpdateChunks below or left empty. + ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); } } + + std::vector::iterator iter = pGroups->begin(); + std::vector::iterator end = pGroups->end(); + for (; iter != end; ++iter) { + (*iter)->UpdateChunks(pProgress); + } } // update einf chunk @@ -3808,7 +7295,7 @@ // Note that there are several fields with unknown use. These // are set to zero. - int sublen = pSamples->size() / 8 + 49; + int sublen = int(pSamples->size() / 8 + 49); int einfSize = (Instruments + 1) * sublen; RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF); @@ -3824,9 +7311,11 @@ uint8_t* pData = (uint8_t*) einf->LoadChunkData(); std::map sampleMap; - int sampleIdx = 0; - for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { - sampleMap[pSample] = sampleIdx++; + size_t sampleIdx = 0; + for (Sample* pSample = GetSample(0); pSample; + pSample = GetSample(++sampleIdx)) + { + sampleMap[pSample] = sampleIdx; } int totnbusedsamples = 0; @@ -3838,8 +7327,10 @@ memset(&pData[48], 0, sublen - 48); - for (Instrument* instrument = GetFirstInstrument() ; instrument ; - instrument = GetNextInstrument()) { + size_t iIns = 0; + for (Instrument* instrument = GetInstrument(iIns); instrument; + instrument = GetInstrument(++iIns)) + { int nbusedsamples = 0; int nbusedchannels = 0; int nbdimregions = 0; @@ -3847,8 +7338,10 @@ memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48); - for (Region* region = instrument->GetFirstRegion() ; region ; - region = instrument->GetNextRegion()) { + size_t iRgn = 0; + for (Region* region = instrument->GetRegionAt(iRgn); region; + region = instrument->GetRegionAt(++iRgn)) + { for (int i = 0 ; i < region->DimensionRegions ; i++) { gig::DimensionRegion *d = region->pDimensionRegions[i]; if (d->pSample) { @@ -3881,7 +7374,7 @@ 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()); + store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size()); // next 4 bytes unknown totnbregions += instrument->Regions; @@ -3899,31 +7392,60 @@ store32(&pData[24], totnbloops); // next 8 bytes unknown // next 4 bytes unknown, not always 0 - store32(&pData[40], pSamples->size()); + store32(&pData[40], (uint32_t) 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. + // samples. When saving a gig file to disk, we first update the 3CRC + // chunk here (in RAM) with the old crc values which we read from the + // 3CRC chunk when we opened the file (available with gig::Sample::crc + // member variable). This step is required, because samples might have + // been deleted by the user since the file was opened, which in turn + // changes the order of the (i.e. old) checksums within the 3crc chunk. + // If a sample was conciously modified by the user (that is if + // Sample::Write() was called later on) then Sample::Write() will just + // update the respective individual checksum(s) directly on disk and + // leaves all other sample checksums untouched. RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC); if (_3crc) { _3crc->Resize(pSamples->size() * 8); - } else if (newFile) { + } 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); + if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf); + } + { // must be performed in RAM here ... + uint32_t* pData = (uint32_t*) _3crc->LoadChunkData(); + if (pData) { + File::SampleList::iterator iter = pSamples->begin(); + File::SampleList::iterator end = pSamples->end(); + for (int index = 0; iter != end; ++iter, ++index) { + gig::Sample* pSample = (gig::Sample*) *iter; + pData[index*2] = 1; // always 1 + pData[index*2+1] = pSample->crc; + } + } + } + } + + void File::UpdateFileOffsets() { + DLS::File::UpdateFileOffsets(); + + size_t i = 0; + for (Instrument* instrument = GetInstrument(i); instrument; + instrument = GetInstrument(++i)) + { + instrument->UpdateScriptFileOffsets(); } } /** - * Enable / disable automatic loading. By default this properyt is - * enabled and all informations are loaded automatically. However + * Enable / disable automatic loading. By default this property is + * enabled and every information is 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 @@ -3931,10 +7453,10 @@ * 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 + * references) and attributes 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! + * superficial information in a very fast way. Don't use it to retrieve + * details like synthesis information or even to modify .gig files! */ void File::SetAutoLoad(bool b) { bAutoLoad = b; @@ -3948,12 +7470,47 @@ return bAutoLoad; } + /** + * Returns @c true in case this gig File object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool File::UsesAnyGigFormatExtension() const { + if (!pInstruments) return false; + InstrumentList::iterator iter = pInstruments->begin(); + InstrumentList::iterator end = pInstruments->end(); + for (; iter != end; ++iter) { + Instrument* pInstrument = static_cast(*iter); + if (pInstrument->UsesAnyGigFormatExtension()) + return true; + } + return false; + } // *************** Exception *************** // * - Exception::Exception(String Message) : DLS::Exception(Message) { + Exception::Exception() : DLS::Exception() { + } + + Exception::Exception(String format, ...) : DLS::Exception() { + va_list arg; + va_start(arg, format); + Message = assemble(format, arg); + va_end(arg); + } + + Exception::Exception(String format, va_list arg) : DLS::Exception() { + Message = assemble(format, arg); } void Exception::PrintMessage() {