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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 839 - (hide annotations) (download)
Fri Feb 10 19:23:59 2006 UTC (18 years, 1 month ago) by persson
File size: 59823 byte(s)
* fixed bug introduced in previous commit - info strings weren't
  correctly terminated

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

  ViewVC Help
Powered by ViewVC