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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 804 - (show annotations) (download)
Sat Nov 12 19:16:01 2005 UTC (18 years, 4 months ago) by schoenebeck
File size: 59671 byte(s)
* src/DLS.cpp:
  - further bugfixes regarding DLS write support
* src/dlsdump.cpp:
  - show for every region the name of the referenced sample
  - show file name in quotation marks

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

  ViewVC Help
Powered by ViewVC