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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2329 - (hide annotations) (download)
Mon Mar 12 14:59:10 2012 UTC (12 years, 1 month ago) by schoenebeck
File size: 68413 byte(s)
* added new method DLS::File::GetExtensionFile(int index)
* bumped version to 3.3.0svn3

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

  ViewVC Help
Powered by ViewVC