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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 902 - (show annotations) (download)
Sat Jul 22 14:22:01 2006 UTC (17 years, 9 months ago) by persson
File size: 60111 byte(s)
* real support for 24 bit samples
* support for reading of .art files

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

  ViewVC Help
Powered by ViewVC