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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3922 - (hide annotations) (download)
Mon Jun 14 10:33:29 2021 UTC (2 years, 10 months ago) by schoenebeck
File size: 100185 byte(s)
* DLS: Use GetSubChunkAt() instead of GetFirstSubChunk() /
  GetNextSubChunk() in entire DLS.cpp file.

* DLS: Use GetSubListAt() instead of GetFirstSubList() / GetNextSubList()
  in entire DLS.cpp file.

* Bumped version (4.3.0.svn12).

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

  ViewVC Help
Powered by ViewVC