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

Legend:
Removed from v.384  
changed lines
  Added in v.1416

  ViewVC Help
Powered by ViewVC