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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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

  ViewVC Help
Powered by ViewVC