--- libgig/trunk/src/DLS.cpp 2007/03/18 07:13:06 1102 +++ libgig/trunk/src/DLS.cpp 2012/03/12 14:59:10 2329 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2007 by Christian Schoenebeck * + * Copyright (C) 2003-2009 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -23,8 +23,15 @@ #include "DLS.h" +#include #include +#ifdef __APPLE__ +#include +#elif defined(HAVE_UUID_UUID_H) +#include +#endif + #include "helper.h" // macros to decode connection transforms @@ -142,15 +149,15 @@ const int iEntrySize = 12; // 12 bytes per connection block pArticulationCk->Resize(HeaderSize + Connections * iEntrySize); uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData(); - memcpy(&pData[0], &HeaderSize, 2); - memcpy(&pData[2], &Connections, 2); + store16(&pData[0], HeaderSize); + store16(&pData[2], Connections); for (uint32_t i = 0; i < Connections; i++) { Connection::conn_block_t c = pConnections[i].ToConnBlock(); - memcpy(&pData[HeaderSize + i * iEntrySize], &c.source, 2); - memcpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 2); - memcpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 2); - memcpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 2); - memcpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 4); + store16(&pData[HeaderSize + i * iEntrySize], c.source); + store16(&pData[HeaderSize + i * iEntrySize + 2], c.control); + store16(&pData[HeaderSize + i * iEntrySize + 4], c.destination); + store16(&pData[HeaderSize + i * iEntrySize + 6], c.transform); + store32(&pData[HeaderSize + i * iEntrySize + 8], c.scale); } } @@ -233,7 +240,7 @@ * @param list - pointer to a list chunk which contains an INFO list chunk */ Info::Info(RIFF::List* list) { - UseFixedLengthStrings = false; + pFixedStringLengths = NULL; pResourceListChunk = list; if (list) { RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO); @@ -262,6 +269,21 @@ Info::~Info() { } + /** + * Forces specific Info fields to be of a fixed length when being saved + * to a file. By default the respective RIFF chunk of an Info field + * will have a size analogue to its actual string length. With this + * method however this behavior can be overridden, allowing to force an + * arbitrary fixed size individually for each Info field. + * + * This method is used as a workaround for the gig format, not for DLS. + * + * @param lengths - NULL terminated array of string_length_t elements + */ + void Info::SetFixedStringLengths(const string_length_t* lengths) { + pFixedStringLengths = lengths; + } + /** @brief Load given INFO field. * * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO @@ -286,12 +308,19 @@ * @param lstINFO - parent (INFO) RIFF list chunk * @param s - current value of info field * @param sDefault - default value - * @param bUseFixedLengthStrings - should a specific string size be forced in the chunk? - * @param size - wanted size of the INFO chunk. This is ignored if bUseFixedLengthStrings is false. */ - void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault, bool bUseFixedLengthStrings, int size) { + void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) { + int size = 0; + if (pFixedStringLengths) { + for (int i = 0 ; pFixedStringLengths[i].length ; i++) { + if (pFixedStringLengths[i].chunkId == ChunkID) { + size = pFixedStringLengths[i].length; + break; + } + } + } RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID); - ::SaveString(ChunkID, ck, lstINFO, s, sDefault, bUseFixedLengthStrings, size); // function from helper.h + ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h } /** @brief Update chunks with current info values. @@ -336,28 +365,23 @@ // save values - // (the string size values are for gig files; they are only - // used if UseFixedLengthStrings is set to true) - SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName, UseFixedLengthStrings, - resourceType == RIFF_TYPE_DLS ? 128 : 64); - SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""), UseFixedLengthStrings, 256); - SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate, UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments, UseFixedLengthStrings, 1024); - SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware, UseFixedLengthStrings, - resourceType == LIST_TYPE_INS ? - (Software == "" ? defaultSoftware.length() : Software.length()) : 128); - SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""), UseFixedLengthStrings, 128); - SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""), UseFixedLengthStrings, 128); + SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String("")); + SaveString(CHUNK_ID_IART, lstINFO, Artists, String("")); + SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String("")); + SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments); + SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String("")); + SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate); + SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String("")); + SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String("")); + SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String("")); + SaveString(CHUNK_ID_IMED, lstINFO, Medium, String("")); + SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName); + SaveString(CHUNK_ID_IPRD, lstINFO, Product, String("")); + SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String("")); + SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware); + SaveString(CHUNK_ID_ISRC, lstINFO, Source, String("")); + SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String("")); + SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String("")); } @@ -406,9 +430,63 @@ */ void Resource::UpdateChunks() { pInfo->UpdateChunks(); - //TODO: save DLSID + + if (pDLSID) { + // make sure 'dlid' chunk exists + RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID); + if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16); + uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData(); + // update 'dlid' chunk + store32(&pData[0], pDLSID->ulData1); + store16(&pData[4], pDLSID->usData2); + store16(&pData[6], pDLSID->usData3); + memcpy(&pData[8], pDLSID->abData, 8); + } } + /** + * Generates a new DLSID for the resource. + */ + void Resource::GenerateDLSID() { +#if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE) + + if (!pDLSID) pDLSID = new dlsid_t; + +#ifdef WIN32 + + UUID uuid; + UuidCreate(&uuid); + pDLSID->ulData1 = uuid.Data1; + pDLSID->usData2 = uuid.Data2; + pDLSID->usData3 = uuid.Data3; + memcpy(pDLSID->abData, uuid.Data4, 8); + +#elif defined(__APPLE__) + + CFUUIDRef uuidRef = CFUUIDCreate(NULL); + CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef); + CFRelease(uuidRef); + pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24; + pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8; + pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8; + pDLSID->abData[0] = uuid.byte8; + pDLSID->abData[1] = uuid.byte9; + pDLSID->abData[2] = uuid.byte10; + pDLSID->abData[3] = uuid.byte11; + pDLSID->abData[4] = uuid.byte12; + pDLSID->abData[5] = uuid.byte13; + pDLSID->abData[6] = uuid.byte14; + pDLSID->abData[7] = uuid.byte15; +#else + uuid_t uuid; + uuid_generate(uuid); + pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24; + pDLSID->usData2 = uuid[4] | uuid[5] << 8; + pDLSID->usData3 = uuid[6] | uuid[7] << 8; + memcpy(pDLSID->abData, &uuid[8], 8); +#endif +#endif + } // *************** Sampler *************** @@ -425,8 +503,8 @@ SamplerOptions = wsmp->ReadUint32(); SampleLoops = wsmp->ReadUint32(); } else { // 'wsmp' chunk missing - uiHeaderSize = 0; - UnityNote = 64; + uiHeaderSize = 20; + UnityNote = 60; FineTune = 0; // +- 0 cents Gain = 0; // 0 dB SamplerOptions = F_WSMP_NO_COMPRESSION; @@ -450,6 +528,10 @@ if (pSampleLoops) delete[] pSampleLoops; } + void Sampler::SetGain(int32_t gain) { + Gain = gain; + } + /** * Apply all sample player options to the respective RIFF chunk. You * have to call File::Save() to make changes persistent. @@ -457,28 +539,78 @@ void Sampler::UpdateChunks() { // make sure 'wsmp' chunk exists RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP); + int wsmpSize = uiHeaderSize + SampleLoops * 16; if (!wsmp) { - uiHeaderSize = 20; - wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16); + wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize); + } else if (wsmp->GetSize() != wsmpSize) { + wsmp->Resize(wsmpSize); } uint8_t* pData = (uint8_t*) wsmp->LoadChunkData(); // update headers size - memcpy(&pData[0], &uiHeaderSize, 4); + store32(&pData[0], uiHeaderSize); // update respective sampler options bits SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION : SamplerOptions & (~F_WSMP_NO_TRUNCATION); SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION : SamplerOptions & (~F_WSMP_NO_COMPRESSION); - memcpy(&pData[4], &UnityNote, 2); - memcpy(&pData[6], &FineTune, 2); - memcpy(&pData[8], &Gain, 4); - memcpy(&pData[12], &SamplerOptions, 4); - memcpy(&pData[16], &SampleLoops, 4); + store16(&pData[4], UnityNote); + store16(&pData[6], FineTune); + store32(&pData[8], Gain); + store32(&pData[12], SamplerOptions); + store32(&pData[16], SampleLoops); // update loop definitions for (uint32_t i = 0; i < SampleLoops; i++) { //FIXME: this does not handle extended loop structs correctly - memcpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4 * 4); + store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size); + store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType); + store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart); + store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength); + } + } + + /** + * Adds a new sample loop with the provided loop definition. + * + * @param pLoopDef - points to a loop definition that is to be copied + */ + void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) { + sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1]; + // copy old loops array + for (int i = 0; i < SampleLoops; i++) { + pNewLoops[i] = pSampleLoops[i]; + } + // add the new loop + pNewLoops[SampleLoops] = *pLoopDef; + // auto correct size field + pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t); + // free the old array and update the member variables + if (SampleLoops) delete[] pSampleLoops; + pSampleLoops = pNewLoops; + SampleLoops++; + } + + /** + * Deletes an existing sample loop. + * + * @param pLoopDef - pointer to existing loop definition + * @throws Exception - if given loop definition does not exist + */ + void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) { + sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1]; + // copy old loops array (skipping given loop) + for (int i = 0, o = 0; i < SampleLoops; i++) { + if (&pSampleLoops[i] == pLoopDef) continue; + if (o == SampleLoops - 1) { + delete[] pNewLoops; + throw Exception("Could not delete Sample Loop, because it does not exist"); + } + pNewLoops[o] = pSampleLoops[i]; + o++; } + // free the old array and update the member variables + if (SampleLoops) delete[] pSampleLoops; + pSampleLoops = pNewLoops; + SampleLoops--; } @@ -716,12 +848,12 @@ if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData(); // update 'fmt' chunk - memcpy(&pData[0], &FormatTag, 2); - memcpy(&pData[2], &Channels, 2); - memcpy(&pData[4], &SamplesPerSecond, 4); - memcpy(&pData[8], &AverageBytesPerSecond, 4); - memcpy(&pData[12], &BlockAlign, 2); - memcpy(&pData[14], &BitDepth, 2); // assuming PCM format + store16(&pData[0], FormatTag); + store16(&pData[2], Channels); + store32(&pData[4], SamplesPerSecond); + store32(&pData[8], AverageBytesPerSecond); + store16(&pData[12], BlockAlign); + store16(&pData[14], BitDepth); // assuming PCM format } @@ -805,6 +937,41 @@ } /** + * Modifies the key range of this Region and makes sure the respective + * chunks are in correct order. + * + * @param Low - lower end of key range + * @param High - upper end of key range + */ + void Region::SetKeyRange(uint16_t Low, uint16_t High) { + KeyRange.low = Low; + KeyRange.high = High; + + // make sure regions are already loaded + Instrument* pInstrument = (Instrument*) GetParent(); + if (!pInstrument->pRegions) pInstrument->LoadRegions(); + if (!pInstrument->pRegions) return; + + // find the r which is the first one to the right of this region + // at its new position + Region* r = NULL; + Region* prev_region = NULL; + for ( + Instrument::RegionList::iterator iter = pInstrument->pRegions->begin(); + iter != pInstrument->pRegions->end(); iter++ + ) { + if ((*iter)->KeyRange.low > this->KeyRange.low) { + r = *iter; + break; + } + prev_region = *iter; + } + + // place this region before r if it's not already there + if (prev_region != this) pInstrument->MoveRegion(this, r); + } + + /** * Apply Region settings to the respective RIFF chunks. You have to * call File::Save() to make changes persistent. * @@ -819,11 +986,13 @@ ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE); // update 'rgnh' chunk - memcpy(&pData[0], &KeyRange, 2 * 2); - memcpy(&pData[4], &VelocityRange, 2 * 2); - memcpy(&pData[8], &FormatOptionFlags, 2); - memcpy(&pData[10], &KeyGroup, 2); - if (rgnh->GetSize() >= 14) memcpy(&pData[12], &Layer, 2); + store16(&pData[0], KeyRange.low); + store16(&pData[2], KeyRange.high); + store16(&pData[4], VelocityRange.low); + store16(&pData[6], VelocityRange.high); + store16(&pData[8], FormatOptionFlags); + store16(&pData[10], KeyGroup); + if (rgnh->GetSize() >= 14) store16(&pData[12], Layer); // update chunks of base classes as well (but skip Resource, // as a rgn doesn't seem to have dlid and INFO chunks) @@ -853,13 +1022,12 @@ } } } - if (index < 0) throw Exception("Could not save Region, could not find Region's sample"); WavePoolTableIndex = index; // update 'wlnk' chunk - memcpy(&pData[0], &WaveLinkOptionFlags, 2); - memcpy(&pData[2], &PhaseGroup, 2); - memcpy(&pData[4], &Channel, 4); - memcpy(&pData[8], &WavePoolTableIndex, 4); + store16(&pData[0], WaveLinkOptionFlags); + store16(&pData[2], PhaseGroup); + store32(&pData[4], Channel); + store32(&pData[8], WavePoolTableIndex); } @@ -981,8 +1149,9 @@ locale.bank = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine); locale.bank = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK); MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it - memcpy(&pData[0], &Regions, 4); - memcpy(&pData[4], &locale, 2 * 4); + store32(&pData[0], Regions); + store32(&pData[4], locale.bank); + store32(&pData[8], locale.instrument); // update Region's chunks if (!pRegions) return; RegionList::iterator iter = pRegions->begin(); @@ -1024,6 +1193,7 @@ * a DLS file. */ File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) { + pRIFF->SetByteOrder(RIFF::endian_little); pVersion = new version_t; pVersion->major = 0; pVersion->minor = 0; @@ -1263,6 +1433,39 @@ } /** + * Returns extension file of given index. Extension files are used + * sometimes to circumvent the 2 GB file size limit of the RIFF format and + * of certain operating systems in general. In this case, instead of just + * using one file, the content is spread among several files with similar + * file name scheme. This is especially used by some GigaStudio sound + * libraries. + * + * @param index - index of extension file + * @returns sought extension file, NULL if index out of bounds + * @see GetFileName() + */ + RIFF::File* File::GetExtensionFile(int index) { + if (index < 0 || index >= ExtensionFiles.size()) return NULL; + std::list::iterator iter = ExtensionFiles.begin(); + for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i) + if (i == index) return *iter; + return NULL; + } + + /** @brief File name of this DLS file. + * + * This method returns the file name as it was provided when loading + * the respective DLS file. However in case the File object associates + * an empty, that is new DLS file, which was not yet saved to disk, + * this method will return an empty string. + * + * @see GetExtensionFile() + */ + String File::GetFileName() { + return pRIFF->GetFileName(); + } + + /** * Apply all the DLS file's current instruments, samples and settings to * the respective RIFF chunks. You have to call Save() to make changes * persistent. @@ -1278,7 +1481,10 @@ RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS); if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8); uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData(); - memcpy(pData, pVersion, 2 * 4); + store16(&pData[0], pVersion->minor); + store16(&pData[2], pVersion->major); + store16(&pData[4], pVersion->build); + store16(&pData[6], pVersion->release); } // update 'colh' chunk @@ -1286,7 +1492,7 @@ RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH); if (!colh) colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4); uint8_t* pData = (uint8_t*) colh->LoadChunkData(); - memcpy(pData, &Instruments, 4); + store32(pData, Instruments); // update instrument's chunks if (pInstruments) { @@ -1306,7 +1512,7 @@ ptbl->Resize(iPtblSize); pData = (uint8_t*) ptbl->LoadChunkData(); WavePoolCount = iSamples; - memcpy(&pData[4], &WavePoolCount, 4); + store32(&pData[4], WavePoolCount); // we actually update the sample offsets in the pool table when we Save() memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize); @@ -1395,18 +1601,24 @@ unsigned long ulOriginalPos = ptbl->GetPos(); // update headers ptbl->SetPos(0); - ptbl->WriteUint32(&WavePoolHeaderSize); - ptbl->WriteUint32(&WavePoolCount); + uint32_t tmp = WavePoolHeaderSize; + ptbl->WriteUint32(&tmp); + tmp = WavePoolCount; + ptbl->WriteUint32(&tmp); // update offsets ptbl->SetPos(WavePoolHeaderSize); if (b64BitWavePoolOffsets) { for (int i = 0 ; i < WavePoolCount ; i++) { - ptbl->WriteUint32(&pWavePoolTableHi[i]); - ptbl->WriteUint32(&pWavePoolTable[i]); + tmp = pWavePoolTableHi[i]; + ptbl->WriteUint32(&tmp); + tmp = pWavePoolTable[i]; + ptbl->WriteUint32(&tmp); } } else { // conventional 32 bit offsets - for (int i = 0 ; i < WavePoolCount ; i++) - ptbl->WriteUint32(&pWavePoolTable[i]); + for (int i = 0 ; i < WavePoolCount ; i++) { + tmp = pWavePoolTable[i]; + ptbl->WriteUint32(&tmp); + } } // restore 'ptbl' chunk's original read/write position ptbl->SetPos(ulOriginalPos);