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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3481 - (hide annotations) (download)
Fri Feb 22 12:12:50 2019 UTC (5 years, 2 months ago) by schoenebeck
File size: 98643 byte(s)
* gig.h, gig.cpp: Added File::GetRiffFile() method.
* DLS.h, DLS.cpp: Added File::GetRiffFile() method.
* sf2.h, sf2.cpp: Added Sample::GetFile() and
  File::GetRiffFile() methods.
* RIFF.h, RIFF.cpp: Added a 2nd (overridden)
  progress_t::subdivide() method which allows a more
  fine graded control into which portions the subtasks
  are divided to.
* RIFF Fix: API doc comment for Chunk::GetFilePos() was
  completely wrong.
* Bumped version (4.1.0.svn14).

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

  ViewVC Help
Powered by ViewVC