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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1388 - (show annotations) (download)
Sun Oct 7 11:10:02 2007 UTC (16 years, 6 months ago) by persson
File size: 66348 byte(s)
* fixed crash when saving a file after a sample loop was added

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 = 20;
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 int wsmpSize = uiHeaderSize + SampleLoops * 16;
527 if (!wsmp) {
528 wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
529 } else if (wsmp->GetSize() != wsmpSize) {
530 wsmp->Resize(wsmpSize);
531 }
532 uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
533 // update headers size
534 store32(&pData[0], uiHeaderSize);
535 // update respective sampler options bits
536 SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
537 : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
538 SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
539 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
540 store16(&pData[4], UnityNote);
541 store16(&pData[6], FineTune);
542 store32(&pData[8], Gain);
543 store32(&pData[12], SamplerOptions);
544 store32(&pData[16], SampleLoops);
545 // update loop definitions
546 for (uint32_t i = 0; i < SampleLoops; i++) {
547 //FIXME: this does not handle extended loop structs correctly
548 store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
549 store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
550 store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
551 store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
552 }
553 }
554
555 /**
556 * Adds a new sample loop with the provided loop definition.
557 *
558 * @param pLoopDef - points to a loop definition that is to be copied
559 */
560 void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
561 sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
562 // copy old loops array
563 for (int i = 0; i < SampleLoops; i++) {
564 pNewLoops[i] = pSampleLoops[i];
565 }
566 // add the new loop
567 pNewLoops[SampleLoops] = *pLoopDef;
568 // auto correct size field
569 pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
570 // free the old array and update the member variables
571 if (SampleLoops) delete[] pSampleLoops;
572 pSampleLoops = pNewLoops;
573 SampleLoops++;
574 }
575
576 /**
577 * Deletes an existing sample loop.
578 *
579 * @param pLoopDef - pointer to existing loop definition
580 * @throws Exception - if given loop definition does not exist
581 */
582 void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
583 sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
584 // copy old loops array (skipping given loop)
585 for (int i = 0, o = 0; i < SampleLoops; i++) {
586 if (&pSampleLoops[i] == pLoopDef) continue;
587 if (o == SampleLoops - 1)
588 throw Exception("Could not delete Sample Loop, because it does not exist");
589 pNewLoops[o] = pSampleLoops[i];
590 o++;
591 }
592 // free the old array and update the member variables
593 if (SampleLoops) delete[] pSampleLoops;
594 pSampleLoops = pNewLoops;
595 SampleLoops--;
596 }
597
598
599
600 // *************** Sample ***************
601 // *
602
603 /** @brief Constructor.
604 *
605 * Load an existing sample or create a new one. A 'wave' list chunk must
606 * be given to this constructor. In case the given 'wave' list chunk
607 * contains a 'fmt' and 'data' chunk, the format and sample data will be
608 * loaded from there, otherwise default values will be used and those
609 * chunks will be created when File::Save() will be called later on.
610 *
611 * @param pFile - pointer to DLS::File where this sample is
612 * located (or will be located)
613 * @param waveList - pointer to 'wave' list chunk which is (or
614 * will be) associated with this sample
615 * @param WavePoolOffset - offset of this sample data from wave pool
616 * ('wvpl') list chunk
617 */
618 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : Resource(pFile, waveList) {
619 pWaveList = waveList;
620 ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;
621 pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
622 pCkData = waveList->GetSubChunk(CHUNK_ID_DATA);
623 if (pCkFormat) {
624 // common fields
625 FormatTag = pCkFormat->ReadUint16();
626 Channels = pCkFormat->ReadUint16();
627 SamplesPerSecond = pCkFormat->ReadUint32();
628 AverageBytesPerSecond = pCkFormat->ReadUint32();
629 BlockAlign = pCkFormat->ReadUint16();
630 // PCM format specific
631 if (FormatTag == DLS_WAVE_FORMAT_PCM) {
632 BitDepth = pCkFormat->ReadUint16();
633 FrameSize = (BitDepth / 8) * Channels;
634 } else { // unsupported sample data format
635 BitDepth = 0;
636 FrameSize = 0;
637 }
638 } else { // 'fmt' chunk missing
639 FormatTag = DLS_WAVE_FORMAT_PCM;
640 BitDepth = 16;
641 Channels = 1;
642 SamplesPerSecond = 44100;
643 AverageBytesPerSecond = (BitDepth / 8) * SamplesPerSecond * Channels;
644 FrameSize = (BitDepth / 8) * Channels;
645 BlockAlign = FrameSize;
646 }
647 SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
648 : 0
649 : 0;
650 }
651
652 /** @brief Destructor.
653 *
654 * Removes RIFF chunks associated with this Sample and frees all
655 * memory occupied by this sample.
656 */
657 Sample::~Sample() {
658 RIFF::List* pParent = pWaveList->GetParent();
659 pParent->DeleteSubChunk(pWaveList);
660 }
661
662 /** @brief Load sample data into RAM.
663 *
664 * In case the respective 'data' chunk exists, the sample data will be
665 * loaded into RAM (if not done already) and a pointer to the data in
666 * RAM will be returned. If this is a new sample, you have to call
667 * Resize() with the desired sample size to create the mandatory RIFF
668 * chunk for the sample wave data.
669 *
670 * You can call LoadChunkData() again if you previously scheduled to
671 * enlarge the sample data RIFF chunk with a Resize() call. In that case
672 * the buffer will be enlarged to the new, scheduled size and you can
673 * already place the sample wave data to the buffer and finally call
674 * File::Save() to enlarge the sample data's chunk physically and write
675 * the new sample wave data in one rush. This approach is definitely
676 * recommended if you have to enlarge and write new sample data to a lot
677 * of samples.
678 *
679 * <b>Caution:</b> the buffer pointer will be invalidated once
680 * File::Save() was called. You have to call LoadChunkData() again to
681 * get a new, valid pointer whenever File::Save() was called.
682 *
683 * @returns pointer to sample data in RAM, NULL in case respective
684 * 'data' chunk does not exist (yet)
685 * @throws Exception if data buffer could not be enlarged
686 * @see Resize(), File::Save()
687 */
688 void* Sample::LoadSampleData() {
689 return (pCkData) ? pCkData->LoadChunkData() : NULL;
690 }
691
692 /** @brief Free sample data from RAM.
693 *
694 * In case sample data was previously successfully loaded into RAM with
695 * LoadSampleData(), this method will free the sample data from RAM.
696 */
697 void Sample::ReleaseSampleData() {
698 if (pCkData) pCkData->ReleaseChunkData();
699 }
700
701 /** @brief Returns sample size.
702 *
703 * Returns the sample wave form's data size (in sample points). This is
704 * actually the current, physical size (converted to sample points) of
705 * the RIFF chunk which encapsulates the sample's wave data. The
706 * returned value is dependant to the current FrameSize value.
707 *
708 * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM
709 * @see FrameSize, FormatTag
710 */
711 unsigned long Sample::GetSize() {
712 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
713 return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
714 }
715
716 /** @brief Resize sample.
717 *
718 * Resizes the sample's wave form data, that is the actual size of
719 * sample wave data possible to be written for this sample. This call
720 * will return immediately and just schedule the resize operation. You
721 * should call File::Save() to actually perform the resize operation(s)
722 * "physically" to the file. As this can take a while on large files, it
723 * is recommended to call Resize() first on all samples which have to be
724 * resized and finally to call File::Save() to perform all those resize
725 * operations in one rush.
726 *
727 * The actual size (in bytes) is dependant to the current FrameSize
728 * value. You may want to set FrameSize before calling Resize().
729 *
730 * <b>Caution:</b> You cannot directly write to enlarged samples before
731 * calling File::Save() as this might exceed the current sample's
732 * boundary!
733 *
734 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
735 * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
736 * other formats will fail!
737 *
738 * @param iNewSize - new sample wave data size in sample points (must be
739 * greater than zero)
740 * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
741 * @throws Exception if \a iNewSize is less than 1
742 * @see File::Save(), FrameSize, FormatTag
743 */
744 void Sample::Resize(int iNewSize) {
745 if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
746 if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");
747 const int iSizeInBytes = iNewSize * FrameSize;
748 pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
749 if (pCkData) pCkData->Resize(iSizeInBytes);
750 else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);
751 }
752
753 /**
754 * Sets the position within the sample (in sample points, not in
755 * bytes). Use this method and <i>Read()</i> if you don't want to load
756 * the sample into RAM, thus for disk streaming.
757 *
758 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
759 * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
760 * with other formats will fail!
761 *
762 * @param SampleCount number of sample points
763 * @param Whence to which relation \a SampleCount refers to
764 * @returns new position within the sample, 0 if
765 * FormatTag != DLS_WAVE_FORMAT_PCM
766 * @throws Exception if no data RIFF chunk was created for the sample yet
767 * @see FrameSize, FormatTag
768 */
769 unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
770 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
771 if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
772 unsigned long orderedBytes = SampleCount * FrameSize;
773 unsigned long result = pCkData->SetPos(orderedBytes, Whence);
774 return (result == orderedBytes) ? SampleCount
775 : result / FrameSize;
776 }
777
778 /**
779 * Reads \a SampleCount number of sample points from the current
780 * position into the buffer pointed by \a pBuffer and increments the
781 * position within the sample. Use this method and <i>SetPos()</i> if you
782 * don't want to load the sample into RAM, thus for disk streaming.
783 *
784 * @param pBuffer destination buffer
785 * @param SampleCount number of sample points to read
786 */
787 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
788 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
789 return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
790 }
791
792 /** @brief Write sample wave data.
793 *
794 * Writes \a SampleCount number of sample points from the buffer pointed
795 * by \a pBuffer and increments the position within the sample. Use this
796 * method to directly write the sample data to disk, i.e. if you don't
797 * want or cannot load the whole sample data into RAM.
798 *
799 * You have to Resize() the sample to the desired size and call
800 * File::Save() <b>before</b> using Write().
801 *
802 * @param pBuffer - source buffer
803 * @param SampleCount - number of sample points to write
804 * @throws Exception if current sample size is too small
805 * @see LoadSampleData()
806 */
807 unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
808 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
809 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
810 return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
811 }
812
813 /**
814 * Apply sample and its settings to the respective RIFF chunks. You have
815 * to call File::Save() to make changes persistent.
816 *
817 * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
818 * was provided yet
819 */
820 void Sample::UpdateChunks() {
821 if (FormatTag != DLS_WAVE_FORMAT_PCM)
822 throw Exception("Could not save sample, only PCM format is supported");
823 // we refuse to do anything if not sample wave form was provided yet
824 if (!pCkData)
825 throw Exception("Could not save sample, there is no sample data to save");
826 // update chunks of base class as well
827 Resource::UpdateChunks();
828 // make sure 'fmt' chunk exists
829 RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
830 if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
831 uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
832 // update 'fmt' chunk
833 store16(&pData[0], FormatTag);
834 store16(&pData[2], Channels);
835 store32(&pData[4], SamplesPerSecond);
836 store32(&pData[8], AverageBytesPerSecond);
837 store16(&pData[12], BlockAlign);
838 store16(&pData[14], BitDepth); // assuming PCM format
839 }
840
841
842
843 // *************** Region ***************
844 // *
845
846 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
847 pCkRegion = rgnList;
848
849 // articulation informations
850 RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
851 if (rgnh) {
852 rgnh->Read(&KeyRange, 2, 2);
853 rgnh->Read(&VelocityRange, 2, 2);
854 FormatOptionFlags = rgnh->ReadUint16();
855 KeyGroup = rgnh->ReadUint16();
856 // Layer is optional
857 if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
858 rgnh->Read(&Layer, 1, sizeof(uint16_t));
859 } else Layer = 0;
860 } else { // 'rgnh' chunk is missing
861 KeyRange.low = 0;
862 KeyRange.high = 127;
863 VelocityRange.low = 0;
864 VelocityRange.high = 127;
865 FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
866 KeyGroup = 0;
867 Layer = 0;
868 }
869 SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
870
871 // sample informations
872 RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
873 if (wlnk) {
874 WaveLinkOptionFlags = wlnk->ReadUint16();
875 PhaseGroup = wlnk->ReadUint16();
876 Channel = wlnk->ReadUint32();
877 WavePoolTableIndex = wlnk->ReadUint32();
878 } else { // 'wlnk' chunk is missing
879 WaveLinkOptionFlags = 0;
880 PhaseGroup = 0;
881 Channel = 0; // mono
882 WavePoolTableIndex = 0; // first entry in wave pool table
883 }
884 PhaseMaster = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
885 MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
886
887 pSample = NULL;
888 }
889
890 /** @brief Destructor.
891 *
892 * Removes RIFF chunks associated with this Region.
893 */
894 Region::~Region() {
895 RIFF::List* pParent = pCkRegion->GetParent();
896 pParent->DeleteSubChunk(pCkRegion);
897 }
898
899 Sample* Region::GetSample() {
900 if (pSample) return pSample;
901 File* file = (File*) GetParent()->GetParent();
902 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
903 Sample* sample = file->GetFirstSample();
904 while (sample) {
905 if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);
906 sample = file->GetNextSample();
907 }
908 return NULL;
909 }
910
911 /**
912 * Assign another sample to this Region.
913 *
914 * @param pSample - sample to be assigned
915 */
916 void Region::SetSample(Sample* pSample) {
917 this->pSample = pSample;
918 WavePoolTableIndex = 0; // we update this offset when we Save()
919 }
920
921 /**
922 * Modifies the key range of this Region and makes sure the respective
923 * chunks are in correct order.
924 *
925 * @param Low - lower end of key range
926 * @param High - upper end of key range
927 */
928 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
929 KeyRange.low = Low;
930 KeyRange.high = High;
931
932 // make sure regions are already loaded
933 Instrument* pInstrument = (Instrument*) GetParent();
934 if (!pInstrument->pRegions) pInstrument->LoadRegions();
935 if (!pInstrument->pRegions) return;
936
937 // find the r which is the first one to the right of this region
938 // at its new position
939 Region* r = NULL;
940 Region* prev_region = NULL;
941 for (
942 Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
943 iter != pInstrument->pRegions->end(); iter++
944 ) {
945 if ((*iter)->KeyRange.low > this->KeyRange.low) {
946 r = *iter;
947 break;
948 }
949 prev_region = *iter;
950 }
951
952 // place this region before r if it's not already there
953 if (prev_region != this) pInstrument->MoveRegion(this, r);
954 }
955
956 /**
957 * Apply Region settings to the respective RIFF chunks. You have to
958 * call File::Save() to make changes persistent.
959 *
960 * @throws Exception - if the Region's sample could not be found
961 */
962 void Region::UpdateChunks() {
963 // make sure 'rgnh' chunk exists
964 RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
965 if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
966 uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
967 FormatOptionFlags = (SelfNonExclusive)
968 ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
969 : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
970 // update 'rgnh' chunk
971 store16(&pData[0], KeyRange.low);
972 store16(&pData[2], KeyRange.high);
973 store16(&pData[4], VelocityRange.low);
974 store16(&pData[6], VelocityRange.high);
975 store16(&pData[8], FormatOptionFlags);
976 store16(&pData[10], KeyGroup);
977 if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
978
979 // update chunks of base classes as well (but skip Resource,
980 // as a rgn doesn't seem to have dlid and INFO chunks)
981 Articulator::UpdateChunks();
982 Sampler::UpdateChunks();
983
984 // make sure 'wlnk' chunk exists
985 RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
986 if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
987 pData = (uint8_t*) wlnk->LoadChunkData();
988 WaveLinkOptionFlags = (PhaseMaster)
989 ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
990 : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
991 WaveLinkOptionFlags = (MultiChannel)
992 ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
993 : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
994 // get sample's wave pool table index
995 int index = -1;
996 File* pFile = (File*) GetParent()->GetParent();
997 if (pFile->pSamples) {
998 File::SampleList::iterator iter = pFile->pSamples->begin();
999 File::SampleList::iterator end = pFile->pSamples->end();
1000 for (int i = 0; iter != end; ++iter, i++) {
1001 if (*iter == pSample) {
1002 index = i;
1003 break;
1004 }
1005 }
1006 }
1007 WavePoolTableIndex = index;
1008 // update 'wlnk' chunk
1009 store16(&pData[0], WaveLinkOptionFlags);
1010 store16(&pData[2], PhaseGroup);
1011 store32(&pData[4], Channel);
1012 store32(&pData[8], WavePoolTableIndex);
1013 }
1014
1015
1016
1017 // *************** Instrument ***************
1018 // *
1019
1020 /** @brief Constructor.
1021 *
1022 * Load an existing instrument definition or create a new one. An 'ins'
1023 * list chunk must be given to this constructor. In case this 'ins' list
1024 * chunk contains a 'insh' chunk, the instrument data fields will be
1025 * loaded from there, otherwise default values will be used and the
1026 * 'insh' chunk will be created once File::Save() was called.
1027 *
1028 * @param pFile - pointer to DLS::File where this instrument is
1029 * located (or will be located)
1030 * @param insList - pointer to 'ins' list chunk which is (or will be)
1031 * associated with this instrument
1032 */
1033 Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
1034 pCkInstrument = insList;
1035
1036 midi_locale_t locale;
1037 RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1038 if (insh) {
1039 Regions = insh->ReadUint32();
1040 insh->Read(&locale, 2, 4);
1041 } else { // 'insh' chunk missing
1042 Regions = 0;
1043 locale.bank = 0;
1044 locale.instrument = 0;
1045 }
1046
1047 MIDIProgram = locale.instrument;
1048 IsDrum = locale.bank & DRUM_TYPE_MASK;
1049 MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
1050 MIDIBankFine = (uint8_t) MIDI_BANK_FINE(locale.bank);
1051 MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
1052
1053 pRegions = NULL;
1054 }
1055
1056 Region* Instrument::GetFirstRegion() {
1057 if (!pRegions) LoadRegions();
1058 if (!pRegions) return NULL;
1059 RegionsIterator = pRegions->begin();
1060 return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1061 }
1062
1063 Region* Instrument::GetNextRegion() {
1064 if (!pRegions) return NULL;
1065 RegionsIterator++;
1066 return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1067 }
1068
1069 void Instrument::LoadRegions() {
1070 if (!pRegions) pRegions = new RegionList;
1071 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1072 if (lrgn) {
1073 uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2
1074 RIFF::List* rgn = lrgn->GetFirstSubList();
1075 while (rgn) {
1076 if (rgn->GetListType() == regionCkType) {
1077 pRegions->push_back(new Region(this, rgn));
1078 }
1079 rgn = lrgn->GetNextSubList();
1080 }
1081 }
1082 }
1083
1084 Region* Instrument::AddRegion() {
1085 if (!pRegions) LoadRegions();
1086 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1087 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
1088 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1089 Region* pNewRegion = new Region(this, rgn);
1090 pRegions->push_back(pNewRegion);
1091 Regions = pRegions->size();
1092 return pNewRegion;
1093 }
1094
1095 void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1096 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1097 lrgn->MoveSubChunk(pSrc->pCkRegion, pDst ? pDst->pCkRegion : 0);
1098
1099 pRegions->remove(pSrc);
1100 RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1101 pRegions->insert(iter, pSrc);
1102 }
1103
1104 void Instrument::DeleteRegion(Region* pRegion) {
1105 if (!pRegions) return;
1106 RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1107 if (iter == pRegions->end()) return;
1108 pRegions->erase(iter);
1109 Regions = pRegions->size();
1110 delete pRegion;
1111 }
1112
1113 /**
1114 * Apply Instrument with all its Regions to the respective RIFF chunks.
1115 * You have to call File::Save() to make changes persistent.
1116 *
1117 * @throws Exception - on errors
1118 */
1119 void Instrument::UpdateChunks() {
1120 // first update base classes' chunks
1121 Resource::UpdateChunks();
1122 Articulator::UpdateChunks();
1123 // make sure 'insh' chunk exists
1124 RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1125 if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1126 uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1127 // update 'insh' chunk
1128 Regions = (pRegions) ? pRegions->size() : 0;
1129 midi_locale_t locale;
1130 locale.instrument = MIDIProgram;
1131 locale.bank = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1132 locale.bank = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
1133 MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
1134 store32(&pData[0], Regions);
1135 store32(&pData[4], locale.bank);
1136 store32(&pData[8], locale.instrument);
1137 // update Region's chunks
1138 if (!pRegions) return;
1139 RegionList::iterator iter = pRegions->begin();
1140 RegionList::iterator end = pRegions->end();
1141 for (; iter != end; ++iter) {
1142 (*iter)->UpdateChunks();
1143 }
1144 }
1145
1146 /** @brief Destructor.
1147 *
1148 * Removes RIFF chunks associated with this Instrument and frees all
1149 * memory occupied by this instrument.
1150 */
1151 Instrument::~Instrument() {
1152 if (pRegions) {
1153 RegionList::iterator iter = pRegions->begin();
1154 RegionList::iterator end = pRegions->end();
1155 while (iter != end) {
1156 delete *iter;
1157 iter++;
1158 }
1159 delete pRegions;
1160 }
1161 // remove instrument's chunks
1162 RIFF::List* pParent = pCkInstrument->GetParent();
1163 pParent->DeleteSubChunk(pCkInstrument);
1164 }
1165
1166
1167
1168 // *************** File ***************
1169 // *
1170
1171 /** @brief Constructor.
1172 *
1173 * Default constructor, use this to create an empty DLS file. You have
1174 * to add samples, instruments and finally call Save() to actually write
1175 * a DLS file.
1176 */
1177 File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1178 pRIFF->SetByteOrder(RIFF::endian_little);
1179 pVersion = new version_t;
1180 pVersion->major = 0;
1181 pVersion->minor = 0;
1182 pVersion->release = 0;
1183 pVersion->build = 0;
1184
1185 Instruments = 0;
1186 WavePoolCount = 0;
1187 pWavePoolTable = NULL;
1188 pWavePoolTableHi = NULL;
1189 WavePoolHeaderSize = 8;
1190
1191 pSamples = NULL;
1192 pInstruments = NULL;
1193
1194 b64BitWavePoolOffsets = false;
1195 }
1196
1197 /** @brief Constructor.
1198 *
1199 * Load an existing DLS file.
1200 *
1201 * @param pRIFF - pointer to a RIFF file which is actually the DLS file
1202 * to load
1203 * @throws Exception if given file is not a DLS file, expected chunks
1204 * are missing
1205 */
1206 File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1207 if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1208 this->pRIFF = pRIFF;
1209
1210 RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1211 if (ckVersion) {
1212 pVersion = new version_t;
1213 ckVersion->Read(pVersion, 4, 2);
1214 }
1215 else pVersion = NULL;
1216
1217 RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1218 if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1219 Instruments = colh->ReadUint32();
1220
1221 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1222 if (!ptbl) { // pool table is missing - this is probably an ".art" file
1223 WavePoolCount = 0;
1224 pWavePoolTable = NULL;
1225 pWavePoolTableHi = NULL;
1226 WavePoolHeaderSize = 8;
1227 b64BitWavePoolOffsets = false;
1228 } else {
1229 WavePoolHeaderSize = ptbl->ReadUint32();
1230 WavePoolCount = ptbl->ReadUint32();
1231 pWavePoolTable = new uint32_t[WavePoolCount];
1232 pWavePoolTableHi = new uint32_t[WavePoolCount];
1233 ptbl->SetPos(WavePoolHeaderSize);
1234
1235 // Check for 64 bit offsets (used in gig v3 files)
1236 b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1237 if (b64BitWavePoolOffsets) {
1238 for (int i = 0 ; i < WavePoolCount ; i++) {
1239 pWavePoolTableHi[i] = ptbl->ReadUint32();
1240 pWavePoolTable[i] = ptbl->ReadUint32();
1241 if (pWavePoolTable[i] & 0x80000000)
1242 throw DLS::Exception("Files larger than 2 GB not yet supported");
1243 }
1244 } else { // conventional 32 bit offsets
1245 ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1246 for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1247 }
1248 }
1249
1250 pSamples = NULL;
1251 pInstruments = NULL;
1252 }
1253
1254 File::~File() {
1255 if (pInstruments) {
1256 InstrumentList::iterator iter = pInstruments->begin();
1257 InstrumentList::iterator end = pInstruments->end();
1258 while (iter != end) {
1259 delete *iter;
1260 iter++;
1261 }
1262 delete pInstruments;
1263 }
1264
1265 if (pSamples) {
1266 SampleList::iterator iter = pSamples->begin();
1267 SampleList::iterator end = pSamples->end();
1268 while (iter != end) {
1269 delete *iter;
1270 iter++;
1271 }
1272 delete pSamples;
1273 }
1274
1275 if (pWavePoolTable) delete[] pWavePoolTable;
1276 if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1277 if (pVersion) delete pVersion;
1278 for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1279 delete *i;
1280 }
1281
1282 Sample* File::GetFirstSample() {
1283 if (!pSamples) LoadSamples();
1284 if (!pSamples) return NULL;
1285 SamplesIterator = pSamples->begin();
1286 return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1287 }
1288
1289 Sample* File::GetNextSample() {
1290 if (!pSamples) return NULL;
1291 SamplesIterator++;
1292 return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1293 }
1294
1295 void File::LoadSamples() {
1296 if (!pSamples) pSamples = new SampleList;
1297 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1298 if (wvpl) {
1299 unsigned long wvplFileOffset = wvpl->GetFilePos();
1300 RIFF::List* wave = wvpl->GetFirstSubList();
1301 while (wave) {
1302 if (wave->GetListType() == LIST_TYPE_WAVE) {
1303 unsigned long waveFileOffset = wave->GetFilePos();
1304 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1305 }
1306 wave = wvpl->GetNextSubList();
1307 }
1308 }
1309 else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)
1310 RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1311 if (dwpl) {
1312 unsigned long dwplFileOffset = dwpl->GetFilePos();
1313 RIFF::List* wave = dwpl->GetFirstSubList();
1314 while (wave) {
1315 if (wave->GetListType() == LIST_TYPE_WAVE) {
1316 unsigned long waveFileOffset = wave->GetFilePos();
1317 pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1318 }
1319 wave = dwpl->GetNextSubList();
1320 }
1321 }
1322 }
1323 }
1324
1325 /** @brief Add a new sample.
1326 *
1327 * This will create a new Sample object for the DLS file. You have to
1328 * call Save() to make this persistent to the file.
1329 *
1330 * @returns pointer to new Sample object
1331 */
1332 Sample* File::AddSample() {
1333 if (!pSamples) LoadSamples();
1334 __ensureMandatoryChunksExist();
1335 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1336 // create new Sample object and its respective 'wave' list chunk
1337 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1338 Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1339 pSamples->push_back(pSample);
1340 return pSample;
1341 }
1342
1343 /** @brief Delete a sample.
1344 *
1345 * This will delete the given Sample object from the DLS file. You have
1346 * to call Save() to make this persistent to the file.
1347 *
1348 * @param pSample - sample to delete
1349 */
1350 void File::DeleteSample(Sample* pSample) {
1351 if (!pSamples) return;
1352 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1353 if (iter == pSamples->end()) return;
1354 pSamples->erase(iter);
1355 delete pSample;
1356 }
1357
1358 Instrument* File::GetFirstInstrument() {
1359 if (!pInstruments) LoadInstruments();
1360 if (!pInstruments) return NULL;
1361 InstrumentsIterator = pInstruments->begin();
1362 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1363 }
1364
1365 Instrument* File::GetNextInstrument() {
1366 if (!pInstruments) return NULL;
1367 InstrumentsIterator++;
1368 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1369 }
1370
1371 void File::LoadInstruments() {
1372 if (!pInstruments) pInstruments = new InstrumentList;
1373 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1374 if (lstInstruments) {
1375 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1376 while (lstInstr) {
1377 if (lstInstr->GetListType() == LIST_TYPE_INS) {
1378 pInstruments->push_back(new Instrument(this, lstInstr));
1379 }
1380 lstInstr = lstInstruments->GetNextSubList();
1381 }
1382 }
1383 }
1384
1385 /** @brief Add a new instrument definition.
1386 *
1387 * This will create a new Instrument object for the DLS file. You have
1388 * to call Save() to make this persistent to the file.
1389 *
1390 * @returns pointer to new Instrument object
1391 */
1392 Instrument* File::AddInstrument() {
1393 if (!pInstruments) LoadInstruments();
1394 __ensureMandatoryChunksExist();
1395 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1396 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1397 Instrument* pInstrument = new Instrument(this, lstInstr);
1398 pInstruments->push_back(pInstrument);
1399 return pInstrument;
1400 }
1401
1402 /** @brief Delete an instrument.
1403 *
1404 * This will delete the given Instrument object from the DLS file. You
1405 * have to call Save() to make this persistent to the file.
1406 *
1407 * @param pInstrument - instrument to delete
1408 */
1409 void File::DeleteInstrument(Instrument* pInstrument) {
1410 if (!pInstruments) return;
1411 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1412 if (iter == pInstruments->end()) return;
1413 pInstruments->erase(iter);
1414 delete pInstrument;
1415 }
1416
1417 /**
1418 * Apply all the DLS file's current instruments, samples and settings to
1419 * the respective RIFF chunks. You have to call Save() to make changes
1420 * persistent.
1421 *
1422 * @throws Exception - on errors
1423 */
1424 void File::UpdateChunks() {
1425 // first update base class's chunks
1426 Resource::UpdateChunks();
1427
1428 // if version struct exists, update 'vers' chunk
1429 if (pVersion) {
1430 RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1431 if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1432 uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1433 store16(&pData[0], pVersion->minor);
1434 store16(&pData[2], pVersion->major);
1435 store16(&pData[4], pVersion->build);
1436 store16(&pData[6], pVersion->release);
1437 }
1438
1439 // update 'colh' chunk
1440 Instruments = (pInstruments) ? pInstruments->size() : 0;
1441 RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1442 if (!colh) colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1443 uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1444 store32(pData, Instruments);
1445
1446 // update instrument's chunks
1447 if (pInstruments) {
1448 InstrumentList::iterator iter = pInstruments->begin();
1449 InstrumentList::iterator end = pInstruments->end();
1450 for (; iter != end; ++iter) {
1451 (*iter)->UpdateChunks();
1452 }
1453 }
1454
1455 // update 'ptbl' chunk
1456 const int iSamples = (pSamples) ? pSamples->size() : 0;
1457 const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1458 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1459 if (!ptbl) ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
1460 const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1461 ptbl->Resize(iPtblSize);
1462 pData = (uint8_t*) ptbl->LoadChunkData();
1463 WavePoolCount = iSamples;
1464 store32(&pData[4], WavePoolCount);
1465 // we actually update the sample offsets in the pool table when we Save()
1466 memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1467
1468 // update sample's chunks
1469 if (pSamples) {
1470 SampleList::iterator iter = pSamples->begin();
1471 SampleList::iterator end = pSamples->end();
1472 for (; iter != end; ++iter) {
1473 (*iter)->UpdateChunks();
1474 }
1475 }
1476 }
1477
1478 /** @brief Save changes to another file.
1479 *
1480 * Make all changes persistent by writing them to another file.
1481 * <b>Caution:</b> this method is optimized for writing to
1482 * <b>another</b> file, do not use it to save the changes to the same
1483 * file! Use Save() (without path argument) in that case instead!
1484 * Ignoring this might result in a corrupted file!
1485 *
1486 * After calling this method, this File object will be associated with
1487 * the new file (given by \a Path) afterwards.
1488 *
1489 * @param Path - path and file name where everything should be written to
1490 */
1491 void File::Save(const String& Path) {
1492 UpdateChunks();
1493 pRIFF->Save(Path);
1494 __UpdateWavePoolTableChunk();
1495 }
1496
1497 /** @brief Save changes to same file.
1498 *
1499 * Make all changes persistent by writing them to the actual (same)
1500 * file. The file might temporarily grow to a higher size than it will
1501 * have at the end of the saving process.
1502 *
1503 * @throws RIFF::Exception if any kind of IO error occured
1504 * @throws DLS::Exception if any kind of DLS specific error occured
1505 */
1506 void File::Save() {
1507 UpdateChunks();
1508 pRIFF->Save();
1509 __UpdateWavePoolTableChunk();
1510 }
1511
1512 /**
1513 * Checks if all (for DLS) mandatory chunks exist, if not they will be
1514 * created. Note that those chunks will not be made persistent until
1515 * Save() was called.
1516 */
1517 void File::__ensureMandatoryChunksExist() {
1518 // enusre 'lins' list chunk exists (mandatory for instrument definitions)
1519 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1520 if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
1521 // ensure 'ptbl' chunk exists (mandatory for samples)
1522 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1523 if (!ptbl) {
1524 const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1525 ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
1526 }
1527 // enusre 'wvpl' list chunk exists (mandatory for samples)
1528 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1529 if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
1530 }
1531
1532 /**
1533 * Updates (persistently) the wave pool table with offsets to all
1534 * currently available samples. <b>Caution:</b> this method assumes the
1535 * 'ptbl' chunk to be already of the correct size and the file to be
1536 * writable, so usually this method is only called after a Save() call.
1537 *
1538 * @throws Exception - if 'ptbl' chunk is too small (should only occur
1539 * if there's a bug)
1540 */
1541 void File::__UpdateWavePoolTableChunk() {
1542 __UpdateWavePoolTable();
1543 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1544 const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1545 // check if 'ptbl' chunk is large enough
1546 WavePoolCount = (pSamples) ? pSamples->size() : 0;
1547 const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1548 if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1549 // save the 'ptbl' chunk's current read/write position
1550 unsigned long ulOriginalPos = ptbl->GetPos();
1551 // update headers
1552 ptbl->SetPos(0);
1553 uint32_t tmp = WavePoolHeaderSize;
1554 ptbl->WriteUint32(&tmp);
1555 tmp = WavePoolCount;
1556 ptbl->WriteUint32(&tmp);
1557 // update offsets
1558 ptbl->SetPos(WavePoolHeaderSize);
1559 if (b64BitWavePoolOffsets) {
1560 for (int i = 0 ; i < WavePoolCount ; i++) {
1561 tmp = pWavePoolTableHi[i];
1562 ptbl->WriteUint32(&tmp);
1563 tmp = pWavePoolTable[i];
1564 ptbl->WriteUint32(&tmp);
1565 }
1566 } else { // conventional 32 bit offsets
1567 for (int i = 0 ; i < WavePoolCount ; i++) {
1568 tmp = pWavePoolTable[i];
1569 ptbl->WriteUint32(&tmp);
1570 }
1571 }
1572 // restore 'ptbl' chunk's original read/write position
1573 ptbl->SetPos(ulOriginalPos);
1574 }
1575
1576 /**
1577 * Updates the wave pool table with offsets to all currently available
1578 * samples. <b>Caution:</b> this method assumes the 'wvpl' list chunk
1579 * exists already.
1580 */
1581 void File::__UpdateWavePoolTable() {
1582 WavePoolCount = (pSamples) ? pSamples->size() : 0;
1583 // resize wave pool table arrays
1584 if (pWavePoolTable) delete[] pWavePoolTable;
1585 if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1586 pWavePoolTable = new uint32_t[WavePoolCount];
1587 pWavePoolTableHi = new uint32_t[WavePoolCount];
1588 if (!pSamples) return;
1589 // update offsets int wave pool table
1590 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1591 uint64_t wvplFileOffset = wvpl->GetFilePos();
1592 if (b64BitWavePoolOffsets) {
1593 SampleList::iterator iter = pSamples->begin();
1594 SampleList::iterator end = pSamples->end();
1595 for (int i = 0 ; iter != end ; ++iter, i++) {
1596 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1597 (*iter)->ulWavePoolOffset = _64BitOffset;
1598 pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1599 pWavePoolTable[i] = (uint32_t) _64BitOffset;
1600 }
1601 } else { // conventional 32 bit offsets
1602 SampleList::iterator iter = pSamples->begin();
1603 SampleList::iterator end = pSamples->end();
1604 for (int i = 0 ; iter != end ; ++iter, i++) {
1605 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1606 (*iter)->ulWavePoolOffset = _64BitOffset;
1607 pWavePoolTable[i] = (uint32_t) _64BitOffset;
1608 }
1609 }
1610 }
1611
1612
1613
1614 // *************** Exception ***************
1615 // *
1616
1617 Exception::Exception(String Message) : RIFF::Exception(Message) {
1618 }
1619
1620 void Exception::PrintMessage() {
1621 std::cout << "DLS::Exception: " << Message << std::endl;
1622 }
1623
1624
1625 // *************** functions ***************
1626 // *
1627
1628 /**
1629 * Returns the name of this C++ library. This is usually "libgig" of
1630 * course. This call is equivalent to RIFF::libraryName() and
1631 * gig::libraryName().
1632 */
1633 String libraryName() {
1634 return PACKAGE;
1635 }
1636
1637 /**
1638 * Returns version of this C++ library. This call is equivalent to
1639 * RIFF::libraryVersion() and gig::libraryVersion().
1640 */
1641 String libraryVersion() {
1642 return VERSION;
1643 }
1644
1645 } // namespace DLS

  ViewVC Help
Powered by ViewVC