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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1358 - (hide annotations) (download)
Sun Sep 30 18:13:33 2007 UTC (16 years, 6 months ago) by schoenebeck
File size: 66259 byte(s)
* added various setter methods to which take care of updating
  lookup tables / caches

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

  ViewVC Help
Powered by ViewVC