/[svn]/libgig/trunk/src/DLS.cpp
ViewVC logotype

Annotation of /libgig/trunk/src/DLS.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 834 - (hide annotations) (download)
Mon Feb 6 17:58:21 2006 UTC (18 years, 1 month ago) by persson
File size: 59710 byte(s)
* fixed some memory management errors, one of them was causing a crash
  when a multi-file gig was deallocated

1 schoenebeck 2 /***************************************************************************
2     * *
3     * libgig - C++ cross-platform Gigasampler format file loader library *
4     * *
5 schoenebeck 384 * Copyright (C) 2003-2005 by Christian Schoenebeck *
6     * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8     * This library is free software; you can redistribute it and/or modify *
9     * it under the terms of the GNU General Public License as published by *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This library is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this library; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include "DLS.h"
25    
26 schoenebeck 800 #include <time.h>
27    
28     #include "helper.h"
29    
30     // macros to decode connection transforms
31     #define CONN_TRANSFORM_SRC(x) ((x >> 10) & 0x000F)
32     #define CONN_TRANSFORM_CTL(x) ((x >> 4) & 0x000F)
33     #define CONN_TRANSFORM_DST(x) (x & 0x000F)
34     #define CONN_TRANSFORM_BIPOLAR_SRC(x) (x & 0x4000)
35     #define CONN_TRANSFORM_BIPOLAR_CTL(x) (x & 0x0100)
36     #define CONN_TRANSFORM_INVERT_SRC(x) (x & 0x8000)
37     #define CONN_TRANSFORM_INVERT_CTL(x) (x & 0x0200)
38    
39     // macros to encode connection transforms
40     #define CONN_TRANSFORM_SRC_ENCODE(x) ((x & 0x000F) << 10)
41     #define CONN_TRANSFORM_CTL_ENCODE(x) ((x & 0x000F) << 4)
42     #define CONN_TRANSFORM_DST_ENCODE(x) (x & 0x000F)
43     #define CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(x) ((x) ? 0x4000 : 0)
44     #define CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(x) ((x) ? 0x0100 : 0)
45     #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x) ((x) ? 0x8000 : 0)
46     #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x) ((x) ? 0x0200 : 0)
47    
48     #define DRUM_TYPE_MASK 0x00000001
49    
50     #define F_RGN_OPTION_SELFNONEXCLUSIVE 0x0001
51    
52     #define F_WAVELINK_PHASE_MASTER 0x0001
53     #define F_WAVELINK_MULTICHANNEL 0x0002
54    
55     #define F_WSMP_NO_TRUNCATION 0x0001
56     #define F_WSMP_NO_COMPRESSION 0x0002
57    
58     #define MIDI_BANK_COARSE(x) ((x & 0x00007F00) >> 8) // CC0
59     #define MIDI_BANK_FINE(x) (x & 0x0000007F) // CC32
60     #define MIDI_BANK_MERGE(coarse, fine) ((((uint16_t) coarse) << 7) | fine) // CC0 + CC32
61     #define MIDI_BANK_ENCODE(coarse, fine) (((coarse & 0x0000007F) << 8) | (fine & 0x0000007F))
62    
63 schoenebeck 2 namespace DLS {
64    
65     // *************** Connection ***************
66     // *
67    
68     void Connection::Init(conn_block_t* Header) {
69     Source = (conn_src_t) Header->source;
70     Control = (conn_src_t) Header->control;
71     Destination = (conn_dst_t) Header->destination;
72     Scale = Header->scale;
73     SourceTransform = (conn_trn_t) CONN_TRANSFORM_SRC(Header->transform);
74     ControlTransform = (conn_trn_t) CONN_TRANSFORM_CTL(Header->transform);
75     DestinationTransform = (conn_trn_t) CONN_TRANSFORM_DST(Header->transform);
76     SourceInvert = CONN_TRANSFORM_INVERT_SRC(Header->transform);
77     SourceBipolar = CONN_TRANSFORM_BIPOLAR_SRC(Header->transform);
78     ControlInvert = CONN_TRANSFORM_INVERT_CTL(Header->transform);
79     ControlBipolar = CONN_TRANSFORM_BIPOLAR_CTL(Header->transform);
80     }
81    
82 schoenebeck 800 Connection::conn_block_t Connection::ToConnBlock() {
83     conn_block_t c;
84     c.source = Source;
85     c.control = Control;
86     c.destination = Destination;
87     c.scale = Scale;
88     c.transform = CONN_TRANSFORM_SRC_ENCODE(SourceTransform) |
89     CONN_TRANSFORM_CTL_ENCODE(ControlTransform) |
90     CONN_TRANSFORM_DST_ENCODE(DestinationTransform) |
91     CONN_TRANSFORM_INVERT_SRC_ENCODE(SourceInvert) |
92     CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(SourceBipolar) |
93     CONN_TRANSFORM_INVERT_CTL_ENCODE(ControlInvert) |
94     CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(ControlBipolar);
95     return c;
96     }
97 schoenebeck 2
98    
99 schoenebeck 800
100 schoenebeck 2 // *************** Articulation ***************
101     // *
102    
103 schoenebeck 800 /** @brief Constructor.
104     *
105     * Expects an 'artl' or 'art2' chunk to be given where the articulation
106     * connections will be read from.
107     *
108     * @param artl - pointer to an 'artl' or 'art2' chunk
109     * @throws Exception if no 'artl' or 'art2' chunk was given
110     */
111     Articulation::Articulation(RIFF::Chunk* artl) {
112     pArticulationCk = artl;
113     if (artl->GetChunkID() != CHUNK_ID_ART2 &&
114     artl->GetChunkID() != CHUNK_ID_ARTL) {
115     throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
116 schoenebeck 2 }
117 schoenebeck 800 HeaderSize = artl->ReadUint32();
118     Connections = artl->ReadUint32();
119     artl->SetPos(HeaderSize);
120 schoenebeck 2
121     pConnections = new Connection[Connections];
122     Connection::conn_block_t connblock;
123 schoenebeck 800 for (uint32_t i = 0; i < Connections; i++) {
124     artl->Read(&connblock.source, 1, 2);
125     artl->Read(&connblock.control, 1, 2);
126     artl->Read(&connblock.destination, 1, 2);
127     artl->Read(&connblock.transform, 1, 2);
128     artl->Read(&connblock.scale, 1, 4);
129 schoenebeck 2 pConnections[i].Init(&connblock);
130     }
131     }
132    
133     Articulation::~Articulation() {
134     if (pConnections) delete[] pConnections;
135     }
136    
137 schoenebeck 800 /**
138     * Apply articulation connections to the respective RIFF chunks. You
139     * have to call File::Save() to make changes persistent.
140     */
141     void Articulation::UpdateChunks() {
142     const int iEntrySize = 12; // 12 bytes per connection block
143     pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
144     uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
145     memccpy(&pData[0], &HeaderSize, 1, 2);
146     memccpy(&pData[2], &Connections, 1, 2);
147     for (uint32_t i = 0; i < Connections; i++) {
148     Connection::conn_block_t c = pConnections[i].ToConnBlock();
149     memccpy(&pData[HeaderSize + i * iEntrySize], &c.source, 1, 2);
150     memccpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 1, 2);
151     memccpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 1, 2);
152     memccpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 1, 2);
153     memccpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 1, 4);
154     }
155     }
156 schoenebeck 2
157    
158 schoenebeck 800
159 schoenebeck 2 // *************** Articulator ***************
160     // *
161    
162     Articulator::Articulator(RIFF::List* ParentList) {
163     pParentList = ParentList;
164     pArticulations = NULL;
165     }
166    
167     Articulation* Articulator::GetFirstArticulation() {
168     if (!pArticulations) LoadArticulations();
169     if (!pArticulations) return NULL;
170     ArticulationsIterator = pArticulations->begin();
171     return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
172     }
173    
174     Articulation* Articulator::GetNextArticulation() {
175     if (!pArticulations) return NULL;
176     ArticulationsIterator++;
177     return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
178     }
179    
180     void Articulator::LoadArticulations() {
181     // prefer articulation level 2
182     RIFF::List* lart = pParentList->GetSubList(LIST_TYPE_LAR2);
183     if (!lart) lart = pParentList->GetSubList(LIST_TYPE_LART);
184     if (lart) {
185 schoenebeck 800 uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2
186     : CHUNK_ID_ARTL;
187     RIFF::Chunk* art = lart->GetFirstSubChunk();
188 schoenebeck 2 while (art) {
189 schoenebeck 800 if (art->GetChunkID() == artCkType) {
190 schoenebeck 2 if (!pArticulations) pArticulations = new ArticulationList;
191     pArticulations->push_back(new Articulation(art));
192     }
193 schoenebeck 800 art = lart->GetNextSubChunk();
194 schoenebeck 2 }
195     }
196     }
197    
198     Articulator::~Articulator() {
199     if (pArticulations) {
200     ArticulationList::iterator iter = pArticulations->begin();
201     ArticulationList::iterator end = pArticulations->end();
202     while (iter != end) {
203     delete *iter;
204     iter++;
205     }
206     delete pArticulations;
207     }
208     }
209    
210 schoenebeck 800 /**
211     * Apply all articulations to the respective RIFF chunks. You have to
212     * call File::Save() to make changes persistent.
213     */
214     void Articulator::UpdateChunks() {
215 schoenebeck 804 if (pArticulations) {
216     ArticulationList::iterator iter = pArticulations->begin();
217     ArticulationList::iterator end = pArticulations->end();
218     for (; iter != end; ++iter) {
219     (*iter)->UpdateChunks();
220     }
221 schoenebeck 800 }
222     }
223 schoenebeck 2
224    
225 schoenebeck 800
226 schoenebeck 2 // *************** Info ***************
227     // *
228    
229 schoenebeck 800 /** @brief Constructor.
230     *
231     * Initializes the info strings with values provided by a INFO list chunk.
232     *
233     * @param list - pointer to a list chunk which contains a INFO list chunk
234     */
235 schoenebeck 2 Info::Info(RIFF::List* list) {
236 schoenebeck 800 pResourceListChunk = list;
237 schoenebeck 2 if (list) {
238     RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
239     if (lstINFO) {
240     LoadString(CHUNK_ID_INAM, lstINFO, Name);
241     LoadString(CHUNK_ID_IARL, lstINFO, ArchivalLocation);
242     LoadString(CHUNK_ID_ICRD, lstINFO, CreationDate);
243     LoadString(CHUNK_ID_ICMT, lstINFO, Comments);
244     LoadString(CHUNK_ID_IPRD, lstINFO, Product);
245     LoadString(CHUNK_ID_ICOP, lstINFO, Copyright);
246     LoadString(CHUNK_ID_IART, lstINFO, Artists);
247     LoadString(CHUNK_ID_IGNR, lstINFO, Genre);
248     LoadString(CHUNK_ID_IKEY, lstINFO, Keywords);
249     LoadString(CHUNK_ID_IENG, lstINFO, Engineer);
250     LoadString(CHUNK_ID_ITCH, lstINFO, Technician);
251     LoadString(CHUNK_ID_ISFT, lstINFO, Software);
252     LoadString(CHUNK_ID_IMED, lstINFO, Medium);
253     LoadString(CHUNK_ID_ISRC, lstINFO, Source);
254     LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
255     LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
256     }
257     }
258     }
259    
260 schoenebeck 823 Info::~Info() {
261     }
262    
263 schoenebeck 800 /** @brief Load given INFO field.
264     *
265     * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO
266     * list chunk \a lstINFO and save value to \a s.
267     */
268     void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
269     RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
270     if (ck) {
271     // TODO: no check for ZSTR terminated strings yet
272 persson 834 s.assign((char*) ck->LoadChunkData(), ck->GetSize());
273 schoenebeck 800 ck->ReleaseChunkData();
274     }
275     }
276 schoenebeck 2
277 schoenebeck 800 /** @brief Apply given INFO field to the respective chunk.
278     *
279     * Apply given info value to info chunk with ID \a ChunkID, which is a
280     * subchunk of INFO list chunk \a lstINFO. If the given chunk already
281 schoenebeck 804 * exists, value \a s will be applied. Otherwise if it doesn't exist yet
282     * and either \a s or \a sDefault is not an empty string, such a chunk
283     * will be created and either \a s or \a sDefault will be applied
284     * (depending on which one is not an empty string, if both are not an
285     * empty string \a s will be preferred).
286 schoenebeck 800 *
287     * @param ChunkID - 32 bit RIFF chunk ID of INFO subchunk
288     * @param lstINFO - parent (INFO) RIFF list chunk
289     * @param s - current value of info field
290     * @param sDefault - default value
291     */
292     void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
293     RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
294     if (ck) { // if chunk exists already, use 's' as value
295     ck->Resize(s.size() + 1);
296     char* pData = (char*) ck->LoadChunkData();
297     memcpy(pData, s.c_str(), s.size() + 1);
298 schoenebeck 804 } else if (s != "" || sDefault != "") { // create chunk
299     const String& sToSave = (s != "") ? s : sDefault;
300     ck = lstINFO->AddSubChunk(ChunkID, sToSave.size() + 1);
301 schoenebeck 800 char* pData = (char*) ck->LoadChunkData();
302 schoenebeck 804 memcpy(pData, sToSave.c_str(), sToSave.size() + 1);
303 schoenebeck 800 }
304     }
305 schoenebeck 2
306 schoenebeck 800 /** @brief Update chunks with current info values.
307     *
308     * Apply current INFO field values to the respective INFO chunks. You
309     * have to call File::Save() to make changes persistent.
310     */
311     void Info::UpdateChunks() {
312     if (!pResourceListChunk) return;
313    
314     // make sure INFO list chunk exists
315     RIFF::List* lstINFO = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
316     if (!lstINFO) lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
317    
318     // assemble default values in case the respective chunk is missing yet
319     String defaultName = "NONAME";
320     // get current date
321     time_t now = time(NULL);
322     tm* pNowBroken = localtime(&now);
323 schoenebeck 804 String defaultCreationDate = ToString(1900 + pNowBroken->tm_year) + "-" +
324     ToString(pNowBroken->tm_mon + 1) + "-" +
325 schoenebeck 800 ToString(pNowBroken->tm_mday);
326     String defaultSoftware = libraryName() + " " + libraryVersion();
327     String defaultComments = "Created with " + libraryName() + " " + libraryVersion();
328    
329     // save values
330     SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
331     SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
332     SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
333     SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
334     SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
335     SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
336     SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
337     SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
338     SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
339     SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
340     SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
341     SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
342     SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
343     SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
344     SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
345     SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
346     }
347    
348    
349    
350 schoenebeck 2 // *************** Resource ***************
351     // *
352    
353 schoenebeck 800 /** @brief Constructor.
354     *
355     * Initializes the 'Resource' object with values provided by a given
356     * INFO list chunk and a DLID chunk (the latter optional).
357     *
358     * @param Parent - pointer to parent 'Resource', NULL if this is
359     * the toplevel 'Resource' object
360     * @param lstResource - pointer to an INFO list chunk
361     */
362 schoenebeck 2 Resource::Resource(Resource* Parent, RIFF::List* lstResource) {
363     pParent = Parent;
364 schoenebeck 800 pResourceList = lstResource;
365 schoenebeck 2
366     pInfo = new Info(lstResource);
367    
368     RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
369     if (ckDLSID) {
370     pDLSID = new dlsid_t;
371 schoenebeck 11 ckDLSID->Read(&pDLSID->ulData1, 1, 4);
372     ckDLSID->Read(&pDLSID->usData2, 1, 2);
373     ckDLSID->Read(&pDLSID->usData3, 1, 2);
374     ckDLSID->Read(pDLSID->abData, 8, 1);
375 schoenebeck 2 }
376     else pDLSID = NULL;
377     }
378    
379     Resource::~Resource() {
380     if (pDLSID) delete pDLSID;
381     if (pInfo) delete pInfo;
382     }
383    
384 schoenebeck 800 /** @brief Update chunks with current Resource data.
385     *
386     * Apply Resource data persistently below the previously given resource
387     * list chunk. This will currently only include the INFO data. The DLSID
388     * will not be applied at the moment (yet).
389     *
390     * You have to call File::Save() to make changes persistent.
391     */
392     void Resource::UpdateChunks() {
393     pInfo->UpdateChunks();
394     //TODO: save DLSID
395     }
396 schoenebeck 2
397    
398 schoenebeck 800
399 schoenebeck 2 // *************** Sampler ***************
400     // *
401    
402     Sampler::Sampler(RIFF::List* ParentList) {
403 schoenebeck 800 pParentList = ParentList;
404 schoenebeck 2 RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
405 schoenebeck 800 if (wsmp) {
406     uiHeaderSize = wsmp->ReadUint32();
407     UnityNote = wsmp->ReadUint16();
408     FineTune = wsmp->ReadInt16();
409     Gain = wsmp->ReadInt32();
410     SamplerOptions = wsmp->ReadUint32();
411     SampleLoops = wsmp->ReadUint32();
412     } else { // 'wsmp' chunk missing
413     uiHeaderSize = 0;
414     UnityNote = 64;
415     FineTune = 0; // +- 0 cents
416     Gain = 0; // 0 dB
417     SamplerOptions = F_WSMP_NO_COMPRESSION;
418     SampleLoops = 0;
419     }
420 schoenebeck 2 NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;
421     NoSampleCompression = SamplerOptions & F_WSMP_NO_COMPRESSION;
422     pSampleLoops = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;
423 schoenebeck 800 if (SampleLoops) {
424     wsmp->SetPos(uiHeaderSize);
425     for (uint32_t i = 0; i < SampleLoops; i++) {
426     wsmp->Read(pSampleLoops + i, 4, 4);
427     if (pSampleLoops[i].Size > sizeof(sample_loop_t)) { // if loop struct was extended
428     wsmp->SetPos(pSampleLoops[i].Size - sizeof(sample_loop_t), RIFF::stream_curpos);
429     }
430 schoenebeck 2 }
431     }
432     }
433    
434     Sampler::~Sampler() {
435     if (pSampleLoops) delete[] pSampleLoops;
436     }
437    
438 schoenebeck 800 /**
439     * Apply all sample player options to the respective RIFF chunk. You
440     * have to call File::Save() to make changes persistent.
441     */
442     void Sampler::UpdateChunks() {
443     // make sure 'wsmp' chunk exists
444     RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
445     if (!wsmp) {
446     uiHeaderSize = 20;
447     wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);
448     }
449     uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
450     // update headers size
451     memccpy(&pData[0], &uiHeaderSize, 1, 4);
452     // update respective sampler options bits
453     SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
454     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
455     SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
456     : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
457     // update loop definitions
458     for (uint32_t i = 0; i < SampleLoops; i++) {
459     //FIXME: this does not handle extended loop structs correctly
460     memccpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4, 4);
461     }
462     }
463 schoenebeck 2
464    
465 schoenebeck 800
466 schoenebeck 2 // *************** Sample ***************
467     // *
468    
469 schoenebeck 800 /** @brief Constructor.
470     *
471     * Load an existing sample or create a new one. A 'wave' list chunk must
472     * be given to this constructor. In case the given 'wave' list chunk
473     * contains a 'fmt' and 'data' chunk, the format and sample data will be
474     * loaded from there, otherwise default values will be used and those
475     * chunks will be created when File::Save() will be called later on.
476     *
477     * @param pFile - pointer to DLS::File where this sample is
478     * located (or will be located)
479     * @param waveList - pointer to 'wave' list chunk which is (or
480     * will be) associated with this sample
481     * @param WavePoolOffset - offset of this sample data from wave pool
482     * ('wvpl') list chunk
483     */
484 schoenebeck 2 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : Resource(pFile, waveList) {
485 schoenebeck 800 pWaveList = waveList;
486 schoenebeck 2 ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;
487     pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
488     pCkData = waveList->GetSubChunk(CHUNK_ID_DATA);
489 schoenebeck 800 if (pCkFormat) {
490     // common fields
491     FormatTag = pCkFormat->ReadUint16();
492     Channels = pCkFormat->ReadUint16();
493     SamplesPerSecond = pCkFormat->ReadUint32();
494     AverageBytesPerSecond = pCkFormat->ReadUint32();
495     BlockAlign = pCkFormat->ReadUint16();
496     // PCM format specific
497     if (FormatTag == WAVE_FORMAT_PCM) {
498     BitDepth = pCkFormat->ReadUint16();
499     FrameSize = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels
500     : 0;
501     } else { // unsupported sample data format
502     BitDepth = 0;
503     FrameSize = 0;
504     }
505     } else { // 'fmt' chunk missing
506     FormatTag = WAVE_FORMAT_PCM;
507     BitDepth = 16;
508     Channels = 1;
509     SamplesPerSecond = 44100;
510     AverageBytesPerSecond = (BitDepth / 8) * SamplesPerSecond * Channels;
511     FrameSize = (BitDepth / 8) * Channels;
512     BlockAlign = FrameSize;
513 schoenebeck 2 }
514 schoenebeck 800 SamplesTotal = (pCkData) ? (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
515     : 0
516     : 0;
517 schoenebeck 2 }
518    
519 schoenebeck 800 /** @brief Destructor.
520     *
521     * Removes RIFF chunks associated with this Sample and frees all
522     * memory occupied by this sample.
523     */
524     Sample::~Sample() {
525     RIFF::List* pParent = pWaveList->GetParent();
526     pParent->DeleteSubChunk(pWaveList);
527     }
528    
529     /** @brief Load sample data into RAM.
530     *
531     * In case the respective 'data' chunk exists, the sample data will be
532     * loaded into RAM (if not done already) and a pointer to the data in
533     * RAM will be returned. If this is a new sample, you have to call
534     * Resize() with the desired sample size to create the mandatory RIFF
535     * chunk for the sample wave data.
536     *
537     * You can call LoadChunkData() again if you previously scheduled to
538     * enlarge the sample data RIFF chunk with a Resize() call. In that case
539     * the buffer will be enlarged to the new, scheduled size and you can
540     * already place the sample wave data to the buffer and finally call
541     * File::Save() to enlarge the sample data's chunk physically and write
542     * the new sample wave data in one rush. This approach is definitely
543     * recommended if you have to enlarge and write new sample data to a lot
544     * of samples.
545     *
546     * <b>Caution:</b> the buffer pointer will be invalidated once
547     * File::Save() was called. You have to call LoadChunkData() again to
548     * get a new, valid pointer whenever File::Save() was called.
549     *
550     * @returns pointer to sample data in RAM, NULL in case respective
551     * 'data' chunk does not exist (yet)
552     * @throws Exception if data buffer could not be enlarged
553     * @see Resize(), File::Save()
554     */
555 schoenebeck 2 void* Sample::LoadSampleData() {
556 schoenebeck 800 return (pCkData) ? pCkData->LoadChunkData() : NULL;
557 schoenebeck 2 }
558    
559 schoenebeck 800 /** @brief Free sample data from RAM.
560     *
561     * In case sample data was previously successfully loaded into RAM with
562     * LoadSampleData(), this method will free the sample data from RAM.
563     */
564 schoenebeck 2 void Sample::ReleaseSampleData() {
565 schoenebeck 800 if (pCkData) pCkData->ReleaseChunkData();
566 schoenebeck 2 }
567    
568 schoenebeck 800 /** @brief Returns sample size.
569     *
570     * Returns the sample wave form's data size (in sample points). This is
571     * actually the current, physical size (converted to sample points) of
572     * the RIFF chunk which encapsulates the sample's wave data. The
573     * returned value is dependant to the current FrameSize value.
574     *
575     * @returns number of sample points or 0 if FormatTag != WAVE_FORMAT_PCM
576     * @see FrameSize, FormatTag
577     */
578     unsigned long Sample::GetSize() {
579     if (FormatTag != WAVE_FORMAT_PCM) return 0;
580     return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
581     }
582    
583     /** @brief Resize sample.
584     *
585     * Resizes the sample's wave form data, that is the actual size of
586     * sample wave data possible to be written for this sample. This call
587     * will return immediately and just schedule the resize operation. You
588     * should call File::Save() to actually perform the resize operation(s)
589     * "physically" to the file. As this can take a while on large files, it
590     * is recommended to call Resize() first on all samples which have to be
591     * resized and finally to call File::Save() to perform all those resize
592     * operations in one rush.
593     *
594     * The actual size (in bytes) is dependant to the current FrameSize
595     * value. You may want to set FrameSize before calling Resize().
596     *
597     * <b>Caution:</b> You cannot directly write to enlarged samples before
598     * calling File::Save() as this might exceed the current sample's
599     * boundary!
600     *
601     * Also note: only WAVE_FORMAT_PCM is currently supported, that is
602     * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
603     * other formats will fail!
604     *
605     * @param iNewSize - new sample wave data size in sample points (must be
606     * greater than zero)
607     * @throws Excecption if FormatTag != WAVE_FORMAT_PCM
608     * @throws Exception if \a iNewSize is less than 1
609     * @see File::Save(), FrameSize, FormatTag
610     */
611     void Sample::Resize(int iNewSize) {
612     if (FormatTag != WAVE_FORMAT_PCM) throw Exception("Sample's format is not WAVE_FORMAT_PCM");
613     if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");
614     const int iSizeInBytes = iNewSize * FrameSize;
615     pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
616     if (pCkData) pCkData->Resize(iSizeInBytes);
617     else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);
618     }
619    
620 schoenebeck 2 /**
621     * Sets the position within the sample (in sample points, not in
622     * bytes). Use this method and <i>Read()</i> if you don't want to load
623     * the sample into RAM, thus for disk streaming.
624     *
625 schoenebeck 800 * Also note: only WAVE_FORMAT_PCM is currently supported, that is
626     * FormatTag must be WAVE_FORMAT_PCM. Trying to reposition the sample
627     * with other formats will fail!
628     *
629 schoenebeck 2 * @param SampleCount number of sample points
630     * @param Whence to which relation \a SampleCount refers to
631 schoenebeck 800 * @returns new position within the sample, 0 if
632     * FormatTag != WAVE_FORMAT_PCM
633     * @throws Exception if no data RIFF chunk was created for the sample yet
634     * @see FrameSize, FormatTag
635 schoenebeck 2 */
636     unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
637     if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
638 schoenebeck 800 if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
639 schoenebeck 2 unsigned long orderedBytes = SampleCount * FrameSize;
640     unsigned long result = pCkData->SetPos(orderedBytes, Whence);
641     return (result == orderedBytes) ? SampleCount
642     : result / FrameSize;
643     }
644    
645     /**
646     * Reads \a SampleCount number of sample points from the current
647     * position into the buffer pointed by \a pBuffer and increments the
648     * position within the sample. Use this method and <i>SetPos()</i> if you
649     * don't want to load the sample into RAM, thus for disk streaming.
650     *
651     * @param pBuffer destination buffer
652     * @param SampleCount number of sample points to read
653     */
654     unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
655     if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
656 schoenebeck 11 return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
657 schoenebeck 2 }
658    
659 schoenebeck 800 /** @brief Write sample wave data.
660     *
661     * Writes \a SampleCount number of sample points from the buffer pointed
662     * by \a pBuffer and increments the position within the sample. Use this
663     * method to directly write the sample data to disk, i.e. if you don't
664     * want or cannot load the whole sample data into RAM.
665     *
666     * You have to Resize() the sample to the desired size and call
667     * File::Save() <b>before</b> using Write().
668     *
669     * @param pBuffer - source buffer
670     * @param SampleCount - number of sample points to write
671     * @throws Exception if current sample size is too small
672     * @see LoadSampleData()
673     */
674     unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
675     if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
676     if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
677     return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
678     }
679 schoenebeck 2
680 schoenebeck 800 /**
681     * Apply sample and its settings to the respective RIFF chunks. You have
682     * to call File::Save() to make changes persistent.
683     *
684     * @throws Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
685     * was provided yet
686     */
687     void Sample::UpdateChunks() {
688     if (FormatTag != WAVE_FORMAT_PCM)
689     throw Exception("Could not save sample, only PCM format is supported");
690     // we refuse to do anything if not sample wave form was provided yet
691     if (!pCkData)
692     throw Exception("Could not save sample, there is no sample data to save");
693     // update chunks of base class as well
694     Resource::UpdateChunks();
695     // make sure 'fmt' chunk exists
696     RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
697     if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
698     uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
699     // update 'fmt' chunk
700     memccpy(&pData[0], &FormatTag, 1, 2);
701     memccpy(&pData[2], &Channels, 1, 2);
702     memccpy(&pData[4], &SamplesPerSecond, 1, 4);
703     memccpy(&pData[8], &AverageBytesPerSecond, 1, 4);
704     memccpy(&pData[12], &BlockAlign, 1, 2);
705     memccpy(&pData[14], &BitDepth, 1, 2); // assuming PCM format
706     }
707 schoenebeck 2
708 schoenebeck 800
709    
710 schoenebeck 2 // *************** Region ***************
711     // *
712    
713     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
714     pCkRegion = rgnList;
715    
716 schoenebeck 800 // articulation informations
717 schoenebeck 2 RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
718 schoenebeck 800 if (rgnh) {
719     rgnh->Read(&KeyRange, 2, 2);
720     rgnh->Read(&VelocityRange, 2, 2);
721     FormatOptionFlags = rgnh->ReadUint16();
722     KeyGroup = rgnh->ReadUint16();
723     // Layer is optional
724     if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
725     rgnh->Read(&Layer, 1, sizeof(uint16_t));
726     } else Layer = 0;
727     } else { // 'rgnh' chunk is missing
728     KeyRange.low = 0;
729     KeyRange.high = 127;
730     VelocityRange.low = 0;
731     VelocityRange.high = 127;
732     FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
733     KeyGroup = 0;
734     Layer = 0;
735 schoenebeck 2 }
736 schoenebeck 800 SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
737 schoenebeck 2
738 schoenebeck 800 // sample informations
739 schoenebeck 2 RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
740 schoenebeck 800 if (wlnk) {
741     WaveLinkOptionFlags = wlnk->ReadUint16();
742     PhaseGroup = wlnk->ReadUint16();
743     Channel = wlnk->ReadUint32();
744     WavePoolTableIndex = wlnk->ReadUint32();
745     } else { // 'wlnk' chunk is missing
746     WaveLinkOptionFlags = 0;
747     PhaseGroup = 0;
748     Channel = 0; // mono
749     WavePoolTableIndex = 0; // first entry in wave pool table
750     }
751     PhaseMaster = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
752     MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
753 schoenebeck 2
754     pSample = NULL;
755     }
756    
757 schoenebeck 800 /** @brief Destructor.
758     *
759     * Removes RIFF chunks associated with this Region.
760     */
761 schoenebeck 2 Region::~Region() {
762 schoenebeck 800 RIFF::List* pParent = pCkRegion->GetParent();
763     pParent->DeleteSubChunk(pCkRegion);
764 schoenebeck 2 }
765    
766     Sample* Region::GetSample() {
767     if (pSample) return pSample;
768     File* file = (File*) GetParent()->GetParent();
769     unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
770     Sample* sample = file->GetFirstSample();
771     while (sample) {
772     if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);
773     sample = file->GetNextSample();
774     }
775     return NULL;
776     }
777    
778 schoenebeck 800 /**
779     * Assign another sample to this Region.
780     *
781     * @param pSample - sample to be assigned
782     */
783     void Region::SetSample(Sample* pSample) {
784     this->pSample = pSample;
785     WavePoolTableIndex = 0; // we update this offset when we Save()
786     }
787 schoenebeck 2
788 schoenebeck 800 /**
789     * Apply Region settings to the respective RIFF chunks. You have to
790     * call File::Save() to make changes persistent.
791     *
792     * @throws Exception - if the Region's sample could not be found
793     */
794     void Region::UpdateChunks() {
795     // make sure 'rgnh' chunk exists
796     RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
797     if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, 14);
798     uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
799     FormatOptionFlags = (SelfNonExclusive)
800     ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
801     : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
802     // update 'rgnh' chunk
803     memccpy(&pData[0], &KeyRange, 2, 2);
804     memccpy(&pData[4], &VelocityRange, 2, 2);
805     memccpy(&pData[8], &FormatOptionFlags, 1, 2);
806     memccpy(&pData[10], &KeyGroup, 1, 2);
807     memccpy(&pData[12], &Layer, 1, 2);
808 schoenebeck 2
809 schoenebeck 800 // update chunks of base classes as well
810     Resource::UpdateChunks();
811     Articulator::UpdateChunks();
812     Sampler::UpdateChunks();
813    
814     // make sure 'wlnk' chunk exists
815     RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
816     if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
817     pData = (uint8_t*) wlnk->LoadChunkData();
818     WaveLinkOptionFlags = (PhaseMaster)
819     ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
820     : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
821     WaveLinkOptionFlags = (MultiChannel)
822     ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
823     : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
824     // get sample's wave pool table index
825     int index = -1;
826     File* pFile = (File*) GetParent()->GetParent();
827 schoenebeck 804 if (pFile->pSamples) {
828     File::SampleList::iterator iter = pFile->pSamples->begin();
829     File::SampleList::iterator end = pFile->pSamples->end();
830     for (int i = 0; iter != end; ++iter, i++) {
831     if (*iter == pSample) {
832     index = i;
833     break;
834     }
835 schoenebeck 800 }
836     }
837     if (index < 0) throw Exception("Could not save Region, could not find Region's sample");
838     WavePoolTableIndex = index;
839     // update 'wlnk' chunk
840     memccpy(&pData[0], &WaveLinkOptionFlags, 1, 2);
841     memccpy(&pData[2], &PhaseGroup, 1, 2);
842     memccpy(&pData[4], &Channel, 1, 4);
843     memccpy(&pData[8], &WavePoolTableIndex, 1, 4);
844     }
845    
846    
847    
848 schoenebeck 2 // *************** Instrument ***************
849     // *
850    
851 schoenebeck 800 /** @brief Constructor.
852     *
853     * Load an existing instrument definition or create a new one. An 'ins'
854     * list chunk must be given to this constructor. In case this 'ins' list
855     * chunk contains a 'insh' chunk, the instrument data fields will be
856     * loaded from there, otherwise default values will be used and the
857     * 'insh' chunk will be created once File::Save() was called.
858     *
859     * @param pFile - pointer to DLS::File where this instrument is
860     * located (or will be located)
861     * @param insList - pointer to 'ins' list chunk which is (or will be)
862     * associated with this instrument
863     */
864 schoenebeck 2 Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
865     pCkInstrument = insList;
866    
867 schoenebeck 800 midi_locale_t locale;
868 schoenebeck 2 RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
869 schoenebeck 800 if (insh) {
870     Regions = insh->ReadUint32();
871     insh->Read(&locale, 2, 4);
872     } else { // 'insh' chunk missing
873     Regions = 0;
874     locale.bank = 0;
875     locale.instrument = 0;
876     }
877    
878 schoenebeck 2 MIDIProgram = locale.instrument;
879     IsDrum = locale.bank & DRUM_TYPE_MASK;
880     MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
881     MIDIBankFine = (uint8_t) MIDI_BANK_FINE(locale.bank);
882     MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
883    
884 schoenebeck 800 pRegions = NULL;
885 schoenebeck 2 }
886    
887     Region* Instrument::GetFirstRegion() {
888     if (!pRegions) LoadRegions();
889     if (!pRegions) return NULL;
890     RegionsIterator = pRegions->begin();
891     return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
892     }
893    
894     Region* Instrument::GetNextRegion() {
895     if (!pRegions) return NULL;
896     RegionsIterator++;
897     return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
898     }
899    
900     void Instrument::LoadRegions() {
901 schoenebeck 823 if (!pRegions) pRegions = new RegionList;
902 schoenebeck 2 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
903 schoenebeck 823 if (lrgn) {
904     uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2
905     RIFF::List* rgn = lrgn->GetFirstSubList();
906     while (rgn) {
907     if (rgn->GetListType() == regionCkType) {
908     pRegions->push_back(new Region(this, rgn));
909     }
910     rgn = lrgn->GetNextSubList();
911 schoenebeck 2 }
912     }
913     }
914    
915 schoenebeck 800 Region* Instrument::AddRegion() {
916 schoenebeck 823 if (!pRegions) LoadRegions();
917 schoenebeck 800 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
918     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
919     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
920     Region* pNewRegion = new Region(this, rgn);
921     pRegions->push_back(pNewRegion);
922 schoenebeck 823 Regions = pRegions->size();
923 schoenebeck 800 return pNewRegion;
924     }
925    
926     void Instrument::DeleteRegion(Region* pRegion) {
927 schoenebeck 802 if (!pRegions) return;
928 schoenebeck 800 RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
929     if (iter == pRegions->end()) return;
930     pRegions->erase(iter);
931 schoenebeck 823 Regions = pRegions->size();
932 schoenebeck 800 delete pRegion;
933     }
934    
935     /**
936     * Apply Instrument with all its Regions to the respective RIFF chunks.
937     * You have to call File::Save() to make changes persistent.
938     *
939     * @throws Exception - on errors
940     */
941     void Instrument::UpdateChunks() {
942     // first update base classes' chunks
943     Resource::UpdateChunks();
944     Articulator::UpdateChunks();
945     // make sure 'insh' chunk exists
946     RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
947     if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
948     uint8_t* pData = (uint8_t*) insh->LoadChunkData();
949     // update 'insh' chunk
950 schoenebeck 804 Regions = (pRegions) ? pRegions->size() : 0;
951 schoenebeck 800 midi_locale_t locale;
952     locale.instrument = MIDIProgram;
953     locale.bank = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
954     locale.bank = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
955     MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
956     memccpy(&pData[0], &Regions, 1, 4);
957     memccpy(&pData[4], &locale, 2, 4);
958     // update Region's chunks
959 schoenebeck 804 if (!pRegions) return;
960 schoenebeck 800 RegionList::iterator iter = pRegions->begin();
961     RegionList::iterator end = pRegions->end();
962     for (; iter != end; ++iter) {
963     (*iter)->UpdateChunks();
964     }
965     }
966    
967     /** @brief Destructor.
968     *
969     * Removes RIFF chunks associated with this Instrument and frees all
970     * memory occupied by this instrument.
971     */
972 schoenebeck 2 Instrument::~Instrument() {
973     if (pRegions) {
974     RegionList::iterator iter = pRegions->begin();
975     RegionList::iterator end = pRegions->end();
976     while (iter != end) {
977     delete *iter;
978     iter++;
979     }
980     delete pRegions;
981     }
982 schoenebeck 800 // remove instrument's chunks
983     RIFF::List* pParent = pCkInstrument->GetParent();
984     pParent->DeleteSubChunk(pCkInstrument);
985 schoenebeck 2 }
986    
987    
988    
989     // *************** File ***************
990     // *
991    
992 schoenebeck 800 /** @brief Constructor.
993     *
994     * Default constructor, use this to create an empty DLS file. You have
995     * to add samples, instruments and finally call Save() to actually write
996     * a DLS file.
997     */
998 schoenebeck 802 File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
999 schoenebeck 800 pVersion = new version_t;
1000     pVersion->major = 0;
1001     pVersion->minor = 0;
1002     pVersion->release = 0;
1003     pVersion->build = 0;
1004    
1005     Instruments = 0;
1006     WavePoolCount = 0;
1007     pWavePoolTable = NULL;
1008     pWavePoolTableHi = NULL;
1009     WavePoolHeaderSize = 8;
1010    
1011     pSamples = NULL;
1012     pInstruments = NULL;
1013    
1014     b64BitWavePoolOffsets = false;
1015     }
1016    
1017     /** @brief Constructor.
1018     *
1019     * Load an existing DLS file.
1020     *
1021     * @param pRIFF - pointer to a RIFF file which is actually the DLS file
1022     * to load
1023     * @throws Exception if given file is not a DLS file, expected chunks
1024     * are missing
1025     */
1026 schoenebeck 2 File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1027     if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1028     this->pRIFF = pRIFF;
1029    
1030     RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1031     if (ckVersion) {
1032     pVersion = new version_t;
1033 schoenebeck 11 ckVersion->Read(pVersion, 4, 2);
1034 schoenebeck 2 }
1035     else pVersion = NULL;
1036    
1037     RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1038     if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1039     Instruments = colh->ReadUint32();
1040    
1041     RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1042     if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");
1043 schoenebeck 800 WavePoolHeaderSize = ptbl->ReadUint32();
1044 schoenebeck 2 WavePoolCount = ptbl->ReadUint32();
1045     pWavePoolTable = new uint32_t[WavePoolCount];
1046 persson 666 pWavePoolTableHi = new uint32_t[WavePoolCount];
1047 schoenebeck 800 ptbl->SetPos(WavePoolHeaderSize);
1048 schoenebeck 2
1049 schoenebeck 317 // Check for 64 bit offsets (used in gig v3 files)
1050 schoenebeck 800 b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1051     if (b64BitWavePoolOffsets) {
1052 schoenebeck 317 for (int i = 0 ; i < WavePoolCount ; i++) {
1053 persson 666 pWavePoolTableHi[i] = ptbl->ReadUint32();
1054 schoenebeck 317 pWavePoolTable[i] = ptbl->ReadUint32();
1055 persson 666 if (pWavePoolTable[i] & 0x80000000)
1056 schoenebeck 317 throw DLS::Exception("Files larger than 2 GB not yet supported");
1057     }
1058 schoenebeck 800 } else { // conventional 32 bit offsets
1059 persson 666 ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1060     for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1061     }
1062 schoenebeck 317
1063 schoenebeck 2 pSamples = NULL;
1064     pInstruments = NULL;
1065     }
1066    
1067     File::~File() {
1068     if (pInstruments) {
1069     InstrumentList::iterator iter = pInstruments->begin();
1070     InstrumentList::iterator end = pInstruments->end();
1071     while (iter != end) {
1072     delete *iter;
1073     iter++;
1074     }
1075     delete pInstruments;
1076     }
1077    
1078     if (pSamples) {
1079     SampleList::iterator iter = pSamples->begin();
1080     SampleList::iterator end = pSamples->end();
1081     while (iter != end) {
1082     delete *iter;
1083     iter++;
1084     }
1085     delete pSamples;
1086     }
1087    
1088     if (pWavePoolTable) delete[] pWavePoolTable;
1089 persson 666 if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1090 schoenebeck 2 if (pVersion) delete pVersion;
1091 persson 834 for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1092     delete *i;
1093 schoenebeck 2 }
1094    
1095     Sample* File::GetFirstSample() {
1096     if (!pSamples) LoadSamples();
1097     if (!pSamples) return NULL;
1098     SamplesIterator = pSamples->begin();
1099     return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1100     }
1101    
1102     Sample* File::GetNextSample() {
1103     if (!pSamples) return NULL;
1104     SamplesIterator++;
1105     return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1106     }
1107    
1108     void File::LoadSamples() {
1109 schoenebeck 823 if (!pSamples) pSamples = new SampleList;
1110 schoenebeck 2 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1111     if (wvpl) {
1112     unsigned long wvplFileOffset = wvpl->GetFilePos();
1113     RIFF::List* wave = wvpl->GetFirstSubList();
1114     while (wave) {
1115     if (wave->GetListType() == LIST_TYPE_WAVE) {
1116     unsigned long waveFileOffset = wave->GetFilePos();
1117     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1118     }
1119     wave = wvpl->GetNextSubList();
1120     }
1121     }
1122     else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)
1123     RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1124     if (dwpl) {
1125     unsigned long dwplFileOffset = dwpl->GetFilePos();
1126     RIFF::List* wave = dwpl->GetFirstSubList();
1127     while (wave) {
1128     if (wave->GetListType() == LIST_TYPE_WAVE) {
1129     unsigned long waveFileOffset = wave->GetFilePos();
1130     pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1131     }
1132     wave = dwpl->GetNextSubList();
1133     }
1134     }
1135     }
1136     }
1137    
1138 schoenebeck 800 /** @brief Add a new sample.
1139     *
1140     * This will create a new Sample object for the DLS file. You have to
1141     * call Save() to make this persistent to the file.
1142     *
1143     * @returns pointer to new Sample object
1144     */
1145     Sample* File::AddSample() {
1146 schoenebeck 809 if (!pSamples) LoadSamples();
1147 schoenebeck 800 __ensureMandatoryChunksExist();
1148     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1149     // create new Sample object and its respective 'wave' list chunk
1150     RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1151     Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1152     pSamples->push_back(pSample);
1153     return pSample;
1154     }
1155    
1156     /** @brief Delete a sample.
1157     *
1158     * This will delete the given Sample object from the DLS file. You have
1159     * to call Save() to make this persistent to the file.
1160     *
1161     * @param pSample - sample to delete
1162     */
1163     void File::DeleteSample(Sample* pSample) {
1164 schoenebeck 802 if (!pSamples) return;
1165 schoenebeck 800 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1166     if (iter == pSamples->end()) return;
1167     pSamples->erase(iter);
1168     delete pSample;
1169     }
1170    
1171 schoenebeck 2 Instrument* File::GetFirstInstrument() {
1172     if (!pInstruments) LoadInstruments();
1173     if (!pInstruments) return NULL;
1174     InstrumentsIterator = pInstruments->begin();
1175     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1176     }
1177    
1178     Instrument* File::GetNextInstrument() {
1179     if (!pInstruments) return NULL;
1180     InstrumentsIterator++;
1181     return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1182     }
1183    
1184     void File::LoadInstruments() {
1185 schoenebeck 823 if (!pInstruments) pInstruments = new InstrumentList;
1186 schoenebeck 2 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1187     if (lstInstruments) {
1188     RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1189     while (lstInstr) {
1190     if (lstInstr->GetListType() == LIST_TYPE_INS) {
1191     pInstruments->push_back(new Instrument(this, lstInstr));
1192     }
1193     lstInstr = lstInstruments->GetNextSubList();
1194     }
1195     }
1196     }
1197    
1198 schoenebeck 800 /** @brief Add a new instrument definition.
1199     *
1200     * This will create a new Instrument object for the DLS file. You have
1201     * to call Save() to make this persistent to the file.
1202     *
1203     * @returns pointer to new Instrument object
1204     */
1205     Instrument* File::AddInstrument() {
1206 schoenebeck 809 if (!pInstruments) LoadInstruments();
1207 schoenebeck 800 __ensureMandatoryChunksExist();
1208     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1209     RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1210     Instrument* pInstrument = new Instrument(this, lstInstr);
1211     pInstruments->push_back(pInstrument);
1212     return pInstrument;
1213     }
1214 schoenebeck 2
1215 schoenebeck 809 /** @brief Delete an instrument.
1216 schoenebeck 800 *
1217     * This will delete the given Instrument object from the DLS file. You
1218     * have to call Save() to make this persistent to the file.
1219     *
1220     * @param pInstrument - instrument to delete
1221     */
1222     void File::DeleteInstrument(Instrument* pInstrument) {
1223 schoenebeck 802 if (!pInstruments) return;
1224 schoenebeck 800 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1225     if (iter == pInstruments->end()) return;
1226     pInstruments->erase(iter);
1227     delete pInstrument;
1228     }
1229 schoenebeck 2
1230 schoenebeck 800 /**
1231     * Apply all the DLS file's current instruments, samples and settings to
1232     * the respective RIFF chunks. You have to call Save() to make changes
1233     * persistent.
1234     *
1235     * @throws Exception - on errors
1236     */
1237     void File::UpdateChunks() {
1238     // first update base class's chunks
1239     Resource::UpdateChunks();
1240    
1241     // if version struct exists, update 'vers' chunk
1242     if (pVersion) {
1243     RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1244     if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1245     uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1246     memccpy(pData, pVersion, 2, 4);
1247     }
1248    
1249     // update 'colh' chunk
1250     Instruments = (pInstruments) ? pInstruments->size() : 0;
1251     RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1252     if (!colh) colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1253     uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1254     memccpy(pData, &Instruments, 1, 4);
1255    
1256     // update instrument's chunks
1257     if (pInstruments) {
1258     InstrumentList::iterator iter = pInstruments->begin();
1259     InstrumentList::iterator end = pInstruments->end();
1260     for (; iter != end; ++iter) {
1261     (*iter)->UpdateChunks();
1262     }
1263     }
1264    
1265     // update 'ptbl' chunk
1266     const int iSamples = (pSamples) ? pSamples->size() : 0;
1267     const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1268     RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1269     if (!ptbl) ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
1270     const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1271     ptbl->Resize(iPtblSize);
1272     pData = (uint8_t*) ptbl->LoadChunkData();
1273     WavePoolCount = iSamples;
1274     memccpy(&pData[4], &WavePoolCount, 1, 4);
1275     // we actually update the sample offsets in the pool table when we Save()
1276     memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1277    
1278     // update sample's chunks
1279     if (pSamples) {
1280     SampleList::iterator iter = pSamples->begin();
1281     SampleList::iterator end = pSamples->end();
1282     for (; iter != end; ++iter) {
1283     (*iter)->UpdateChunks();
1284     }
1285     }
1286     }
1287    
1288     /** @brief Save changes to another file.
1289     *
1290     * Make all changes persistent by writing them to another file.
1291     * <b>Caution:</b> this method is optimized for writing to
1292     * <b>another</b> file, do not use it to save the changes to the same
1293     * file! Use Save() (without path argument) in that case instead!
1294     * Ignoring this might result in a corrupted file!
1295     *
1296     * After calling this method, this File object will be associated with
1297     * the new file (given by \a Path) afterwards.
1298     *
1299     * @param Path - path and file name where everything should be written to
1300     */
1301     void File::Save(const String& Path) {
1302     UpdateChunks();
1303     pRIFF->Save(Path);
1304     __UpdateWavePoolTableChunk();
1305     }
1306    
1307     /** @brief Save changes to same file.
1308     *
1309     * Make all changes persistent by writing them to the actual (same)
1310     * file. The file might temporarily grow to a higher size than it will
1311     * have at the end of the saving process.
1312     *
1313     * @throws RIFF::Exception if any kind of IO error occured
1314     * @throws DLS::Exception if any kind of DLS specific error occured
1315     */
1316     void File::Save() {
1317     UpdateChunks();
1318     pRIFF->Save();
1319     __UpdateWavePoolTableChunk();
1320     }
1321    
1322     /**
1323     * Checks if all (for DLS) mandatory chunks exist, if not they will be
1324     * created. Note that those chunks will not be made persistent until
1325     * Save() was called.
1326     */
1327     void File::__ensureMandatoryChunksExist() {
1328     // enusre 'lins' list chunk exists (mandatory for instrument definitions)
1329     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1330     if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
1331     // ensure 'ptbl' chunk exists (mandatory for samples)
1332     RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1333     if (!ptbl) {
1334     const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1335     ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
1336     }
1337     // enusre 'wvpl' list chunk exists (mandatory for samples)
1338     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1339     if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
1340     }
1341    
1342     /**
1343     * Updates (persistently) the wave pool table with offsets to all
1344     * currently available samples. <b>Caution:</b> this method assumes the
1345 schoenebeck 804 * 'ptbl' chunk to be already of the correct size and the file to be
1346     * writable, so usually this method is only called after a Save() call.
1347 schoenebeck 800 *
1348     * @throws Exception - if 'ptbl' chunk is too small (should only occur
1349     * if there's a bug)
1350     */
1351     void File::__UpdateWavePoolTableChunk() {
1352     __UpdateWavePoolTable();
1353     RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1354     const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1355     // check if 'ptbl' chunk is large enough
1356 schoenebeck 802 WavePoolCount = (pSamples) ? pSamples->size() : 0;
1357 schoenebeck 800 const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1358     if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1359 schoenebeck 804 // save the 'ptbl' chunk's current read/write position
1360     unsigned long ulOriginalPos = ptbl->GetPos();
1361 schoenebeck 800 // update headers
1362 schoenebeck 804 ptbl->SetPos(0);
1363     ptbl->WriteUint32(&WavePoolHeaderSize);
1364     ptbl->WriteUint32(&WavePoolCount);
1365 schoenebeck 800 // update offsets
1366 schoenebeck 804 ptbl->SetPos(WavePoolHeaderSize);
1367 schoenebeck 800 if (b64BitWavePoolOffsets) {
1368     for (int i = 0 ; i < WavePoolCount ; i++) {
1369 schoenebeck 804 ptbl->WriteUint32(&pWavePoolTableHi[i]);
1370     ptbl->WriteUint32(&pWavePoolTable[i]);
1371 schoenebeck 800 }
1372     } else { // conventional 32 bit offsets
1373     for (int i = 0 ; i < WavePoolCount ; i++)
1374 schoenebeck 804 ptbl->WriteUint32(&pWavePoolTable[i]);
1375 schoenebeck 800 }
1376 schoenebeck 804 // restore 'ptbl' chunk's original read/write position
1377     ptbl->SetPos(ulOriginalPos);
1378 schoenebeck 800 }
1379    
1380     /**
1381     * Updates the wave pool table with offsets to all currently available
1382     * samples. <b>Caution:</b> this method assumes the 'wvpl' list chunk
1383     * exists already.
1384     */
1385     void File::__UpdateWavePoolTable() {
1386 schoenebeck 802 WavePoolCount = (pSamples) ? pSamples->size() : 0;
1387 schoenebeck 800 // resize wave pool table arrays
1388     if (pWavePoolTable) delete[] pWavePoolTable;
1389     if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1390     pWavePoolTable = new uint32_t[WavePoolCount];
1391     pWavePoolTableHi = new uint32_t[WavePoolCount];
1392 schoenebeck 802 if (!pSamples) return;
1393 schoenebeck 800 // update offsets int wave pool table
1394     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1395     uint64_t wvplFileOffset = wvpl->GetFilePos();
1396     if (b64BitWavePoolOffsets) {
1397     SampleList::iterator iter = pSamples->begin();
1398     SampleList::iterator end = pSamples->end();
1399     for (int i = 0 ; iter != end ; ++iter, i++) {
1400 schoenebeck 804 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1401 schoenebeck 800 (*iter)->ulWavePoolOffset = _64BitOffset;
1402     pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1403     pWavePoolTable[i] = (uint32_t) _64BitOffset;
1404     }
1405     } else { // conventional 32 bit offsets
1406     SampleList::iterator iter = pSamples->begin();
1407     SampleList::iterator end = pSamples->end();
1408     for (int i = 0 ; iter != end ; ++iter, i++) {
1409 schoenebeck 804 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1410 schoenebeck 800 (*iter)->ulWavePoolOffset = _64BitOffset;
1411     pWavePoolTable[i] = (uint32_t) _64BitOffset;
1412     }
1413     }
1414     }
1415    
1416    
1417    
1418 schoenebeck 2 // *************** Exception ***************
1419     // *
1420    
1421     Exception::Exception(String Message) : RIFF::Exception(Message) {
1422     }
1423    
1424     void Exception::PrintMessage() {
1425     std::cout << "DLS::Exception: " << Message << std::endl;
1426     }
1427    
1428 schoenebeck 518
1429     // *************** functions ***************
1430     // *
1431    
1432     /**
1433     * Returns the name of this C++ library. This is usually "libgig" of
1434     * course. This call is equivalent to RIFF::libraryName() and
1435     * gig::libraryName().
1436     */
1437     String libraryName() {
1438     return PACKAGE;
1439     }
1440    
1441     /**
1442     * Returns version of this C++ library. This call is equivalent to
1443     * RIFF::libraryVersion() and gig::libraryVersion().
1444     */
1445     String libraryVersion() {
1446     return VERSION;
1447     }
1448    
1449 schoenebeck 2 } // namespace DLS

  ViewVC Help
Powered by ViewVC