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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 919 - (hide annotations) (download)
Fri Sep 15 19:35:11 2006 UTC (17 years, 7 months ago) by schoenebeck
File size: 61253 byte(s)
* bugfix: sampler parameters UnityNote, FineTune, Gain, SamplerOptions and
  SampleLoops were not stored when trying to save DLS or .gig files

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

  ViewVC Help
Powered by ViewVC