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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 802 - (show annotations) (download)
Thu Nov 10 19:53:34 2005 UTC (18 years, 5 months ago) by schoenebeck
File size: 59117 byte(s)
* bugfixes for the last commit batch

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

  ViewVC Help
Powered by ViewVC