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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3463 - (show annotations) (download)
Sun Feb 10 19:58:24 2019 UTC (5 years, 2 months ago) by schoenebeck
File size: 82049 byte(s)
* DLS.cpp/DLS.h: Fixed implicitly allocated RIFF::File object never been
  freed.
* Bumped version (4.1.0.svn9).

1 /***************************************************************************
2 * *
3 * libgig - C++ cross-platform Gigasampler format file access library *
4 * *
5 * Copyright (C) 2003-2019 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 <algorithm>
27 #include <time.h>
28
29 #ifdef __APPLE__
30 #include <CoreFoundation/CFUUID.h>
31 #elif defined(HAVE_UUID_UUID_H)
32 #include <uuid/uuid.h>
33 #endif
34
35 #include "helper.h"
36
37 // macros to decode connection transforms
38 #define CONN_TRANSFORM_SRC(x) ((x >> 10) & 0x000F)
39 #define CONN_TRANSFORM_CTL(x) ((x >> 4) & 0x000F)
40 #define CONN_TRANSFORM_DST(x) (x & 0x000F)
41 #define CONN_TRANSFORM_BIPOLAR_SRC(x) (x & 0x4000)
42 #define CONN_TRANSFORM_BIPOLAR_CTL(x) (x & 0x0100)
43 #define CONN_TRANSFORM_INVERT_SRC(x) (x & 0x8000)
44 #define CONN_TRANSFORM_INVERT_CTL(x) (x & 0x0200)
45
46 // macros to encode connection transforms
47 #define CONN_TRANSFORM_SRC_ENCODE(x) ((x & 0x000F) << 10)
48 #define CONN_TRANSFORM_CTL_ENCODE(x) ((x & 0x000F) << 4)
49 #define CONN_TRANSFORM_DST_ENCODE(x) (x & 0x000F)
50 #define CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(x) ((x) ? 0x4000 : 0)
51 #define CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(x) ((x) ? 0x0100 : 0)
52 #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x) ((x) ? 0x8000 : 0)
53 #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x) ((x) ? 0x0200 : 0)
54
55 #define DRUM_TYPE_MASK 0x80000000
56
57 #define F_RGN_OPTION_SELFNONEXCLUSIVE 0x0001
58
59 #define F_WAVELINK_PHASE_MASTER 0x0001
60 #define F_WAVELINK_MULTICHANNEL 0x0002
61
62 #define F_WSMP_NO_TRUNCATION 0x0001
63 #define F_WSMP_NO_COMPRESSION 0x0002
64
65 #define MIDI_BANK_COARSE(x) ((x & 0x00007F00) >> 8) // CC0
66 #define MIDI_BANK_FINE(x) (x & 0x0000007F) // CC32
67 #define MIDI_BANK_MERGE(coarse, fine) ((((uint16_t) coarse) << 7) | fine) // CC0 + CC32
68 #define MIDI_BANK_ENCODE(coarse, fine) (((coarse & 0x0000007F) << 8) | (fine & 0x0000007F))
69
70 namespace DLS {
71
72 // *************** Connection ***************
73 // *
74
75 void Connection::Init(conn_block_t* Header) {
76 Source = (conn_src_t) Header->source;
77 Control = (conn_src_t) Header->control;
78 Destination = (conn_dst_t) Header->destination;
79 Scale = Header->scale;
80 SourceTransform = (conn_trn_t) CONN_TRANSFORM_SRC(Header->transform);
81 ControlTransform = (conn_trn_t) CONN_TRANSFORM_CTL(Header->transform);
82 DestinationTransform = (conn_trn_t) CONN_TRANSFORM_DST(Header->transform);
83 SourceInvert = CONN_TRANSFORM_INVERT_SRC(Header->transform);
84 SourceBipolar = CONN_TRANSFORM_BIPOLAR_SRC(Header->transform);
85 ControlInvert = CONN_TRANSFORM_INVERT_CTL(Header->transform);
86 ControlBipolar = CONN_TRANSFORM_BIPOLAR_CTL(Header->transform);
87 }
88
89 Connection::conn_block_t Connection::ToConnBlock() {
90 conn_block_t c;
91 c.source = Source;
92 c.control = Control;
93 c.destination = Destination;
94 c.scale = Scale;
95 c.transform = CONN_TRANSFORM_SRC_ENCODE(SourceTransform) |
96 CONN_TRANSFORM_CTL_ENCODE(ControlTransform) |
97 CONN_TRANSFORM_DST_ENCODE(DestinationTransform) |
98 CONN_TRANSFORM_INVERT_SRC_ENCODE(SourceInvert) |
99 CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(SourceBipolar) |
100 CONN_TRANSFORM_INVERT_CTL_ENCODE(ControlInvert) |
101 CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(ControlBipolar);
102 return c;
103 }
104
105
106
107 // *************** Articulation ***************
108 // *
109
110 /** @brief Constructor.
111 *
112 * Expects an 'artl' or 'art2' chunk to be given where the articulation
113 * connections will be read from.
114 *
115 * @param artl - pointer to an 'artl' or 'art2' chunk
116 * @throws Exception if no 'artl' or 'art2' chunk was given
117 */
118 Articulation::Articulation(RIFF::Chunk* artl) {
119 pArticulationCk = artl;
120 if (artl->GetChunkID() != CHUNK_ID_ART2 &&
121 artl->GetChunkID() != CHUNK_ID_ARTL) {
122 throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
123 }
124 HeaderSize = artl->ReadUint32();
125 Connections = artl->ReadUint32();
126 artl->SetPos(HeaderSize);
127
128 pConnections = new Connection[Connections];
129 Connection::conn_block_t connblock;
130 for (uint32_t i = 0; i < Connections; i++) {
131 artl->Read(&connblock.source, 1, 2);
132 artl->Read(&connblock.control, 1, 2);
133 artl->Read(&connblock.destination, 1, 2);
134 artl->Read(&connblock.transform, 1, 2);
135 artl->Read(&connblock.scale, 1, 4);
136 pConnections[i].Init(&connblock);
137 }
138 }
139
140 Articulation::~Articulation() {
141 if (pConnections) delete[] pConnections;
142 }
143
144 /**
145 * Apply articulation connections to the respective RIFF chunks. You
146 * have to call File::Save() to make changes persistent.
147 *
148 * @param pProgress - callback function for progress notification
149 */
150 void Articulation::UpdateChunks(progress_t* pProgress) {
151 const int iEntrySize = 12; // 12 bytes per connection block
152 pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
153 uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
154 store16(&pData[0], HeaderSize);
155 store16(&pData[2], Connections);
156 for (uint32_t i = 0; i < Connections; i++) {
157 Connection::conn_block_t c = pConnections[i].ToConnBlock();
158 store16(&pData[HeaderSize + i * iEntrySize], c.source);
159 store16(&pData[HeaderSize + i * iEntrySize + 2], c.control);
160 store16(&pData[HeaderSize + i * iEntrySize + 4], c.destination);
161 store16(&pData[HeaderSize + i * iEntrySize + 6], c.transform);
162 store32(&pData[HeaderSize + i * iEntrySize + 8], c.scale);
163 }
164 }
165
166
167
168 // *************** Articulator ***************
169 // *
170
171 Articulator::Articulator(RIFF::List* ParentList) {
172 pParentList = ParentList;
173 pArticulations = NULL;
174 }
175
176 Articulation* Articulator::GetFirstArticulation() {
177 if (!pArticulations) LoadArticulations();
178 if (!pArticulations) return NULL;
179 ArticulationsIterator = pArticulations->begin();
180 return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
181 }
182
183 Articulation* Articulator::GetNextArticulation() {
184 if (!pArticulations) return NULL;
185 ArticulationsIterator++;
186 return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
187 }
188
189 void Articulator::LoadArticulations() {
190 // prefer articulation level 2
191 RIFF::List* lart = pParentList->GetSubList(LIST_TYPE_LAR2);
192 if (!lart) lart = pParentList->GetSubList(LIST_TYPE_LART);
193 if (lart) {
194 uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2
195 : CHUNK_ID_ARTL;
196 RIFF::Chunk* art = lart->GetFirstSubChunk();
197 while (art) {
198 if (art->GetChunkID() == artCkType) {
199 if (!pArticulations) pArticulations = new ArticulationList;
200 pArticulations->push_back(new Articulation(art));
201 }
202 art = lart->GetNextSubChunk();
203 }
204 }
205 }
206
207 Articulator::~Articulator() {
208 if (pArticulations) {
209 ArticulationList::iterator iter = pArticulations->begin();
210 ArticulationList::iterator end = pArticulations->end();
211 while (iter != end) {
212 delete *iter;
213 iter++;
214 }
215 delete pArticulations;
216 }
217 }
218
219 /**
220 * Apply all articulations to the respective RIFF chunks. You have to
221 * call File::Save() to make changes persistent.
222 *
223 * @param pProgress - callback function for progress notification
224 */
225 void Articulator::UpdateChunks(progress_t* pProgress) {
226 if (pArticulations) {
227 ArticulationList::iterator iter = pArticulations->begin();
228 ArticulationList::iterator end = pArticulations->end();
229 for (; iter != end; ++iter) {
230 (*iter)->UpdateChunks(pProgress);
231 }
232 }
233 }
234
235 /**
236 * Not yet implemented in this version, since the .gig format does
237 * not need to copy DLS articulators and so far nobody used pure
238 * DLS instrument AFAIK.
239 */
240 void Articulator::CopyAssign(const Articulator* orig) {
241 //TODO: implement deep copy assignment for this class
242 }
243
244
245
246 // *************** Info ***************
247 // *
248
249 /** @brief Constructor.
250 *
251 * Initializes the info strings with values provided by an INFO list chunk.
252 *
253 * @param list - pointer to a list chunk which contains an INFO list chunk
254 */
255 Info::Info(RIFF::List* list) {
256 pFixedStringLengths = NULL;
257 pResourceListChunk = list;
258 if (list) {
259 RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
260 if (lstINFO) {
261 LoadString(CHUNK_ID_INAM, lstINFO, Name);
262 LoadString(CHUNK_ID_IARL, lstINFO, ArchivalLocation);
263 LoadString(CHUNK_ID_ICRD, lstINFO, CreationDate);
264 LoadString(CHUNK_ID_ICMT, lstINFO, Comments);
265 LoadString(CHUNK_ID_IPRD, lstINFO, Product);
266 LoadString(CHUNK_ID_ICOP, lstINFO, Copyright);
267 LoadString(CHUNK_ID_IART, lstINFO, Artists);
268 LoadString(CHUNK_ID_IGNR, lstINFO, Genre);
269 LoadString(CHUNK_ID_IKEY, lstINFO, Keywords);
270 LoadString(CHUNK_ID_IENG, lstINFO, Engineer);
271 LoadString(CHUNK_ID_ITCH, lstINFO, Technician);
272 LoadString(CHUNK_ID_ISFT, lstINFO, Software);
273 LoadString(CHUNK_ID_IMED, lstINFO, Medium);
274 LoadString(CHUNK_ID_ISRC, lstINFO, Source);
275 LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
276 LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
277 LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
278 }
279 }
280 }
281
282 Info::~Info() {
283 }
284
285 /**
286 * Forces specific Info fields to be of a fixed length when being saved
287 * to a file. By default the respective RIFF chunk of an Info field
288 * will have a size analogue to its actual string length. With this
289 * method however this behavior can be overridden, allowing to force an
290 * arbitrary fixed size individually for each Info field.
291 *
292 * This method is used as a workaround for the gig format, not for DLS.
293 *
294 * @param lengths - NULL terminated array of string_length_t elements
295 */
296 void Info::SetFixedStringLengths(const string_length_t* lengths) {
297 pFixedStringLengths = lengths;
298 }
299
300 /** @brief Load given INFO field.
301 *
302 * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO
303 * list chunk \a lstINFO and save value to \a s.
304 */
305 void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
306 RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
307 ::LoadString(ck, s); // function from helper.h
308 }
309
310 /** @brief Apply given INFO field to the respective chunk.
311 *
312 * Apply given info value to info chunk with ID \a ChunkID, which is a
313 * subchunk of INFO list chunk \a lstINFO. If the given chunk already
314 * exists, value \a s will be applied. Otherwise if it doesn't exist yet
315 * and either \a s or \a sDefault is not an empty string, such a chunk
316 * will be created and either \a s or \a sDefault will be applied
317 * (depending on which one is not an empty string, if both are not an
318 * empty string \a s will be preferred).
319 *
320 * @param ChunkID - 32 bit RIFF chunk ID of INFO subchunk
321 * @param lstINFO - parent (INFO) RIFF list chunk
322 * @param s - current value of info field
323 * @param sDefault - default value
324 */
325 void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
326 int size = 0;
327 if (pFixedStringLengths) {
328 for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
329 if (pFixedStringLengths[i].chunkId == ChunkID) {
330 size = pFixedStringLengths[i].length;
331 break;
332 }
333 }
334 }
335 RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
336 ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h
337 }
338
339 /** @brief Update chunks with current info values.
340 *
341 * Apply current INFO field values to the respective INFO chunks. You
342 * have to call File::Save() to make changes persistent.
343 *
344 * @param pProgress - callback function for progress notification
345 */
346 void Info::UpdateChunks(progress_t* pProgress) {
347 if (!pResourceListChunk) return;
348
349 // make sure INFO list chunk exists
350 RIFF::List* lstINFO = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
351
352 String defaultName = "";
353 String defaultCreationDate = "";
354 String defaultSoftware = "";
355 String defaultComments = "";
356
357 uint32_t resourceType = pResourceListChunk->GetListType();
358
359 if (!lstINFO) {
360 lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
361
362 // assemble default values
363 defaultName = "NONAME";
364
365 if (resourceType == RIFF_TYPE_DLS) {
366 // get current date
367 time_t now = time(NULL);
368 tm* pNowBroken = localtime(&now);
369 char buf[11];
370 strftime(buf, 11, "%F", pNowBroken);
371 defaultCreationDate = buf;
372
373 defaultComments = "Created with " + libraryName() + " " + libraryVersion();
374 }
375 if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
376 {
377 defaultSoftware = libraryName() + " " + libraryVersion();
378 }
379 }
380
381 // save values
382
383 SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
384 SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
385 SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
386 SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
387 SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
388 SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
389 SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
390 SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
391 SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
392 SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
393 SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
394 SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
395 SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
396 SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
397 SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
398 SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
399 SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
400 }
401
402 /**
403 * Make a deep copy of the Info object given by @a orig and assign it to
404 * this object.
405 *
406 * @param orig - original Info object to be copied from
407 */
408 void Info::CopyAssign(const Info* orig) {
409 Name = orig->Name;
410 ArchivalLocation = orig->ArchivalLocation;
411 CreationDate = orig->CreationDate;
412 Comments = orig->Comments;
413 Product = orig->Product;
414 Copyright = orig->Copyright;
415 Artists = orig->Artists;
416 Genre = orig->Genre;
417 Keywords = orig->Keywords;
418 Engineer = orig->Engineer;
419 Technician = orig->Technician;
420 Software = orig->Software;
421 Medium = orig->Medium;
422 Source = orig->Source;
423 SourceForm = orig->SourceForm;
424 Commissioned = orig->Commissioned;
425 Subject = orig->Subject;
426 //FIXME: hmm, is copying this pointer a good idea?
427 pFixedStringLengths = orig->pFixedStringLengths;
428 }
429
430
431
432 // *************** Resource ***************
433 // *
434
435 /** @brief Constructor.
436 *
437 * Initializes the 'Resource' object with values provided by a given
438 * INFO list chunk and a DLID chunk (the latter optional).
439 *
440 * @param Parent - pointer to parent 'Resource', NULL if this is
441 * the toplevel 'Resource' object
442 * @param lstResource - pointer to an INFO list chunk
443 */
444 Resource::Resource(Resource* Parent, RIFF::List* lstResource) {
445 pParent = Parent;
446 pResourceList = lstResource;
447
448 pInfo = new Info(lstResource);
449
450 RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
451 if (ckDLSID) {
452 pDLSID = new dlsid_t;
453 ckDLSID->Read(&pDLSID->ulData1, 1, 4);
454 ckDLSID->Read(&pDLSID->usData2, 1, 2);
455 ckDLSID->Read(&pDLSID->usData3, 1, 2);
456 ckDLSID->Read(pDLSID->abData, 8, 1);
457 }
458 else pDLSID = NULL;
459 }
460
461 Resource::~Resource() {
462 if (pDLSID) delete pDLSID;
463 if (pInfo) delete pInfo;
464 }
465
466 /** @brief Update chunks with current Resource data.
467 *
468 * Apply Resource data persistently below the previously given resource
469 * list chunk. This will currently only include the INFO data. The DLSID
470 * will not be applied at the moment (yet).
471 *
472 * You have to call File::Save() to make changes persistent.
473 *
474 * @param pProgress - callback function for progress notification
475 */
476 void Resource::UpdateChunks(progress_t* pProgress) {
477 pInfo->UpdateChunks(pProgress);
478
479 if (pDLSID) {
480 // make sure 'dlid' chunk exists
481 RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID);
482 if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16);
483 uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
484 // update 'dlid' chunk
485 store32(&pData[0], pDLSID->ulData1);
486 store16(&pData[4], pDLSID->usData2);
487 store16(&pData[6], pDLSID->usData3);
488 memcpy(&pData[8], pDLSID->abData, 8);
489 }
490 }
491
492 /**
493 * Generates a new DLSID for the resource.
494 */
495 void Resource::GenerateDLSID() {
496 #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
497
498 if (!pDLSID) pDLSID = new dlsid_t;
499
500 #ifdef WIN32
501
502 UUID uuid;
503 UuidCreate(&uuid);
504 pDLSID->ulData1 = uuid.Data1;
505 pDLSID->usData2 = uuid.Data2;
506 pDLSID->usData3 = uuid.Data3;
507 memcpy(pDLSID->abData, uuid.Data4, 8);
508
509 #elif defined(__APPLE__)
510
511 CFUUIDRef uuidRef = CFUUIDCreate(NULL);
512 CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef);
513 CFRelease(uuidRef);
514 pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24;
515 pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8;
516 pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8;
517 pDLSID->abData[0] = uuid.byte8;
518 pDLSID->abData[1] = uuid.byte9;
519 pDLSID->abData[2] = uuid.byte10;
520 pDLSID->abData[3] = uuid.byte11;
521 pDLSID->abData[4] = uuid.byte12;
522 pDLSID->abData[5] = uuid.byte13;
523 pDLSID->abData[6] = uuid.byte14;
524 pDLSID->abData[7] = uuid.byte15;
525 #else
526 uuid_t uuid;
527 uuid_generate(uuid);
528 pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
529 pDLSID->usData2 = uuid[4] | uuid[5] << 8;
530 pDLSID->usData3 = uuid[6] | uuid[7] << 8;
531 memcpy(pDLSID->abData, &uuid[8], 8);
532 #endif
533 #endif
534 }
535
536 /**
537 * Make a deep copy of the Resource object given by @a orig and assign it
538 * to this object.
539 *
540 * @param orig - original Resource object to be copied from
541 */
542 void Resource::CopyAssign(const Resource* orig) {
543 pInfo->CopyAssign(orig->pInfo);
544 }
545
546
547 // *************** Sampler ***************
548 // *
549
550 Sampler::Sampler(RIFF::List* ParentList) {
551 pParentList = ParentList;
552 RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
553 if (wsmp) {
554 uiHeaderSize = wsmp->ReadUint32();
555 UnityNote = wsmp->ReadUint16();
556 FineTune = wsmp->ReadInt16();
557 Gain = wsmp->ReadInt32();
558 SamplerOptions = wsmp->ReadUint32();
559 SampleLoops = wsmp->ReadUint32();
560 } else { // 'wsmp' chunk missing
561 uiHeaderSize = 20;
562 UnityNote = 60;
563 FineTune = 0; // +- 0 cents
564 Gain = 0; // 0 dB
565 SamplerOptions = F_WSMP_NO_COMPRESSION;
566 SampleLoops = 0;
567 }
568 NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;
569 NoSampleCompression = SamplerOptions & F_WSMP_NO_COMPRESSION;
570 pSampleLoops = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;
571 if (SampleLoops) {
572 wsmp->SetPos(uiHeaderSize);
573 for (uint32_t i = 0; i < SampleLoops; i++) {
574 wsmp->Read(pSampleLoops + i, 4, 4);
575 if (pSampleLoops[i].Size > sizeof(sample_loop_t)) { // if loop struct was extended
576 wsmp->SetPos(pSampleLoops[i].Size - sizeof(sample_loop_t), RIFF::stream_curpos);
577 }
578 }
579 }
580 }
581
582 Sampler::~Sampler() {
583 if (pSampleLoops) delete[] pSampleLoops;
584 }
585
586 void Sampler::SetGain(int32_t gain) {
587 Gain = gain;
588 }
589
590 /**
591 * Apply all sample player options to the respective RIFF chunk. You
592 * have to call File::Save() to make changes persistent.
593 *
594 * @param pProgress - callback function for progress notification
595 */
596 void Sampler::UpdateChunks(progress_t* pProgress) {
597 // make sure 'wsmp' chunk exists
598 RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
599 int wsmpSize = uiHeaderSize + SampleLoops * 16;
600 if (!wsmp) {
601 wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
602 } else if (wsmp->GetSize() != wsmpSize) {
603 wsmp->Resize(wsmpSize);
604 }
605 uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
606 // update headers size
607 store32(&pData[0], uiHeaderSize);
608 // update respective sampler options bits
609 SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
610 : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
611 SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
612 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
613 store16(&pData[4], UnityNote);
614 store16(&pData[6], FineTune);
615 store32(&pData[8], Gain);
616 store32(&pData[12], SamplerOptions);
617 store32(&pData[16], SampleLoops);
618 // update loop definitions
619 for (uint32_t i = 0; i < SampleLoops; i++) {
620 //FIXME: this does not handle extended loop structs correctly
621 store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
622 store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
623 store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
624 store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
625 }
626 }
627
628 /**
629 * Adds a new sample loop with the provided loop definition.
630 *
631 * @param pLoopDef - points to a loop definition that is to be copied
632 */
633 void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
634 sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
635 // copy old loops array
636 for (int i = 0; i < SampleLoops; i++) {
637 pNewLoops[i] = pSampleLoops[i];
638 }
639 // add the new loop
640 pNewLoops[SampleLoops] = *pLoopDef;
641 // auto correct size field
642 pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
643 // free the old array and update the member variables
644 if (SampleLoops) delete[] pSampleLoops;
645 pSampleLoops = pNewLoops;
646 SampleLoops++;
647 }
648
649 /**
650 * Deletes an existing sample loop.
651 *
652 * @param pLoopDef - pointer to existing loop definition
653 * @throws Exception - if given loop definition does not exist
654 */
655 void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
656 sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
657 // copy old loops array (skipping given loop)
658 for (int i = 0, o = 0; i < SampleLoops; i++) {
659 if (&pSampleLoops[i] == pLoopDef) continue;
660 if (o == SampleLoops - 1) {
661 delete[] pNewLoops;
662 throw Exception("Could not delete Sample Loop, because it does not exist");
663 }
664 pNewLoops[o] = pSampleLoops[i];
665 o++;
666 }
667 // free the old array and update the member variables
668 if (SampleLoops) delete[] pSampleLoops;
669 pSampleLoops = pNewLoops;
670 SampleLoops--;
671 }
672
673 /**
674 * Make a deep copy of the Sampler object given by @a orig and assign it
675 * to this object.
676 *
677 * @param orig - original Sampler object to be copied from
678 */
679 void Sampler::CopyAssign(const Sampler* orig) {
680 // copy trivial scalars
681 UnityNote = orig->UnityNote;
682 FineTune = orig->FineTune;
683 Gain = orig->Gain;
684 NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
685 NoSampleCompression = orig->NoSampleCompression;
686 SamplerOptions = orig->SamplerOptions;
687
688 // copy sample loops
689 if (SampleLoops) delete[] pSampleLoops;
690 pSampleLoops = new sample_loop_t[orig->SampleLoops];
691 memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
692 SampleLoops = orig->SampleLoops;
693 }
694
695
696 // *************** Sample ***************
697 // *
698
699 /** @brief Constructor.
700 *
701 * Load an existing sample or create a new one. A 'wave' list chunk must
702 * be given to this constructor. In case the given 'wave' list chunk
703 * contains a 'fmt' and 'data' chunk, the format and sample data will be
704 * loaded from there, otherwise default values will be used and those
705 * chunks will be created when File::Save() will be called later on.
706 *
707 * @param pFile - pointer to DLS::File where this sample is
708 * located (or will be located)
709 * @param waveList - pointer to 'wave' list chunk which is (or
710 * will be) associated with this sample
711 * @param WavePoolOffset - offset of this sample data from wave pool
712 * ('wvpl') list chunk
713 */
714 Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset) : Resource(pFile, waveList) {
715 pWaveList = waveList;
716 ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
717 pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
718 pCkData = waveList->GetSubChunk(CHUNK_ID_DATA);
719 if (pCkFormat) {
720 // common fields
721 FormatTag = pCkFormat->ReadUint16();
722 Channels = pCkFormat->ReadUint16();
723 SamplesPerSecond = pCkFormat->ReadUint32();
724 AverageBytesPerSecond = pCkFormat->ReadUint32();
725 BlockAlign = pCkFormat->ReadUint16();
726 // PCM format specific
727 if (FormatTag == DLS_WAVE_FORMAT_PCM) {
728 BitDepth = pCkFormat->ReadUint16();
729 FrameSize = (BitDepth / 8) * Channels;
730 } else { // unsupported sample data format
731 BitDepth = 0;
732 FrameSize = 0;
733 }
734 } else { // 'fmt' chunk missing
735 FormatTag = DLS_WAVE_FORMAT_PCM;
736 BitDepth = 16;
737 Channels = 1;
738 SamplesPerSecond = 44100;
739 AverageBytesPerSecond = (BitDepth / 8) * SamplesPerSecond * Channels;
740 FrameSize = (BitDepth / 8) * Channels;
741 BlockAlign = FrameSize;
742 }
743 SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
744 : 0
745 : 0;
746 }
747
748 /** @brief Destructor.
749 *
750 * Removes RIFF chunks associated with this Sample and frees all
751 * memory occupied by this sample.
752 */
753 Sample::~Sample() {
754 RIFF::List* pParent = pWaveList->GetParent();
755 pParent->DeleteSubChunk(pWaveList);
756 }
757
758 /**
759 * Make a deep copy of the Sample object given by @a orig (without the
760 * actual sample waveform data however) and assign it to this object.
761 *
762 * This is a special internal variant of CopyAssign() which only copies the
763 * most mandatory member variables. It will be called by gig::Sample
764 * descendent instead of CopyAssign() since gig::Sample has its own
765 * implementation to access and copy the actual sample waveform data.
766 *
767 * @param orig - original Sample object to be copied from
768 */
769 void Sample::CopyAssignCore(const Sample* orig) {
770 // handle base classes
771 Resource::CopyAssign(orig);
772 // handle actual own attributes of this class
773 FormatTag = orig->FormatTag;
774 Channels = orig->Channels;
775 SamplesPerSecond = orig->SamplesPerSecond;
776 AverageBytesPerSecond = orig->AverageBytesPerSecond;
777 BlockAlign = orig->BlockAlign;
778 BitDepth = orig->BitDepth;
779 SamplesTotal = orig->SamplesTotal;
780 FrameSize = orig->FrameSize;
781 }
782
783 /**
784 * Make a deep copy of the Sample object given by @a orig and assign it to
785 * this object.
786 *
787 * @param orig - original Sample object to be copied from
788 */
789 void Sample::CopyAssign(const Sample* orig) {
790 CopyAssignCore(orig);
791
792 // copy sample waveform data (reading directly from disc)
793 Resize(orig->GetSize());
794 char* buf = (char*) LoadSampleData();
795 Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
796 const file_offset_t restorePos = pOrig->pCkData->GetPos();
797 pOrig->SetPos(0);
798 for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
799 const int iReadAtOnce = 64*1024;
800 file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
801 n = pOrig->Read(&buf[i], n);
802 if (!n) break;
803 todo -= n;
804 i += (n * pOrig->FrameSize);
805 }
806 pOrig->pCkData->SetPos(restorePos);
807 }
808
809 /** @brief Load sample data into RAM.
810 *
811 * In case the respective 'data' chunk exists, the sample data will be
812 * loaded into RAM (if not done already) and a pointer to the data in
813 * RAM will be returned. If this is a new sample, you have to call
814 * Resize() with the desired sample size to create the mandatory RIFF
815 * chunk for the sample wave data.
816 *
817 * You can call LoadChunkData() again if you previously scheduled to
818 * enlarge the sample data RIFF chunk with a Resize() call. In that case
819 * the buffer will be enlarged to the new, scheduled size and you can
820 * already place the sample wave data to the buffer and finally call
821 * File::Save() to enlarge the sample data's chunk physically and write
822 * the new sample wave data in one rush. This approach is definitely
823 * recommended if you have to enlarge and write new sample data to a lot
824 * of samples.
825 *
826 * <b>Caution:</b> the buffer pointer will be invalidated once
827 * File::Save() was called. You have to call LoadChunkData() again to
828 * get a new, valid pointer whenever File::Save() was called.
829 *
830 * @returns pointer to sample data in RAM, NULL in case respective
831 * 'data' chunk does not exist (yet)
832 * @throws Exception if data buffer could not be enlarged
833 * @see Resize(), File::Save()
834 */
835 void* Sample::LoadSampleData() {
836 return (pCkData) ? pCkData->LoadChunkData() : NULL;
837 }
838
839 /** @brief Free sample data from RAM.
840 *
841 * In case sample data was previously successfully loaded into RAM with
842 * LoadSampleData(), this method will free the sample data from RAM.
843 */
844 void Sample::ReleaseSampleData() {
845 if (pCkData) pCkData->ReleaseChunkData();
846 }
847
848 /** @brief Returns sample size.
849 *
850 * Returns the sample wave form's data size (in sample points). This is
851 * actually the current, physical size (converted to sample points) of
852 * the RIFF chunk which encapsulates the sample's wave data. The
853 * returned value is dependant to the current FrameSize value.
854 *
855 * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM
856 * @see FrameSize, FormatTag
857 */
858 file_offset_t Sample::GetSize() const {
859 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
860 return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
861 }
862
863 /** @brief Resize sample.
864 *
865 * Resizes the sample's wave form data, that is the actual size of
866 * sample wave data possible to be written for this sample. This call
867 * will return immediately and just schedule the resize operation. You
868 * should call File::Save() to actually perform the resize operation(s)
869 * "physically" to the file. As this can take a while on large files, it
870 * is recommended to call Resize() first on all samples which have to be
871 * resized and finally to call File::Save() to perform all those resize
872 * operations in one rush.
873 *
874 * The actual size (in bytes) is dependant to the current FrameSize
875 * value. You may want to set FrameSize before calling Resize().
876 *
877 * <b>Caution:</b> You cannot directly write to enlarged samples before
878 * calling File::Save() as this might exceed the current sample's
879 * boundary!
880 *
881 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
882 * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
883 * other formats will fail!
884 *
885 * @param NewSize - new sample wave data size in sample points (must be
886 * greater than zero)
887 * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
888 * @throws Exception if \a NewSize is less than 1 or unrealistic large
889 * @see File::Save(), FrameSize, FormatTag
890 */
891 void Sample::Resize(file_offset_t NewSize) {
892 if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
893 if (NewSize < 1) throw Exception("Sample size must be at least one sample point");
894 if ((NewSize >> 48) != 0)
895 throw Exception("Unrealistic high DLS sample size detected");
896 const file_offset_t sizeInBytes = NewSize * FrameSize;
897 pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
898 if (pCkData) pCkData->Resize(sizeInBytes);
899 else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
900 }
901
902 /**
903 * Sets the position within the sample (in sample points, not in
904 * bytes). Use this method and <i>Read()</i> if you don't want to load
905 * the sample into RAM, thus for disk streaming.
906 *
907 * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
908 * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
909 * with other formats will fail!
910 *
911 * @param SampleCount number of sample points
912 * @param Whence to which relation \a SampleCount refers to
913 * @returns new position within the sample, 0 if
914 * FormatTag != DLS_WAVE_FORMAT_PCM
915 * @throws Exception if no data RIFF chunk was created for the sample yet
916 * @see FrameSize, FormatTag
917 */
918 file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
919 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
920 if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
921 file_offset_t orderedBytes = SampleCount * FrameSize;
922 file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
923 return (result == orderedBytes) ? SampleCount
924 : result / FrameSize;
925 }
926
927 /**
928 * Reads \a SampleCount number of sample points from the current
929 * position into the buffer pointed by \a pBuffer and increments the
930 * position within the sample. Use this method and <i>SetPos()</i> if you
931 * don't want to load the sample into RAM, thus for disk streaming.
932 *
933 * @param pBuffer destination buffer
934 * @param SampleCount number of sample points to read
935 */
936 file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
937 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
938 return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
939 }
940
941 /** @brief Write sample wave data.
942 *
943 * Writes \a SampleCount number of sample points from the buffer pointed
944 * by \a pBuffer and increments the position within the sample. Use this
945 * method to directly write the sample data to disk, i.e. if you don't
946 * want or cannot load the whole sample data into RAM.
947 *
948 * You have to Resize() the sample to the desired size and call
949 * File::Save() <b>before</b> using Write().
950 *
951 * @param pBuffer - source buffer
952 * @param SampleCount - number of sample points to write
953 * @throws Exception if current sample size is too small
954 * @see LoadSampleData()
955 */
956 file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
957 if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
958 if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
959 return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
960 }
961
962 /**
963 * Apply sample and its settings to the respective RIFF chunks. You have
964 * to call File::Save() to make changes persistent.
965 *
966 * @param pProgress - callback function for progress notification
967 * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
968 * was provided yet
969 */
970 void Sample::UpdateChunks(progress_t* pProgress) {
971 if (FormatTag != DLS_WAVE_FORMAT_PCM)
972 throw Exception("Could not save sample, only PCM format is supported");
973 // we refuse to do anything if not sample wave form was provided yet
974 if (!pCkData)
975 throw Exception("Could not save sample, there is no sample data to save");
976 // update chunks of base class as well
977 Resource::UpdateChunks(pProgress);
978 // make sure 'fmt' chunk exists
979 RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
980 if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
981 uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
982 // update 'fmt' chunk
983 store16(&pData[0], FormatTag);
984 store16(&pData[2], Channels);
985 store32(&pData[4], SamplesPerSecond);
986 store32(&pData[8], AverageBytesPerSecond);
987 store16(&pData[12], BlockAlign);
988 store16(&pData[14], BitDepth); // assuming PCM format
989 }
990
991
992
993 // *************** Region ***************
994 // *
995
996 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
997 pCkRegion = rgnList;
998
999 // articulation information
1000 RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1001 if (rgnh) {
1002 rgnh->Read(&KeyRange, 2, 2);
1003 rgnh->Read(&VelocityRange, 2, 2);
1004 FormatOptionFlags = rgnh->ReadUint16();
1005 KeyGroup = rgnh->ReadUint16();
1006 // Layer is optional
1007 if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
1008 rgnh->Read(&Layer, 1, sizeof(uint16_t));
1009 } else Layer = 0;
1010 } else { // 'rgnh' chunk is missing
1011 KeyRange.low = 0;
1012 KeyRange.high = 127;
1013 VelocityRange.low = 0;
1014 VelocityRange.high = 127;
1015 FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
1016 KeyGroup = 0;
1017 Layer = 0;
1018 }
1019 SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1020
1021 // sample information
1022 RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1023 if (wlnk) {
1024 WaveLinkOptionFlags = wlnk->ReadUint16();
1025 PhaseGroup = wlnk->ReadUint16();
1026 Channel = wlnk->ReadUint32();
1027 WavePoolTableIndex = wlnk->ReadUint32();
1028 } else { // 'wlnk' chunk is missing
1029 WaveLinkOptionFlags = 0;
1030 PhaseGroup = 0;
1031 Channel = 0; // mono
1032 WavePoolTableIndex = 0; // first entry in wave pool table
1033 }
1034 PhaseMaster = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
1035 MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
1036
1037 pSample = NULL;
1038 }
1039
1040 /** @brief Destructor.
1041 *
1042 * Removes RIFF chunks associated with this Region.
1043 */
1044 Region::~Region() {
1045 RIFF::List* pParent = pCkRegion->GetParent();
1046 pParent->DeleteSubChunk(pCkRegion);
1047 }
1048
1049 Sample* Region::GetSample() {
1050 if (pSample) return pSample;
1051 File* file = (File*) GetParent()->GetParent();
1052 uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1053 Sample* sample = file->GetFirstSample();
1054 while (sample) {
1055 if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1056 sample = file->GetNextSample();
1057 }
1058 return NULL;
1059 }
1060
1061 /**
1062 * Assign another sample to this Region.
1063 *
1064 * @param pSample - sample to be assigned
1065 */
1066 void Region::SetSample(Sample* pSample) {
1067 this->pSample = pSample;
1068 WavePoolTableIndex = 0; // we update this offset when we Save()
1069 }
1070
1071 /**
1072 * Modifies the key range of this Region and makes sure the respective
1073 * chunks are in correct order.
1074 *
1075 * @param Low - lower end of key range
1076 * @param High - upper end of key range
1077 */
1078 void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1079 KeyRange.low = Low;
1080 KeyRange.high = High;
1081
1082 // make sure regions are already loaded
1083 Instrument* pInstrument = (Instrument*) GetParent();
1084 if (!pInstrument->pRegions) pInstrument->LoadRegions();
1085 if (!pInstrument->pRegions) return;
1086
1087 // find the r which is the first one to the right of this region
1088 // at its new position
1089 Region* r = NULL;
1090 Region* prev_region = NULL;
1091 for (
1092 Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1093 iter != pInstrument->pRegions->end(); iter++
1094 ) {
1095 if ((*iter)->KeyRange.low > this->KeyRange.low) {
1096 r = *iter;
1097 break;
1098 }
1099 prev_region = *iter;
1100 }
1101
1102 // place this region before r if it's not already there
1103 if (prev_region != this) pInstrument->MoveRegion(this, r);
1104 }
1105
1106 /**
1107 * Apply Region settings to the respective RIFF chunks. You have to
1108 * call File::Save() to make changes persistent.
1109 *
1110 * @param pProgress - callback function for progress notification
1111 * @throws Exception - if the Region's sample could not be found
1112 */
1113 void Region::UpdateChunks(progress_t* pProgress) {
1114 // make sure 'rgnh' chunk exists
1115 RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1116 if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
1117 uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
1118 FormatOptionFlags = (SelfNonExclusive)
1119 ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
1120 : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
1121 // update 'rgnh' chunk
1122 store16(&pData[0], KeyRange.low);
1123 store16(&pData[2], KeyRange.high);
1124 store16(&pData[4], VelocityRange.low);
1125 store16(&pData[6], VelocityRange.high);
1126 store16(&pData[8], FormatOptionFlags);
1127 store16(&pData[10], KeyGroup);
1128 if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
1129
1130 // update chunks of base classes as well (but skip Resource,
1131 // as a rgn doesn't seem to have dlid and INFO chunks)
1132 Articulator::UpdateChunks(pProgress);
1133 Sampler::UpdateChunks(pProgress);
1134
1135 // make sure 'wlnk' chunk exists
1136 RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
1137 if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
1138 pData = (uint8_t*) wlnk->LoadChunkData();
1139 WaveLinkOptionFlags = (PhaseMaster)
1140 ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
1141 : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
1142 WaveLinkOptionFlags = (MultiChannel)
1143 ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
1144 : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
1145 // get sample's wave pool table index
1146 int index = -1;
1147 File* pFile = (File*) GetParent()->GetParent();
1148 if (pFile->pSamples) {
1149 File::SampleList::iterator iter = pFile->pSamples->begin();
1150 File::SampleList::iterator end = pFile->pSamples->end();
1151 for (int i = 0; iter != end; ++iter, i++) {
1152 if (*iter == pSample) {
1153 index = i;
1154 break;
1155 }
1156 }
1157 }
1158 WavePoolTableIndex = index;
1159 // update 'wlnk' chunk
1160 store16(&pData[0], WaveLinkOptionFlags);
1161 store16(&pData[2], PhaseGroup);
1162 store32(&pData[4], Channel);
1163 store32(&pData[8], WavePoolTableIndex);
1164 }
1165
1166 /**
1167 * Make a (semi) deep copy of the Region object given by @a orig and assign
1168 * it to this object.
1169 *
1170 * Note that the sample pointer referenced by @a orig is simply copied as
1171 * memory address. Thus the respective sample is shared, not duplicated!
1172 *
1173 * @param orig - original Region object to be copied from
1174 */
1175 void Region::CopyAssign(const Region* orig) {
1176 // handle base classes
1177 Resource::CopyAssign(orig);
1178 Articulator::CopyAssign(orig);
1179 Sampler::CopyAssign(orig);
1180 // handle actual own attributes of this class
1181 // (the trivial ones)
1182 VelocityRange = orig->VelocityRange;
1183 KeyGroup = orig->KeyGroup;
1184 Layer = orig->Layer;
1185 SelfNonExclusive = orig->SelfNonExclusive;
1186 PhaseMaster = orig->PhaseMaster;
1187 PhaseGroup = orig->PhaseGroup;
1188 MultiChannel = orig->MultiChannel;
1189 Channel = orig->Channel;
1190 // only take the raw sample reference if the two Region objects are
1191 // part of the same file
1192 if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1193 WavePoolTableIndex = orig->WavePoolTableIndex;
1194 pSample = orig->pSample;
1195 } else {
1196 WavePoolTableIndex = -1;
1197 pSample = NULL;
1198 }
1199 FormatOptionFlags = orig->FormatOptionFlags;
1200 WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1201 // handle the last, a bit sensible attribute
1202 SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1203 }
1204
1205
1206 // *************** Instrument ***************
1207 // *
1208
1209 /** @brief Constructor.
1210 *
1211 * Load an existing instrument definition or create a new one. An 'ins'
1212 * list chunk must be given to this constructor. In case this 'ins' list
1213 * chunk contains a 'insh' chunk, the instrument data fields will be
1214 * loaded from there, otherwise default values will be used and the
1215 * 'insh' chunk will be created once File::Save() was called.
1216 *
1217 * @param pFile - pointer to DLS::File where this instrument is
1218 * located (or will be located)
1219 * @param insList - pointer to 'ins' list chunk which is (or will be)
1220 * associated with this instrument
1221 */
1222 Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
1223 pCkInstrument = insList;
1224
1225 midi_locale_t locale;
1226 RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1227 if (insh) {
1228 Regions = insh->ReadUint32();
1229 insh->Read(&locale, 2, 4);
1230 } else { // 'insh' chunk missing
1231 Regions = 0;
1232 locale.bank = 0;
1233 locale.instrument = 0;
1234 }
1235
1236 MIDIProgram = locale.instrument;
1237 IsDrum = locale.bank & DRUM_TYPE_MASK;
1238 MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
1239 MIDIBankFine = (uint8_t) MIDI_BANK_FINE(locale.bank);
1240 MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
1241
1242 pRegions = NULL;
1243 }
1244
1245 Region* Instrument::GetFirstRegion() {
1246 if (!pRegions) LoadRegions();
1247 if (!pRegions) return NULL;
1248 RegionsIterator = pRegions->begin();
1249 return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1250 }
1251
1252 Region* Instrument::GetNextRegion() {
1253 if (!pRegions) return NULL;
1254 RegionsIterator++;
1255 return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1256 }
1257
1258 void Instrument::LoadRegions() {
1259 if (!pRegions) pRegions = new RegionList;
1260 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1261 if (lrgn) {
1262 uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2
1263 RIFF::List* rgn = lrgn->GetFirstSubList();
1264 while (rgn) {
1265 if (rgn->GetListType() == regionCkType) {
1266 pRegions->push_back(new Region(this, rgn));
1267 }
1268 rgn = lrgn->GetNextSubList();
1269 }
1270 }
1271 }
1272
1273 Region* Instrument::AddRegion() {
1274 if (!pRegions) LoadRegions();
1275 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1276 if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
1277 RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1278 Region* pNewRegion = new Region(this, rgn);
1279 pRegions->push_back(pNewRegion);
1280 Regions = (uint32_t) pRegions->size();
1281 return pNewRegion;
1282 }
1283
1284 void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1285 RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1286 lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1287
1288 pRegions->remove(pSrc);
1289 RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1290 pRegions->insert(iter, pSrc);
1291 }
1292
1293 void Instrument::DeleteRegion(Region* pRegion) {
1294 if (!pRegions) return;
1295 RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1296 if (iter == pRegions->end()) return;
1297 pRegions->erase(iter);
1298 Regions = (uint32_t) pRegions->size();
1299 delete pRegion;
1300 }
1301
1302 /**
1303 * Apply Instrument with all its Regions to the respective RIFF chunks.
1304 * You have to call File::Save() to make changes persistent.
1305 *
1306 * @param pProgress - callback function for progress notification
1307 * @throws Exception - on errors
1308 */
1309 void Instrument::UpdateChunks(progress_t* pProgress) {
1310 // first update base classes' chunks
1311 Resource::UpdateChunks(pProgress);
1312 Articulator::UpdateChunks(pProgress);
1313 // make sure 'insh' chunk exists
1314 RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1315 if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1316 uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1317 // update 'insh' chunk
1318 Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1319 midi_locale_t locale;
1320 locale.instrument = MIDIProgram;
1321 locale.bank = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1322 locale.bank = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
1323 MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
1324 store32(&pData[0], Regions);
1325 store32(&pData[4], locale.bank);
1326 store32(&pData[8], locale.instrument);
1327 // update Region's chunks
1328 if (!pRegions) return;
1329 RegionList::iterator iter = pRegions->begin();
1330 RegionList::iterator end = pRegions->end();
1331 for (int i = 0; iter != end; ++iter, ++i) {
1332 // divide local progress into subprogress
1333 progress_t subprogress;
1334 __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1335 // do the actual work
1336 (*iter)->UpdateChunks(&subprogress);
1337 }
1338 __notify_progress(pProgress, 1.0); // notify done
1339 }
1340
1341 /** @brief Destructor.
1342 *
1343 * Removes RIFF chunks associated with this Instrument and frees all
1344 * memory occupied by this instrument.
1345 */
1346 Instrument::~Instrument() {
1347 if (pRegions) {
1348 RegionList::iterator iter = pRegions->begin();
1349 RegionList::iterator end = pRegions->end();
1350 while (iter != end) {
1351 delete *iter;
1352 iter++;
1353 }
1354 delete pRegions;
1355 }
1356 // remove instrument's chunks
1357 RIFF::List* pParent = pCkInstrument->GetParent();
1358 pParent->DeleteSubChunk(pCkInstrument);
1359 }
1360
1361 void Instrument::CopyAssignCore(const Instrument* orig) {
1362 // handle base classes
1363 Resource::CopyAssign(orig);
1364 Articulator::CopyAssign(orig);
1365 // handle actual own attributes of this class
1366 // (the trivial ones)
1367 IsDrum = orig->IsDrum;
1368 MIDIBank = orig->MIDIBank;
1369 MIDIBankCoarse = orig->MIDIBankCoarse;
1370 MIDIBankFine = orig->MIDIBankFine;
1371 MIDIProgram = orig->MIDIProgram;
1372 }
1373
1374 /**
1375 * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1376 * it to this object.
1377 *
1378 * Note that all sample pointers referenced by @a orig are simply copied as
1379 * memory address. Thus the respective samples are shared, not duplicated!
1380 *
1381 * @param orig - original Instrument object to be copied from
1382 */
1383 void Instrument::CopyAssign(const Instrument* orig) {
1384 CopyAssignCore(orig);
1385 // delete all regions first
1386 while (Regions) DeleteRegion(GetFirstRegion());
1387 // now recreate and copy regions
1388 {
1389 RegionList::const_iterator it = orig->pRegions->begin();
1390 for (int i = 0; i < orig->Regions; ++i, ++it) {
1391 Region* dstRgn = AddRegion();
1392 //NOTE: Region does semi-deep copy !
1393 dstRgn->CopyAssign(*it);
1394 }
1395 }
1396 }
1397
1398
1399 // *************** File ***************
1400 // *
1401
1402 /** @brief Constructor.
1403 *
1404 * Default constructor, use this to create an empty DLS file. You have
1405 * to add samples, instruments and finally call Save() to actually write
1406 * a DLS file.
1407 */
1408 File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1409 pRIFF->SetByteOrder(RIFF::endian_little);
1410 bOwningRiff = true;
1411 pVersion = new version_t;
1412 pVersion->major = 0;
1413 pVersion->minor = 0;
1414 pVersion->release = 0;
1415 pVersion->build = 0;
1416
1417 Instruments = 0;
1418 WavePoolCount = 0;
1419 pWavePoolTable = NULL;
1420 pWavePoolTableHi = NULL;
1421 WavePoolHeaderSize = 8;
1422
1423 pSamples = NULL;
1424 pInstruments = NULL;
1425
1426 b64BitWavePoolOffsets = false;
1427 }
1428
1429 /** @brief Constructor.
1430 *
1431 * Load an existing DLS file.
1432 *
1433 * @param pRIFF - pointer to a RIFF file which is actually the DLS file
1434 * to load
1435 * @throws Exception if given file is not a DLS file, expected chunks
1436 * are missing
1437 */
1438 File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1439 if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1440 this->pRIFF = pRIFF;
1441 bOwningRiff = false;
1442 RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1443 if (ckVersion) {
1444 pVersion = new version_t;
1445 ckVersion->Read(pVersion, 4, 2);
1446 }
1447 else pVersion = NULL;
1448
1449 RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1450 if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1451 Instruments = colh->ReadUint32();
1452
1453 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1454 if (!ptbl) { // pool table is missing - this is probably an ".art" file
1455 WavePoolCount = 0;
1456 pWavePoolTable = NULL;
1457 pWavePoolTableHi = NULL;
1458 WavePoolHeaderSize = 8;
1459 b64BitWavePoolOffsets = false;
1460 } else {
1461 WavePoolHeaderSize = ptbl->ReadUint32();
1462 WavePoolCount = ptbl->ReadUint32();
1463 pWavePoolTable = new uint32_t[WavePoolCount];
1464 pWavePoolTableHi = new uint32_t[WavePoolCount];
1465 ptbl->SetPos(WavePoolHeaderSize);
1466
1467 // Check for 64 bit offsets (used in gig v3 files)
1468 b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1469 if (b64BitWavePoolOffsets) {
1470 for (int i = 0 ; i < WavePoolCount ; i++) {
1471 pWavePoolTableHi[i] = ptbl->ReadUint32();
1472 pWavePoolTable[i] = ptbl->ReadUint32();
1473 //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1474 //if (pWavePoolTable[i] & 0x80000000)
1475 // throw DLS::Exception("Files larger than 2 GB not yet supported");
1476 }
1477 } else { // conventional 32 bit offsets
1478 ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1479 for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1480 }
1481 }
1482
1483 pSamples = NULL;
1484 pInstruments = NULL;
1485 }
1486
1487 File::~File() {
1488 if (pInstruments) {
1489 InstrumentList::iterator iter = pInstruments->begin();
1490 InstrumentList::iterator end = pInstruments->end();
1491 while (iter != end) {
1492 delete *iter;
1493 iter++;
1494 }
1495 delete pInstruments;
1496 }
1497
1498 if (pSamples) {
1499 SampleList::iterator iter = pSamples->begin();
1500 SampleList::iterator end = pSamples->end();
1501 while (iter != end) {
1502 delete *iter;
1503 iter++;
1504 }
1505 delete pSamples;
1506 }
1507
1508 if (pWavePoolTable) delete[] pWavePoolTable;
1509 if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1510 if (pVersion) delete pVersion;
1511 for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1512 delete *i;
1513 if (bOwningRiff)
1514 delete pRIFF;
1515 }
1516
1517 Sample* File::GetFirstSample() {
1518 if (!pSamples) LoadSamples();
1519 if (!pSamples) return NULL;
1520 SamplesIterator = pSamples->begin();
1521 return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1522 }
1523
1524 Sample* File::GetNextSample() {
1525 if (!pSamples) return NULL;
1526 SamplesIterator++;
1527 return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1528 }
1529
1530 void File::LoadSamples() {
1531 if (!pSamples) pSamples = new SampleList;
1532 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1533 if (wvpl) {
1534 file_offset_t wvplFileOffset = wvpl->GetFilePos();
1535 RIFF::List* wave = wvpl->GetFirstSubList();
1536 while (wave) {
1537 if (wave->GetListType() == LIST_TYPE_WAVE) {
1538 file_offset_t waveFileOffset = wave->GetFilePos();
1539 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1540 }
1541 wave = wvpl->GetNextSubList();
1542 }
1543 }
1544 else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)
1545 RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1546 if (dwpl) {
1547 file_offset_t dwplFileOffset = dwpl->GetFilePos();
1548 RIFF::List* wave = dwpl->GetFirstSubList();
1549 while (wave) {
1550 if (wave->GetListType() == LIST_TYPE_WAVE) {
1551 file_offset_t waveFileOffset = wave->GetFilePos();
1552 pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1553 }
1554 wave = dwpl->GetNextSubList();
1555 }
1556 }
1557 }
1558 }
1559
1560 /** @brief Add a new sample.
1561 *
1562 * This will create a new Sample object for the DLS file. You have to
1563 * call Save() to make this persistent to the file.
1564 *
1565 * @returns pointer to new Sample object
1566 */
1567 Sample* File::AddSample() {
1568 if (!pSamples) LoadSamples();
1569 __ensureMandatoryChunksExist();
1570 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1571 // create new Sample object and its respective 'wave' list chunk
1572 RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1573 Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1574 pSamples->push_back(pSample);
1575 return pSample;
1576 }
1577
1578 /** @brief Delete a sample.
1579 *
1580 * This will delete the given Sample object from the DLS file. You have
1581 * to call Save() to make this persistent to the file.
1582 *
1583 * @param pSample - sample to delete
1584 */
1585 void File::DeleteSample(Sample* pSample) {
1586 if (!pSamples) return;
1587 SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1588 if (iter == pSamples->end()) return;
1589 pSamples->erase(iter);
1590 delete pSample;
1591 }
1592
1593 Instrument* File::GetFirstInstrument() {
1594 if (!pInstruments) LoadInstruments();
1595 if (!pInstruments) return NULL;
1596 InstrumentsIterator = pInstruments->begin();
1597 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1598 }
1599
1600 Instrument* File::GetNextInstrument() {
1601 if (!pInstruments) return NULL;
1602 InstrumentsIterator++;
1603 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1604 }
1605
1606 void File::LoadInstruments() {
1607 if (!pInstruments) pInstruments = new InstrumentList;
1608 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1609 if (lstInstruments) {
1610 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1611 while (lstInstr) {
1612 if (lstInstr->GetListType() == LIST_TYPE_INS) {
1613 pInstruments->push_back(new Instrument(this, lstInstr));
1614 }
1615 lstInstr = lstInstruments->GetNextSubList();
1616 }
1617 }
1618 }
1619
1620 /** @brief Add a new instrument definition.
1621 *
1622 * This will create a new Instrument object for the DLS file. You have
1623 * to call Save() to make this persistent to the file.
1624 *
1625 * @returns pointer to new Instrument object
1626 */
1627 Instrument* File::AddInstrument() {
1628 if (!pInstruments) LoadInstruments();
1629 __ensureMandatoryChunksExist();
1630 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1631 RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1632 Instrument* pInstrument = new Instrument(this, lstInstr);
1633 pInstruments->push_back(pInstrument);
1634 return pInstrument;
1635 }
1636
1637 /** @brief Delete an instrument.
1638 *
1639 * This will delete the given Instrument object from the DLS file. You
1640 * have to call Save() to make this persistent to the file.
1641 *
1642 * @param pInstrument - instrument to delete
1643 */
1644 void File::DeleteInstrument(Instrument* pInstrument) {
1645 if (!pInstruments) return;
1646 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1647 if (iter == pInstruments->end()) return;
1648 pInstruments->erase(iter);
1649 delete pInstrument;
1650 }
1651
1652 /**
1653 * Returns extension file of given index. Extension files are used
1654 * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1655 * of certain operating systems in general. In this case, instead of just
1656 * using one file, the content is spread among several files with similar
1657 * file name scheme. This is especially used by some GigaStudio sound
1658 * libraries.
1659 *
1660 * @param index - index of extension file
1661 * @returns sought extension file, NULL if index out of bounds
1662 * @see GetFileName()
1663 */
1664 RIFF::File* File::GetExtensionFile(int index) {
1665 if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1666 std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1667 for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1668 if (i == index) return *iter;
1669 return NULL;
1670 }
1671
1672 /** @brief File name of this DLS file.
1673 *
1674 * This method returns the file name as it was provided when loading
1675 * the respective DLS file. However in case the File object associates
1676 * an empty, that is new DLS file, which was not yet saved to disk,
1677 * this method will return an empty string.
1678 *
1679 * @see GetExtensionFile()
1680 */
1681 String File::GetFileName() {
1682 return pRIFF->GetFileName();
1683 }
1684
1685 /**
1686 * You may call this method store a future file name, so you don't have to
1687 * to pass it to the Save() call later on.
1688 */
1689 void File::SetFileName(const String& name) {
1690 pRIFF->SetFileName(name);
1691 }
1692
1693 /**
1694 * Apply all the DLS file's current instruments, samples and settings to
1695 * the respective RIFF chunks. You have to call Save() to make changes
1696 * persistent.
1697 *
1698 * @param pProgress - callback function for progress notification
1699 * @throws Exception - on errors
1700 */
1701 void File::UpdateChunks(progress_t* pProgress) {
1702 // first update base class's chunks
1703 Resource::UpdateChunks(pProgress);
1704
1705 // if version struct exists, update 'vers' chunk
1706 if (pVersion) {
1707 RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1708 if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1709 uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1710 store16(&pData[0], pVersion->minor);
1711 store16(&pData[2], pVersion->major);
1712 store16(&pData[4], pVersion->build);
1713 store16(&pData[6], pVersion->release);
1714 }
1715
1716 // update 'colh' chunk
1717 Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1718 RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1719 if (!colh) colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1720 uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1721 store32(pData, Instruments);
1722
1723 // update instrument's chunks
1724 if (pInstruments) {
1725 // divide local progress into subprogress
1726 progress_t subprogress;
1727 __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1728
1729 // do the actual work
1730 InstrumentList::iterator iter = pInstruments->begin();
1731 InstrumentList::iterator end = pInstruments->end();
1732 for (int i = 0; iter != end; ++iter, ++i) {
1733 // divide subprogress into sub-subprogress
1734 progress_t subsubprogress;
1735 __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1736 // do the actual work
1737 (*iter)->UpdateChunks(&subsubprogress);
1738 }
1739
1740 __notify_progress(&subprogress, 1.0); // notify subprogress done
1741 }
1742
1743 // update 'ptbl' chunk
1744 const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
1745 int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1746 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1747 if (!ptbl) ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
1748 int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1749 ptbl->Resize(iPtblSize);
1750 pData = (uint8_t*) ptbl->LoadChunkData();
1751 WavePoolCount = iSamples;
1752 store32(&pData[4], WavePoolCount);
1753 // we actually update the sample offsets in the pool table when we Save()
1754 memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1755
1756 // update sample's chunks
1757 if (pSamples) {
1758 // divide local progress into subprogress
1759 progress_t subprogress;
1760 __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1761
1762 // do the actual work
1763 SampleList::iterator iter = pSamples->begin();
1764 SampleList::iterator end = pSamples->end();
1765 for (int i = 0; iter != end; ++iter, ++i) {
1766 // divide subprogress into sub-subprogress
1767 progress_t subsubprogress;
1768 __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1769 // do the actual work
1770 (*iter)->UpdateChunks(&subsubprogress);
1771 }
1772
1773 __notify_progress(&subprogress, 1.0); // notify subprogress done
1774 }
1775
1776 // the RIFF file to be written might now been grown >= 4GB or might
1777 // been shrunk < 4GB, so we might need to update the wave pool offset
1778 // size and thus accordingly we would need to resize the wave pool
1779 // chunk
1780 const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
1781 const bool bRequires64Bit = (finalFileSize >> 32) != 0;
1782 if (b64BitWavePoolOffsets != bRequires64Bit) {
1783 b64BitWavePoolOffsets = bRequires64Bit;
1784 iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1785 iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1786 ptbl->Resize(iPtblSize);
1787 }
1788
1789 __notify_progress(pProgress, 1.0); // notify done
1790 }
1791
1792 /** @brief Save changes to another file.
1793 *
1794 * Make all changes persistent by writing them to another file.
1795 * <b>Caution:</b> this method is optimized for writing to
1796 * <b>another</b> file, do not use it to save the changes to the same
1797 * file! Use Save() (without path argument) in that case instead!
1798 * Ignoring this might result in a corrupted file!
1799 *
1800 * After calling this method, this File object will be associated with
1801 * the new file (given by \a Path) afterwards.
1802 *
1803 * @param Path - path and file name where everything should be written to
1804 * @param pProgress - optional: callback function for progress notification
1805 */
1806 void File::Save(const String& Path, progress_t* pProgress) {
1807 {
1808 // divide local progress into subprogress
1809 progress_t subprogress;
1810 __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1811 // do the actual work
1812 UpdateChunks(&subprogress);
1813
1814 }
1815 {
1816 // divide local progress into subprogress
1817 progress_t subprogress;
1818 __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1819 // do the actual work
1820 pRIFF->Save(Path, &subprogress);
1821 }
1822 UpdateFileOffsets();
1823 __notify_progress(pProgress, 1.0); // notify done
1824 }
1825
1826 /** @brief Save changes to same file.
1827 *
1828 * Make all changes persistent by writing them to the actual (same)
1829 * file. The file might temporarily grow to a higher size than it will
1830 * have at the end of the saving process.
1831 *
1832 * @param pProgress - optional: callback function for progress notification
1833 * @throws RIFF::Exception if any kind of IO error occurred
1834 * @throws DLS::Exception if any kind of DLS specific error occurred
1835 */
1836 void File::Save(progress_t* pProgress) {
1837 {
1838 // divide local progress into subprogress
1839 progress_t subprogress;
1840 __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1841 // do the actual work
1842 UpdateChunks(&subprogress);
1843 }
1844 {
1845 // divide local progress into subprogress
1846 progress_t subprogress;
1847 __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1848 // do the actual work
1849 pRIFF->Save(&subprogress);
1850 }
1851 UpdateFileOffsets();
1852 __notify_progress(pProgress, 1.0); // notify done
1853 }
1854
1855 /** @brief Updates all file offsets stored all over the file.
1856 *
1857 * This virtual method is called whenever the overall file layout has been
1858 * changed (i.e. file or individual RIFF chunks have been resized). It is
1859 * then the responsibility of this method to update all file offsets stored
1860 * in the file format. For example samples are referenced by instruments by
1861 * file offsets. The gig format also stores references to instrument
1862 * scripts as file offsets, and thus it overrides this method to update
1863 * those file offsets as well.
1864 */
1865 void File::UpdateFileOffsets() {
1866 __UpdateWavePoolTableChunk();
1867 }
1868
1869 /**
1870 * Checks if all (for DLS) mandatory chunks exist, if not they will be
1871 * created. Note that those chunks will not be made persistent until
1872 * Save() was called.
1873 */
1874 void File::__ensureMandatoryChunksExist() {
1875 // enusre 'lins' list chunk exists (mandatory for instrument definitions)
1876 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1877 if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
1878 // ensure 'ptbl' chunk exists (mandatory for samples)
1879 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1880 if (!ptbl) {
1881 const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1882 ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
1883 }
1884 // enusre 'wvpl' list chunk exists (mandatory for samples)
1885 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1886 if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
1887 }
1888
1889 /**
1890 * Updates (persistently) the wave pool table with offsets to all
1891 * currently available samples. <b>Caution:</b> this method assumes the
1892 * 'ptbl' chunk to be already of the correct size and the file to be
1893 * writable, so usually this method is only called after a Save() call.
1894 *
1895 * @throws Exception - if 'ptbl' chunk is too small (should only occur
1896 * if there's a bug)
1897 */
1898 void File::__UpdateWavePoolTableChunk() {
1899 __UpdateWavePoolTable();
1900 RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1901 const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1902 // check if 'ptbl' chunk is large enough
1903 WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
1904 const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1905 if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1906 // save the 'ptbl' chunk's current read/write position
1907 file_offset_t ullOriginalPos = ptbl->GetPos();
1908 // update headers
1909 ptbl->SetPos(0);
1910 uint32_t tmp = WavePoolHeaderSize;
1911 ptbl->WriteUint32(&tmp);
1912 tmp = WavePoolCount;
1913 ptbl->WriteUint32(&tmp);
1914 // update offsets
1915 ptbl->SetPos(WavePoolHeaderSize);
1916 if (b64BitWavePoolOffsets) {
1917 for (int i = 0 ; i < WavePoolCount ; i++) {
1918 tmp = pWavePoolTableHi[i];
1919 ptbl->WriteUint32(&tmp);
1920 tmp = pWavePoolTable[i];
1921 ptbl->WriteUint32(&tmp);
1922 }
1923 } else { // conventional 32 bit offsets
1924 for (int i = 0 ; i < WavePoolCount ; i++) {
1925 tmp = pWavePoolTable[i];
1926 ptbl->WriteUint32(&tmp);
1927 }
1928 }
1929 // restore 'ptbl' chunk's original read/write position
1930 ptbl->SetPos(ullOriginalPos);
1931 }
1932
1933 /**
1934 * Updates the wave pool table with offsets to all currently available
1935 * samples. <b>Caution:</b> this method assumes the 'wvpl' list chunk
1936 * exists already.
1937 */
1938 void File::__UpdateWavePoolTable() {
1939 WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
1940 // resize wave pool table arrays
1941 if (pWavePoolTable) delete[] pWavePoolTable;
1942 if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1943 pWavePoolTable = new uint32_t[WavePoolCount];
1944 pWavePoolTableHi = new uint32_t[WavePoolCount];
1945 if (!pSamples) return;
1946 // update offsets int wave pool table
1947 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1948 uint64_t wvplFileOffset = wvpl->GetFilePos();
1949 if (b64BitWavePoolOffsets) {
1950 SampleList::iterator iter = pSamples->begin();
1951 SampleList::iterator end = pSamples->end();
1952 for (int i = 0 ; iter != end ; ++iter, i++) {
1953 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1954 (*iter)->ullWavePoolOffset = _64BitOffset;
1955 pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1956 pWavePoolTable[i] = (uint32_t) _64BitOffset;
1957 }
1958 } else { // conventional 32 bit offsets
1959 SampleList::iterator iter = pSamples->begin();
1960 SampleList::iterator end = pSamples->end();
1961 for (int i = 0 ; iter != end ; ++iter, i++) {
1962 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1963 (*iter)->ullWavePoolOffset = _64BitOffset;
1964 pWavePoolTable[i] = (uint32_t) _64BitOffset;
1965 }
1966 }
1967 }
1968
1969
1970
1971 // *************** Exception ***************
1972 // *
1973
1974 Exception::Exception() : RIFF::Exception() {
1975 }
1976
1977 Exception::Exception(String format, ...) : RIFF::Exception() {
1978 va_list arg;
1979 va_start(arg, format);
1980 Message = assemble(format, arg);
1981 va_end(arg);
1982 }
1983
1984 Exception::Exception(String format, va_list arg) : RIFF::Exception() {
1985 Message = assemble(format, arg);
1986 }
1987
1988 void Exception::PrintMessage() {
1989 std::cout << "DLS::Exception: " << Message << std::endl;
1990 }
1991
1992
1993 // *************** functions ***************
1994 // *
1995
1996 /**
1997 * Returns the name of this C++ library. This is usually "libgig" of
1998 * course. This call is equivalent to RIFF::libraryName() and
1999 * gig::libraryName().
2000 */
2001 String libraryName() {
2002 return PACKAGE;
2003 }
2004
2005 /**
2006 * Returns version of this C++ library. This call is equivalent to
2007 * RIFF::libraryVersion() and gig::libraryVersion().
2008 */
2009 String libraryVersion() {
2010 return VERSION;
2011 }
2012
2013 } // namespace DLS

  ViewVC Help
Powered by ViewVC