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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.2  
changed lines
  Added in v.1953

  ViewVC Help
Powered by ViewVC