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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1194 - (show annotations) (download)
Thu May 17 17:09:10 2007 UTC (13 years, 6 months ago) by schoenebeck
File size: 63002 byte(s)
- eliminated Doxygen warning

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

  ViewVC Help
Powered by ViewVC