/[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 1154 by schoenebeck, Wed Apr 11 16:33:56 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    #include "helper.h"
29    
30    // macros to decode connection transforms
31    #define CONN_TRANSFORM_SRC(x)                   ((x >> 10) & 0x000F)
32    #define CONN_TRANSFORM_CTL(x)                   ((x >> 4) & 0x000F)
33    #define CONN_TRANSFORM_DST(x)                   (x & 0x000F)
34    #define CONN_TRANSFORM_BIPOLAR_SRC(x)   (x & 0x4000)
35    #define CONN_TRANSFORM_BIPOLAR_CTL(x)   (x & 0x0100)
36    #define CONN_TRANSFORM_INVERT_SRC(x)    (x & 0x8000)
37    #define CONN_TRANSFORM_INVERT_CTL(x)    (x & 0x0200)
38    
39    // macros to encode connection transforms
40    #define CONN_TRANSFORM_SRC_ENCODE(x)                    ((x & 0x000F) << 10)
41    #define CONN_TRANSFORM_CTL_ENCODE(x)                    ((x & 0x000F) << 4)
42    #define CONN_TRANSFORM_DST_ENCODE(x)                    (x & 0x000F)
43    #define CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(x)    ((x) ? 0x4000 : 0)
44    #define CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(x)    ((x) ? 0x0100 : 0)
45    #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x)             ((x) ? 0x8000 : 0)
46    #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x)             ((x) ? 0x0200 : 0)
47    
48    #define DRUM_TYPE_MASK                  0x80000000
49    
50    #define F_RGN_OPTION_SELFNONEXCLUSIVE   0x0001
51    
52    #define F_WAVELINK_PHASE_MASTER         0x0001
53    #define F_WAVELINK_MULTICHANNEL         0x0002
54    
55    #define F_WSMP_NO_TRUNCATION            0x0001
56    #define F_WSMP_NO_COMPRESSION           0x0002
57    
58    #define MIDI_BANK_COARSE(x)             ((x & 0x00007F00) >> 8)                 // CC0
59    #define MIDI_BANK_FINE(x)               (x & 0x0000007F)                        // CC32
60    #define MIDI_BANK_MERGE(coarse, fine)   ((((uint16_t) coarse) << 7) | fine)     // CC0 + CC32
61    #define MIDI_BANK_ENCODE(coarse, fine)  (((coarse & 0x0000007F) << 8) | (fine & 0x0000007F))
62    
63  namespace DLS {  namespace DLS {
64    
65  // *************** Connection  ***************  // *************** Connection  ***************
# Line 42  namespace DLS { Line 79  namespace DLS {
79          ControlBipolar       = CONN_TRANSFORM_BIPOLAR_CTL(Header->transform);          ControlBipolar       = CONN_TRANSFORM_BIPOLAR_CTL(Header->transform);
80      }      }
81    
82        Connection::conn_block_t Connection::ToConnBlock() {
83            conn_block_t c;
84            c.source = Source;
85            c.control = Control;
86            c.destination = Destination;
87            c.scale = Scale;
88            c.transform = CONN_TRANSFORM_SRC_ENCODE(SourceTransform) |
89                          CONN_TRANSFORM_CTL_ENCODE(ControlTransform) |
90                          CONN_TRANSFORM_DST_ENCODE(DestinationTransform) |
91                          CONN_TRANSFORM_INVERT_SRC_ENCODE(SourceInvert) |
92                          CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(SourceBipolar) |
93                          CONN_TRANSFORM_INVERT_CTL_ENCODE(ControlInvert) |
94                          CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(ControlBipolar);
95            return c;
96        }
97    
98    
99    
100  // *************** Articulation  ***************  // *************** Articulation  ***************
101  // *  // *
102    
103      Articulation::Articulation(RIFF::List* artList) {      /** @brief Constructor.
104          if (artList->GetListType() != LIST_TYPE_ART2 &&       *
105              artList->GetListType() != LIST_TYPE_ART1) {       * Expects an 'artl' or 'art2' chunk to be given where the articulation
106                throw DLS::Exception("<art1-list> or <art2-list> chunk expected");       * connections will be read from.
107          }       *
108          uint32_t headerSize = artList->ReadUint32();       * @param artl - pointer to an 'artl' or 'art2' chunk
109          Connections         = artList->ReadUint32();       * @throws Exception if no 'artl' or 'art2' chunk was given
110          artList->SetPos(headerSize);       */
111        Articulation::Articulation(RIFF::Chunk* artl) {
112            pArticulationCk = artl;
113            if (artl->GetChunkID() != CHUNK_ID_ART2 &&
114                artl->GetChunkID() != CHUNK_ID_ARTL) {
115                  throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
116            }
117            HeaderSize  = artl->ReadUint32();
118            Connections = artl->ReadUint32();
119            artl->SetPos(HeaderSize);
120    
121          pConnections = new Connection[Connections];          pConnections = new Connection[Connections];
122          Connection::conn_block_t connblock;          Connection::conn_block_t connblock;
123          for (uint32_t i = 0; i <= Connections; i++) {          for (uint32_t i = 0; i < Connections; i++) {
124              artList->Read(&connblock.source, 1, 2);              artl->Read(&connblock.source, 1, 2);
125              artList->Read(&connblock.control, 1, 2);              artl->Read(&connblock.control, 1, 2);
126              artList->Read(&connblock.destination, 1, 2);              artl->Read(&connblock.destination, 1, 2);
127              artList->Read(&connblock.transform, 1, 2);              artl->Read(&connblock.transform, 1, 2);
128              artList->Read(&connblock.scale, 1, 4);              artl->Read(&connblock.scale, 1, 4);
129              pConnections[i].Init(&connblock);              pConnections[i].Init(&connblock);
130          }          }
131      }      }
# Line 72  namespace DLS { Line 134  namespace DLS {
134         if (pConnections) delete[] pConnections;         if (pConnections) delete[] pConnections;
135      }      }
136    
137        /**
138         * Apply articulation connections to the respective RIFF chunks. You
139         * have to call File::Save() to make changes persistent.
140         */
141        void Articulation::UpdateChunks() {
142            const int iEntrySize = 12; // 12 bytes per connection block
143            pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
144            uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
145            memcpy(&pData[0], &HeaderSize, 2);
146            memcpy(&pData[2], &Connections, 2);
147            for (uint32_t i = 0; i < Connections; i++) {
148                Connection::conn_block_t c = pConnections[i].ToConnBlock();
149                memcpy(&pData[HeaderSize + i * iEntrySize],     &c.source, 2);
150                memcpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 2);
151                memcpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 2);
152                memcpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 2);
153                memcpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 4);
154            }
155        }
156    
157    
158    
159  // *************** Articulator  ***************  // *************** Articulator  ***************
# Line 100  namespace DLS { Line 182  namespace DLS {
182          RIFF::List* lart = pParentList->GetSubList(LIST_TYPE_LAR2);          RIFF::List* lart = pParentList->GetSubList(LIST_TYPE_LAR2);
183          if (!lart)  lart = pParentList->GetSubList(LIST_TYPE_LART);          if (!lart)  lart = pParentList->GetSubList(LIST_TYPE_LART);
184          if (lart) {          if (lart) {
185              uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? LIST_TYPE_ART2              uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2
186                                                                           : LIST_TYPE_ART1;                                                                           : CHUNK_ID_ARTL;
187              RIFF::List* art = lart->GetFirstSubList();              RIFF::Chunk* art = lart->GetFirstSubChunk();
188              while (art) {              while (art) {
189                  if (art->GetListType() == artCkType) {                  if (art->GetChunkID() == artCkType) {
190                      if (!pArticulations) pArticulations = new ArticulationList;                      if (!pArticulations) pArticulations = new ArticulationList;
191                      pArticulations->push_back(new Articulation(art));                      pArticulations->push_back(new Articulation(art));
192                  }                  }
193                  art = lart->GetNextSubList();                  art = lart->GetNextSubChunk();
194              }              }
195          }          }
196      }      }
# Line 125  namespace DLS { Line 207  namespace DLS {
207          }          }
208      }      }
209    
210        /**
211         * Apply all articulations to the respective RIFF chunks. You have to
212         * call File::Save() to make changes persistent.
213         */
214        void Articulator::UpdateChunks() {
215            if (pArticulations) {
216                ArticulationList::iterator iter = pArticulations->begin();
217                ArticulationList::iterator end  = pArticulations->end();
218                for (; iter != end; ++iter) {
219                    (*iter)->UpdateChunks();
220                }
221            }
222        }
223    
224    
225    
226  // *************** Info  ***************  // *************** Info  ***************
227  // *  // *
228    
229        /** @brief Constructor.
230         *
231         * Initializes the info strings with values provided by an INFO list chunk.
232         *
233         * @param list - pointer to a list chunk which contains an INFO list chunk
234         */
235      Info::Info(RIFF::List* list) {      Info::Info(RIFF::List* list) {
236            UseFixedLengthStrings = false;
237            pResourceListChunk = list;
238          if (list) {          if (list) {
239              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
240              if (lstINFO) {              if (lstINFO) {
# Line 150  namespace DLS { Line 254  namespace DLS {
254                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);
255                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
256                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
257                    LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
258              }              }
259          }          }
260      }      }
261    
262        Info::~Info() {
263        }
264    
265        /** @brief Load given INFO field.
266         *
267         * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO
268         * list chunk \a lstINFO and save value to \a s.
269         */
270        void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
271            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
272            ::LoadString(ck, s); // function from helper.h
273        }
274    
275        /** @brief Apply given INFO field to the respective chunk.
276         *
277         * Apply given info value to info chunk with ID \a ChunkID, which is a
278         * subchunk of INFO list chunk \a lstINFO. If the given chunk already
279         * exists, value \a s will be applied. Otherwise if it doesn't exist yet
280         * and either \a s or \a sDefault is not an empty string, such a chunk
281         * will be created and either \a s or \a sDefault will be applied
282         * (depending on which one is not an empty string, if both are not an
283         * empty string \a s will be preferred).
284         *
285         * @param ChunkID  - 32 bit RIFF chunk ID of INFO subchunk
286         * @param lstINFO  - parent (INFO) RIFF list chunk
287         * @param s        - current value of info field
288         * @param sDefault - default value
289         * @param bUseFixedLengthStrings - should a specific string size be forced in the chunk?
290         * @param size     - wanted size of the INFO chunk. This is ignored if bUseFixedLengthStrings is false.
291         */
292        void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault, bool bUseFixedLengthStrings, int size) {
293            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
294            ::SaveString(ChunkID, ck, lstINFO, s, sDefault, bUseFixedLengthStrings, size); // function from helper.h
295        }
296    
297        /** @brief Update chunks with current info values.
298         *
299         * Apply current INFO field values to the respective INFO chunks. You
300         * have to call File::Save() to make changes persistent.
301         */
302        void Info::UpdateChunks() {
303            if (!pResourceListChunk) return;
304    
305            // make sure INFO list chunk exists
306            RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
307    
308            String defaultName = "";
309            String defaultCreationDate = "";
310            String defaultSoftware = "";
311            String defaultComments = "";
312    
313            uint32_t resourceType = pResourceListChunk->GetListType();
314    
315            if (!lstINFO) {
316                lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
317    
318                // assemble default values
319                defaultName = "NONAME";
320    
321                if (resourceType == RIFF_TYPE_DLS) {
322                    // get current date
323                    time_t now = time(NULL);
324                    tm* pNowBroken = localtime(&now);
325                    char buf[11];
326                    strftime(buf, 11, "%F", pNowBroken);
327                    defaultCreationDate = buf;
328    
329                    defaultComments = "Created with " + libraryName() + " " + libraryVersion();
330                }
331                if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
332                {
333                    defaultSoftware = libraryName() + " " + libraryVersion();
334                }
335            }
336    
337            // save values
338    
339            // (the string size values are for gig files; they are only
340            // used if UseFixedLengthStrings is set to true)
341            SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName, UseFixedLengthStrings,
342                       resourceType == RIFF_TYPE_DLS ? 128 : 64);
343            SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""), UseFixedLengthStrings, 256);
344            SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate, UseFixedLengthStrings, 128);
345            SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments, UseFixedLengthStrings, 1024);
346            SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""), UseFixedLengthStrings, 128);
347            SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""), UseFixedLengthStrings, 128);
348            SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""), UseFixedLengthStrings, 128);
349            SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""), UseFixedLengthStrings, 128);
350            SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""), UseFixedLengthStrings, 128);
351            SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""), UseFixedLengthStrings, 128);
352            SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""), UseFixedLengthStrings, 128);
353            SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware, UseFixedLengthStrings,
354                       resourceType == LIST_TYPE_INS ?
355                       (Software == "" ? defaultSoftware.length()+1 : Software.length()+1) : 128);
356            SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""), UseFixedLengthStrings, 128);
357            SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""), UseFixedLengthStrings, 128);
358            SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""), UseFixedLengthStrings, 128);
359            SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""), UseFixedLengthStrings, 128);
360            SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""), UseFixedLengthStrings, 128);
361        }
362    
363    
364    
365  // *************** Resource ***************  // *************** Resource ***************
366  // *  // *
367    
368        /** @brief Constructor.
369         *
370         * Initializes the 'Resource' object with values provided by a given
371         * INFO list chunk and a DLID chunk (the latter optional).
372         *
373         * @param Parent      - pointer to parent 'Resource', NULL if this is
374         *                      the toplevel 'Resource' object
375         * @param lstResource - pointer to an INFO list chunk
376         */
377      Resource::Resource(Resource* Parent, RIFF::List* lstResource) {      Resource::Resource(Resource* Parent, RIFF::List* lstResource) {
378          pParent = Parent;          pParent = Parent;
379            pResourceList = lstResource;
380    
381          pInfo = new Info(lstResource);          pInfo = new Info(lstResource);
382    
# Line 180  namespace DLS { Line 396  namespace DLS {
396          if (pInfo)  delete pInfo;          if (pInfo)  delete pInfo;
397      }      }
398    
399        /** @brief Update chunks with current Resource data.
400         *
401         * Apply Resource data persistently below the previously given resource
402         * list chunk. This will currently only include the INFO data. The DLSID
403         * will not be applied at the moment (yet).
404         *
405         * You have to call File::Save() to make changes persistent.
406         */
407        void Resource::UpdateChunks() {
408            pInfo->UpdateChunks();
409            //TODO: save DLSID
410        }
411    
412    
413    
414  // *************** Sampler ***************  // *************** Sampler ***************
415  // *  // *
416    
417      Sampler::Sampler(RIFF::List* ParentList) {      Sampler::Sampler(RIFF::List* ParentList) {
418            pParentList       = ParentList;
419          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
420          if (!wsmp) throw DLS::Exception("Mandatory <wsmp> chunk not found.");          if (wsmp) {
421          uint32_t headersize = wsmp->ReadUint32();              uiHeaderSize   = wsmp->ReadUint32();
422          UnityNote        = wsmp->ReadUint16();              UnityNote      = wsmp->ReadUint16();
423          FineTune         = wsmp->ReadInt16();              FineTune       = wsmp->ReadInt16();
424          Gain             = wsmp->ReadInt32();              Gain           = wsmp->ReadInt32();
425          SamplerOptions   = wsmp->ReadUint32();              SamplerOptions = wsmp->ReadUint32();
426                SampleLoops    = wsmp->ReadUint32();
427            } else { // 'wsmp' chunk missing
428                uiHeaderSize   = 0;
429                UnityNote      = 64;
430                FineTune       = 0; // +- 0 cents
431                Gain           = 0; // 0 dB
432                SamplerOptions = F_WSMP_NO_COMPRESSION;
433                SampleLoops    = 0;
434            }
435          NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;          NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;
436          NoSampleCompression     = SamplerOptions & F_WSMP_NO_COMPRESSION;          NoSampleCompression     = SamplerOptions & F_WSMP_NO_COMPRESSION;
         SampleLoops             = wsmp->ReadUint32();  
437          pSampleLoops            = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;          pSampleLoops            = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;
438          wsmp->SetPos(headersize);          if (SampleLoops) {
439          for (uint32_t i = 0; i < SampleLoops; i++) {              wsmp->SetPos(uiHeaderSize);
440              wsmp->Read(pSampleLoops + i, 4, 4);              for (uint32_t i = 0; i < SampleLoops; i++) {
441              if (pSampleLoops[i].Size > sizeof(sample_loop_t)) { // if loop struct was extended                  wsmp->Read(pSampleLoops + i, 4, 4);
442                  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
443                        wsmp->SetPos(pSampleLoops[i].Size - sizeof(sample_loop_t), RIFF::stream_curpos);
444                    }
445              }              }
446          }          }
447      }      }
# Line 210  namespace DLS { Line 450  namespace DLS {
450          if (pSampleLoops) delete[] pSampleLoops;          if (pSampleLoops) delete[] pSampleLoops;
451      }      }
452    
453        /**
454         * Apply all sample player options to the respective RIFF chunk. You
455         * have to call File::Save() to make changes persistent.
456         */
457        void Sampler::UpdateChunks() {
458            // make sure 'wsmp' chunk exists
459            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
460            if (!wsmp) {
461                uiHeaderSize = 20;
462                wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);
463            }
464            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
465            // update headers size
466            memcpy(&pData[0], &uiHeaderSize, 4);
467            // update respective sampler options bits
468            SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
469                                                       : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
470            SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
471                                                   : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
472            memcpy(&pData[4], &UnityNote, 2);
473            memcpy(&pData[6], &FineTune, 2);
474            memcpy(&pData[8], &Gain, 4);
475            memcpy(&pData[12], &SamplerOptions, 4);
476            memcpy(&pData[16], &SampleLoops, 4);
477            // update loop definitions
478            for (uint32_t i = 0; i < SampleLoops; i++) {
479                //FIXME: this does not handle extended loop structs correctly
480                memcpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4 * 4);
481            }
482        }
483    
484        /**
485         * Adds a new sample loop with the provided loop definition.
486         *
487         * @param - points to a loop definition that is to be copied
488         */
489        void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
490            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
491            // copy old loops array
492            for (int i = 0; i < SampleLoops; i++) {
493                pNewLoops[i] = pSampleLoops[i];
494            }
495            // add the new loop
496            pNewLoops[SampleLoops] = *pLoopDef;
497            // free the old array and update the member variables
498            if (SampleLoops) delete[] pSampleLoops;
499            pSampleLoops = pNewLoops;
500            SampleLoops++;
501        }
502    
503        /**
504         * Deletes an existing sample loop.
505         *
506         * @param pLoopDef - pointer to existing loop definition
507         * @throws Exception - if given loop definition does not exist
508         */
509        void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
510            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
511            // copy old loops array (skipping given loop)
512            for (int i = 0, o = 0; i < SampleLoops; i++) {
513                if (&pSampleLoops[i] == pLoopDef) continue;
514                if (o == SampleLoops - 1)
515                    throw Exception("Could not delete Sample Loop, because it does not exist");
516                pNewLoops[o] = pSampleLoops[i];
517                o++;
518            }
519            // free the old array and update the member variables
520            if (SampleLoops) delete[] pSampleLoops;
521            pSampleLoops = pNewLoops;
522            SampleLoops--;
523        }
524    
525    
526    
527  // *************** Sample ***************  // *************** Sample ***************
528  // *  // *
529    
530        /** @brief Constructor.
531         *
532         * Load an existing sample or create a new one. A 'wave' list chunk must
533         * be given to this constructor. In case the given 'wave' list chunk
534         * contains a 'fmt' and 'data' chunk, the format and sample data will be
535         * loaded from there, otherwise default values will be used and those
536         * chunks will be created when File::Save() will be called later on.
537         *
538         * @param pFile          - pointer to DLS::File where this sample is
539         *                         located (or will be located)
540         * @param waveList       - pointer to 'wave' list chunk which is (or
541         *                         will be) associated with this sample
542         * @param WavePoolOffset - offset of this sample data from wave pool
543         *                         ('wvpl') list chunk
544         */
545      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) {
546            pWaveList = waveList;
547          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;
548          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
549          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
550          if (!pCkFormat || !pCkData) throw DLS::Exception("Mandatory chunks in wave list not found.");          if (pCkFormat) {
551                // common fields
552          // common fields              FormatTag              = pCkFormat->ReadUint16();
553          FormatTag              = pCkFormat->ReadUint16();              Channels               = pCkFormat->ReadUint16();
554          Channels               = pCkFormat->ReadUint16();              SamplesPerSecond       = pCkFormat->ReadUint32();
555          SamplesPerSecond       = pCkFormat->ReadUint32();              AverageBytesPerSecond  = pCkFormat->ReadUint32();
556          AverageBytesPerSecond  = pCkFormat->ReadUint32();              BlockAlign             = pCkFormat->ReadUint16();
557          BlockAlign             = pCkFormat->ReadUint16();              // PCM format specific
558                if (FormatTag == DLS_WAVE_FORMAT_PCM) {
559          // PCM format specific                  BitDepth     = pCkFormat->ReadUint16();
560          if (FormatTag == WAVE_FORMAT_PCM) {                  FrameSize    = (BitDepth / 8) * Channels;
561              BitDepth     = pCkFormat->ReadUint16();              } else { // unsupported sample data format
562              FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels                  BitDepth     = 0;
563                                                            : 0;                  FrameSize    = 0;
564              SamplesTotal = (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize              }
565                                                            : 0;          } else { // 'fmt' chunk missing
566          }              FormatTag              = DLS_WAVE_FORMAT_PCM;
567          else {              BitDepth               = 16;
568              BitDepth     = 0;              Channels               = 1;
569              FrameSize    = 0;              SamplesPerSecond       = 44100;
570              SamplesTotal = 0;              AverageBytesPerSecond  = (BitDepth / 8) * SamplesPerSecond * Channels;
571                FrameSize              = (BitDepth / 8) * Channels;
572                BlockAlign             = FrameSize;
573          }          }
574            SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
575                                                                          : 0
576                                     : 0;
577      }      }
578    
579        /** @brief Destructor.
580         *
581         * Removes RIFF chunks associated with this Sample and frees all
582         * memory occupied by this sample.
583         */
584        Sample::~Sample() {
585            RIFF::List* pParent = pWaveList->GetParent();
586            pParent->DeleteSubChunk(pWaveList);
587        }
588    
589        /** @brief Load sample data into RAM.
590         *
591         * In case the respective 'data' chunk exists, the sample data will be
592         * loaded into RAM (if not done already) and a pointer to the data in
593         * RAM will be returned. If this is a new sample, you have to call
594         * Resize() with the desired sample size to create the mandatory RIFF
595         * chunk for the sample wave data.
596         *
597         * You can call LoadChunkData() again if you previously scheduled to
598         * enlarge the sample data RIFF chunk with a Resize() call. In that case
599         * the buffer will be enlarged to the new, scheduled size and you can
600         * already place the sample wave data to the buffer and finally call
601         * File::Save() to enlarge the sample data's chunk physically and write
602         * the new sample wave data in one rush. This approach is definitely
603         * recommended if you have to enlarge and write new sample data to a lot
604         * of samples.
605         *
606         * <b>Caution:</b> the buffer pointer will be invalidated once
607         * File::Save() was called. You have to call LoadChunkData() again to
608         * get a new, valid pointer whenever File::Save() was called.
609         *
610         * @returns pointer to sample data in RAM, NULL in case respective
611         *          'data' chunk does not exist (yet)
612         * @throws Exception if data buffer could not be enlarged
613         * @see Resize(), File::Save()
614         */
615      void* Sample::LoadSampleData() {      void* Sample::LoadSampleData() {
616          return pCkData->LoadChunkData();          return (pCkData) ? pCkData->LoadChunkData() : NULL;
617      }      }
618    
619        /** @brief Free sample data from RAM.
620         *
621         * In case sample data was previously successfully loaded into RAM with
622         * LoadSampleData(), this method will free the sample data from RAM.
623         */
624      void Sample::ReleaseSampleData() {      void Sample::ReleaseSampleData() {
625          pCkData->ReleaseChunkData();          if (pCkData) pCkData->ReleaseChunkData();
626        }
627    
628        /** @brief Returns sample size.
629         *
630         * Returns the sample wave form's data size (in sample points). This is
631         * actually the current, physical size (converted to sample points) of
632         * the RIFF chunk which encapsulates the sample's wave data. The
633         * returned value is dependant to the current FrameSize value.
634         *
635         * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM
636         * @see FrameSize, FormatTag
637         */
638        unsigned long Sample::GetSize() {
639            if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
640            return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
641        }
642    
643        /** @brief Resize sample.
644         *
645         * Resizes the sample's wave form data, that is the actual size of
646         * sample wave data possible to be written for this sample. This call
647         * will return immediately and just schedule the resize operation. You
648         * should call File::Save() to actually perform the resize operation(s)
649         * "physically" to the file. As this can take a while on large files, it
650         * is recommended to call Resize() first on all samples which have to be
651         * resized and finally to call File::Save() to perform all those resize
652         * operations in one rush.
653         *
654         * The actual size (in bytes) is dependant to the current FrameSize
655         * value. You may want to set FrameSize before calling Resize().
656         *
657         * <b>Caution:</b> You cannot directly write to enlarged samples before
658         * calling File::Save() as this might exceed the current sample's
659         * boundary!
660         *
661         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
662         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
663         * other formats will fail!
664         *
665         * @param iNewSize - new sample wave data size in sample points (must be
666         *                   greater than zero)
667         * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
668         * @throws Exception if \a iNewSize is less than 1
669         * @see File::Save(), FrameSize, FormatTag
670         */
671        void Sample::Resize(int iNewSize) {
672            if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
673            if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");
674            const int iSizeInBytes = iNewSize * FrameSize;
675            pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
676            if (pCkData) pCkData->Resize(iSizeInBytes);
677            else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);
678      }      }
679    
680      /**      /**
# Line 256  namespace DLS { Line 682  namespace DLS {
682       * 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
683       * the sample into RAM, thus for disk streaming.       * the sample into RAM, thus for disk streaming.
684       *       *
685         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
686         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
687         * with other formats will fail!
688         *
689       * @param SampleCount  number of sample points       * @param SampleCount  number of sample points
690       * @param Whence       to which relation \a SampleCount refers to       * @param Whence       to which relation \a SampleCount refers to
691         * @returns new position within the sample, 0 if
692         *          FormatTag != DLS_WAVE_FORMAT_PCM
693         * @throws Exception if no data RIFF chunk was created for the sample yet
694         * @see FrameSize, FormatTag
695       */       */
696      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
697          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
698            if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
699          unsigned long orderedBytes = SampleCount * FrameSize;          unsigned long orderedBytes = SampleCount * FrameSize;
700          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          unsigned long result = pCkData->SetPos(orderedBytes, Whence);
701          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
# Line 277  namespace DLS { Line 712  namespace DLS {
712       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
713       */       */
714      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
715          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
716          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?
717      }      }
718    
719        /** @brief Write sample wave data.
720         *
721         * Writes \a SampleCount number of sample points from the buffer pointed
722         * by \a pBuffer and increments the position within the sample. Use this
723         * method to directly write the sample data to disk, i.e. if you don't
724         * want or cannot load the whole sample data into RAM.
725         *
726         * You have to Resize() the sample to the desired size and call
727         * File::Save() <b>before</b> using Write().
728         *
729         * @param pBuffer     - source buffer
730         * @param SampleCount - number of sample points to write
731         * @throws Exception if current sample size is too small
732         * @see LoadSampleData()
733         */
734        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
735            if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
736            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
737            return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
738        }
739    
740        /**
741         * Apply sample and its settings to the respective RIFF chunks. You have
742         * to call File::Save() to make changes persistent.
743         *
744         * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
745         *                   was provided yet
746         */
747        void Sample::UpdateChunks() {
748            if (FormatTag != DLS_WAVE_FORMAT_PCM)
749                throw Exception("Could not save sample, only PCM format is supported");
750            // we refuse to do anything if not sample wave form was provided yet
751            if (!pCkData)
752                throw Exception("Could not save sample, there is no sample data to save");
753            // update chunks of base class as well
754            Resource::UpdateChunks();
755            // make sure 'fmt' chunk exists
756            RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
757            if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
758            uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
759            // update 'fmt' chunk
760            memcpy(&pData[0], &FormatTag, 2);
761            memcpy(&pData[2], &Channels,  2);
762            memcpy(&pData[4], &SamplesPerSecond, 4);
763            memcpy(&pData[8], &AverageBytesPerSecond, 4);
764            memcpy(&pData[12], &BlockAlign, 2);
765            memcpy(&pData[14], &BitDepth, 2); // assuming PCM format
766        }
767    
768    
769    
770  // *************** Region ***************  // *************** Region ***************
# Line 289  namespace DLS { Line 773  namespace DLS {
773      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) {
774          pCkRegion = rgnList;          pCkRegion = rgnList;
775    
776            // articulation informations
777          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
778          rgnh->Read(&KeyRange, 2, 2);          if (rgnh) {
779          rgnh->Read(&VelocityRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
780          uint16_t optionflags = rgnh->ReadUint16();              rgnh->Read(&VelocityRange, 2, 2);
781          SelfNonExclusive = optionflags & F_RGN_OPTION_SELFNONEXCLUSIVE;              FormatOptionFlags = rgnh->ReadUint16();
782          KeyGroup = rgnh->ReadUint16();              KeyGroup = rgnh->ReadUint16();
783          // Layer is optional              // Layer is optional
784          if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {              if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
785              rgnh->Read(&Layer, 1, sizeof(uint16_t));                  rgnh->Read(&Layer, 1, sizeof(uint16_t));
786                } else Layer = 0;
787            } else { // 'rgnh' chunk is missing
788                KeyRange.low  = 0;
789                KeyRange.high = 127;
790                VelocityRange.low  = 0;
791                VelocityRange.high = 127;
792                FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
793                KeyGroup = 0;
794                Layer = 0;
795          }          }
796          else Layer = 0;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
797    
798            // sample informations
799          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
800          optionflags  = wlnk->ReadUint16();          if (wlnk) {
801          PhaseMaster  = optionflags & F_WAVELINK_PHASE_MASTER;              WaveLinkOptionFlags = wlnk->ReadUint16();
802          MultiChannel = optionflags & F_WAVELINK_MULTICHANNEL;              PhaseGroup          = wlnk->ReadUint16();
803          PhaseGroup         = wlnk->ReadUint16();              Channel             = wlnk->ReadUint32();
804          Channel            = wlnk->ReadUint32();              WavePoolTableIndex  = wlnk->ReadUint32();
805          WavePoolTableIndex = wlnk->ReadUint32();          } else { // 'wlnk' chunk is missing
806                WaveLinkOptionFlags = 0;
807                PhaseGroup          = 0;
808                Channel             = 0; // mono
809                WavePoolTableIndex  = 0; // first entry in wave pool table
810            }
811            PhaseMaster  = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
812            MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
813    
814          pSample = NULL;          pSample = NULL;
815      }      }
816    
817        /** @brief Destructor.
818         *
819         * Removes RIFF chunks associated with this Region.
820         */
821      Region::~Region() {      Region::~Region() {
822            RIFF::List* pParent = pCkRegion->GetParent();
823            pParent->DeleteSubChunk(pCkRegion);
824      }      }
825    
826      Sample* Region::GetSample() {      Sample* Region::GetSample() {
# Line 327  namespace DLS { Line 835  namespace DLS {
835          return NULL;          return NULL;
836      }      }
837    
838        /**
839         * Assign another sample to this Region.
840         *
841         * @param pSample - sample to be assigned
842         */
843        void Region::SetSample(Sample* pSample) {
844            this->pSample = pSample;
845            WavePoolTableIndex = 0; // we update this offset when we Save()
846        }
847    
848        /**
849         * Apply Region settings to the respective RIFF chunks. You have to
850         * call File::Save() to make changes persistent.
851         *
852         * @throws Exception - if the Region's sample could not be found
853         */
854        void Region::UpdateChunks() {
855            // make sure 'rgnh' chunk exists
856            RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
857            if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
858            uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
859            FormatOptionFlags = (SelfNonExclusive)
860                                    ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
861                                    : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
862            // update 'rgnh' chunk
863            memcpy(&pData[0], &KeyRange, 2 * 2);
864            memcpy(&pData[4], &VelocityRange, 2 * 2);
865            memcpy(&pData[8], &FormatOptionFlags, 2);
866            memcpy(&pData[10], &KeyGroup, 2);
867            if (rgnh->GetSize() >= 14) memcpy(&pData[12], &Layer, 2);
868    
869            // update chunks of base classes as well (but skip Resource,
870            // as a rgn doesn't seem to have dlid and INFO chunks)
871            Articulator::UpdateChunks();
872            Sampler::UpdateChunks();
873    
874            // make sure 'wlnk' chunk exists
875            RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
876            if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
877            pData = (uint8_t*) wlnk->LoadChunkData();
878            WaveLinkOptionFlags = (PhaseMaster)
879                                      ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
880                                      : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
881            WaveLinkOptionFlags = (MultiChannel)
882                                      ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
883                                      : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
884            // get sample's wave pool table index
885            int index = -1;
886            File* pFile = (File*) GetParent()->GetParent();
887            if (pFile->pSamples) {
888                File::SampleList::iterator iter = pFile->pSamples->begin();
889                File::SampleList::iterator end  = pFile->pSamples->end();
890                for (int i = 0; iter != end; ++iter, i++) {
891                    if (*iter == pSample) {
892                        index = i;
893                        break;
894                    }
895                }
896            }
897            if (index < 0) throw Exception("Could not save Region, could not find Region's sample");
898            WavePoolTableIndex = index;
899            // update 'wlnk' chunk
900            memcpy(&pData[0], &WaveLinkOptionFlags, 2);
901            memcpy(&pData[2], &PhaseGroup, 2);
902            memcpy(&pData[4], &Channel, 4);
903            memcpy(&pData[8], &WavePoolTableIndex, 4);
904        }
905    
906    
907    
908  // *************** Instrument ***************  // *************** Instrument ***************
909  // *  // *
910    
911        /** @brief Constructor.
912         *
913         * Load an existing instrument definition or create a new one. An 'ins'
914         * list chunk must be given to this constructor. In case this 'ins' list
915         * chunk contains a 'insh' chunk, the instrument data fields will be
916         * loaded from there, otherwise default values will be used and the
917         * 'insh' chunk will be created once File::Save() was called.
918         *
919         * @param pFile   - pointer to DLS::File where this instrument is
920         *                  located (or will be located)
921         * @param insList - pointer to 'ins' list chunk which is (or will be)
922         *                  associated with this instrument
923         */
924      Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
925          pCkInstrument = insList;          pCkInstrument = insList;
926    
         RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);  
         if (!insh) throw DLS::Exception("Mandatory chunks in <lins> list chunk not found.");  
         Regions = insh->ReadUint32();  
927          midi_locale_t locale;          midi_locale_t locale;
928          insh->Read(&locale, 2, 4);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
929            if (insh) {
930                Regions = insh->ReadUint32();
931                insh->Read(&locale, 2, 4);
932            } else { // 'insh' chunk missing
933                Regions = 0;
934                locale.bank       = 0;
935                locale.instrument = 0;
936            }
937    
938          MIDIProgram    = locale.instrument;          MIDIProgram    = locale.instrument;
939          IsDrum         = locale.bank & DRUM_TYPE_MASK;          IsDrum         = locale.bank & DRUM_TYPE_MASK;
940          MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);          MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
941          MIDIBankFine   = (uint8_t) MIDI_BANK_FINE(locale.bank);          MIDIBankFine   = (uint8_t) MIDI_BANK_FINE(locale.bank);
942          MIDIBank       = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);          MIDIBank       = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
943    
944          pRegions   = NULL;          pRegions = NULL;
945      }      }
946    
947      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
# Line 363  namespace DLS { Line 958  namespace DLS {
958      }      }
959    
960      void Instrument::LoadRegions() {      void Instrument::LoadRegions() {
961            if (!pRegions) pRegions = new RegionList;
962          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
963          if (!lrgn) throw DLS::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
964          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
965          RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::List* rgn = lrgn->GetFirstSubList();
966          while (rgn) {              while (rgn) {
967              if (rgn->GetListType() == regionCkType) {                  if (rgn->GetListType() == regionCkType) {
968                  if (!pRegions) pRegions = new RegionList;                      pRegions->push_back(new Region(this, rgn));
969                  pRegions->push_back(new Region(this, rgn));                  }
970                    rgn = lrgn->GetNextSubList();
971              }              }
             rgn = lrgn->GetNextSubList();  
972          }          }
973      }      }
974    
975        Region* Instrument::AddRegion() {
976            if (!pRegions) LoadRegions();
977            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
978            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
979            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
980            Region* pNewRegion = new Region(this, rgn);
981            pRegions->push_back(pNewRegion);
982            Regions = pRegions->size();
983            return pNewRegion;
984        }
985    
986        void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
987            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
988            lrgn->MoveSubChunk(pSrc->pCkRegion, pDst ? pDst->pCkRegion : 0);
989    
990            pRegions->remove(pSrc);
991            RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
992            pRegions->insert(iter, pSrc);
993        }
994    
995        void Instrument::DeleteRegion(Region* pRegion) {
996            if (!pRegions) return;
997            RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
998            if (iter == pRegions->end()) return;
999            pRegions->erase(iter);
1000            Regions = pRegions->size();
1001            delete pRegion;
1002        }
1003    
1004        /**
1005         * Apply Instrument with all its Regions to the respective RIFF chunks.
1006         * You have to call File::Save() to make changes persistent.
1007         *
1008         * @throws Exception - on errors
1009         */
1010        void Instrument::UpdateChunks() {
1011            // first update base classes' chunks
1012            Resource::UpdateChunks();
1013            Articulator::UpdateChunks();
1014            // make sure 'insh' chunk exists
1015            RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1016            if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1017            uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1018            // update 'insh' chunk
1019            Regions = (pRegions) ? pRegions->size() : 0;
1020            midi_locale_t locale;
1021            locale.instrument = MIDIProgram;
1022            locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1023            locale.bank       = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
1024            MIDIBank          = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
1025            memcpy(&pData[0], &Regions, 4);
1026            memcpy(&pData[4], &locale, 2 * 4);
1027            // update Region's chunks
1028            if (!pRegions) return;
1029            RegionList::iterator iter = pRegions->begin();
1030            RegionList::iterator end  = pRegions->end();
1031            for (; iter != end; ++iter) {
1032                (*iter)->UpdateChunks();
1033            }
1034        }
1035    
1036        /** @brief Destructor.
1037         *
1038         * Removes RIFF chunks associated with this Instrument and frees all
1039         * memory occupied by this instrument.
1040         */
1041      Instrument::~Instrument() {      Instrument::~Instrument() {
1042          if (pRegions) {          if (pRegions) {
1043              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
# Line 386  namespace DLS { Line 1048  namespace DLS {
1048              }              }
1049              delete pRegions;              delete pRegions;
1050          }          }
1051            // remove instrument's chunks
1052            RIFF::List* pParent = pCkInstrument->GetParent();
1053            pParent->DeleteSubChunk(pCkInstrument);
1054      }      }
1055    
1056    
# Line 393  namespace DLS { Line 1058  namespace DLS {
1058  // *************** File ***************  // *************** File ***************
1059  // *  // *
1060    
1061        /** @brief Constructor.
1062         *
1063         * Default constructor, use this to create an empty DLS file. You have
1064         * to add samples, instruments and finally call Save() to actually write
1065         * a DLS file.
1066         */
1067        File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1068            pVersion = new version_t;
1069            pVersion->major   = 0;
1070            pVersion->minor   = 0;
1071            pVersion->release = 0;
1072            pVersion->build   = 0;
1073    
1074            Instruments      = 0;
1075            WavePoolCount    = 0;
1076            pWavePoolTable   = NULL;
1077            pWavePoolTableHi = NULL;
1078            WavePoolHeaderSize = 8;
1079    
1080            pSamples     = NULL;
1081            pInstruments = NULL;
1082    
1083            b64BitWavePoolOffsets = false;
1084        }
1085    
1086        /** @brief Constructor.
1087         *
1088         * Load an existing DLS file.
1089         *
1090         * @param pRIFF - pointer to a RIFF file which is actually the DLS file
1091         *                to load
1092         * @throws Exception if given file is not a DLS file, expected chunks
1093         *                   are missing
1094         */
1095      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1096          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1097          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
# Line 409  namespace DLS { Line 1108  namespace DLS {
1108          Instruments = colh->ReadUint32();          Instruments = colh->ReadUint32();
1109    
1110          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1111          if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");          if (!ptbl) { // pool table is missing - this is probably an ".art" file
1112          uint32_t headersize = ptbl->ReadUint32();              WavePoolCount    = 0;
1113          WavePoolCount  = ptbl->ReadUint32();              pWavePoolTable   = NULL;
1114          pWavePoolTable = new uint32_t[WavePoolCount];              pWavePoolTableHi = NULL;
1115          ptbl->SetPos(headersize);              WavePoolHeaderSize = 8;
1116                b64BitWavePoolOffsets = false;
1117          // Check for 64 bit offsets (used in gig v3 files)          } else {
1118          if (ptbl->GetSize() - headersize == WavePoolCount * 8) {              WavePoolHeaderSize = ptbl->ReadUint32();
1119              for (int i = 0 ; i < WavePoolCount ; i++) {              WavePoolCount  = ptbl->ReadUint32();
1120                  // Just ignore the upper bits for now              pWavePoolTable = new uint32_t[WavePoolCount];
1121                  uint32_t upper = ptbl->ReadUint32();              pWavePoolTableHi = new uint32_t[WavePoolCount];
1122                  pWavePoolTable[i] = ptbl->ReadUint32();              ptbl->SetPos(WavePoolHeaderSize);
1123                  if (upper || (pWavePoolTable[i] & 0x80000000))  
1124                      throw DLS::Exception("Files larger than 2 GB not yet supported");              // Check for 64 bit offsets (used in gig v3 files)
1125                b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1126                if (b64BitWavePoolOffsets) {
1127                    for (int i = 0 ; i < WavePoolCount ; i++) {
1128                        pWavePoolTableHi[i] = ptbl->ReadUint32();
1129                        pWavePoolTable[i] = ptbl->ReadUint32();
1130                        if (pWavePoolTable[i] & 0x80000000)
1131                            throw DLS::Exception("Files larger than 2 GB not yet supported");
1132                    }
1133                } else { // conventional 32 bit offsets
1134                    ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1135                    for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1136              }              }
1137          }          }
         else ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));  
1138    
1139          pSamples     = NULL;          pSamples     = NULL;
1140          pInstruments = NULL;          pInstruments = NULL;
         Instruments  = 0;  
1141      }      }
1142    
1143      File::~File() {      File::~File() {
# Line 454  namespace DLS { Line 1162  namespace DLS {
1162          }          }
1163    
1164          if (pWavePoolTable) delete[] pWavePoolTable;          if (pWavePoolTable) delete[] pWavePoolTable;
1165            if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1166          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1167            for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1168                delete *i;
1169      }      }
1170    
1171      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
# Line 471  namespace DLS { Line 1182  namespace DLS {
1182      }      }
1183    
1184      void File::LoadSamples() {      void File::LoadSamples() {
1185            if (!pSamples) pSamples = new SampleList;
1186          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1187          if (wvpl) {          if (wvpl) {
1188              unsigned long wvplFileOffset = wvpl->GetFilePos();              unsigned long wvplFileOffset = wvpl->GetFilePos();
1189              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1190              while (wave) {              while (wave) {
1191                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
                     if (!pSamples) pSamples = new SampleList;  
1192                      unsigned long waveFileOffset = wave->GetFilePos();                      unsigned long waveFileOffset = wave->GetFilePos();
1193                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1194                  }                  }
# Line 491  namespace DLS { Line 1202  namespace DLS {
1202                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1203                  while (wave) {                  while (wave) {
1204                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
                         if (!pSamples) pSamples = new SampleList;  
1205                          unsigned long waveFileOffset = wave->GetFilePos();                          unsigned long waveFileOffset = wave->GetFilePos();
1206                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1207                      }                      }
# Line 501  namespace DLS { Line 1211  namespace DLS {
1211          }          }
1212      }      }
1213    
1214        /** @brief Add a new sample.
1215         *
1216         * This will create a new Sample object for the DLS file. You have to
1217         * call Save() to make this persistent to the file.
1218         *
1219         * @returns pointer to new Sample object
1220         */
1221        Sample* File::AddSample() {
1222           if (!pSamples) LoadSamples();
1223           __ensureMandatoryChunksExist();
1224           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1225           // create new Sample object and its respective 'wave' list chunk
1226           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1227           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1228           pSamples->push_back(pSample);
1229           return pSample;
1230        }
1231    
1232        /** @brief Delete a sample.
1233         *
1234         * This will delete the given Sample object from the DLS file. You have
1235         * to call Save() to make this persistent to the file.
1236         *
1237         * @param pSample - sample to delete
1238         */
1239        void File::DeleteSample(Sample* pSample) {
1240            if (!pSamples) return;
1241            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1242            if (iter == pSamples->end()) return;
1243            pSamples->erase(iter);
1244            delete pSample;
1245        }
1246    
1247      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
1248          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
1249          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
# Line 515  namespace DLS { Line 1258  namespace DLS {
1258      }      }
1259    
1260      void File::LoadInstruments() {      void File::LoadInstruments() {
1261            if (!pInstruments) pInstruments = new InstrumentList;
1262          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1263          if (lstInstruments) {          if (lstInstruments) {
1264              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1265              while (lstInstr) {              while (lstInstr) {
1266                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
                     if (!pInstruments) pInstruments = new InstrumentList;  
1267                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr));
1268                  }                  }
1269                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
# Line 528  namespace DLS { Line 1271  namespace DLS {
1271          }          }
1272      }      }
1273    
1274        /** @brief Add a new instrument definition.
1275         *
1276         * This will create a new Instrument object for the DLS file. You have
1277         * to call Save() to make this persistent to the file.
1278         *
1279         * @returns pointer to new Instrument object
1280         */
1281        Instrument* File::AddInstrument() {
1282           if (!pInstruments) LoadInstruments();
1283           __ensureMandatoryChunksExist();
1284           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1285           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1286           Instrument* pInstrument = new Instrument(this, lstInstr);
1287           pInstruments->push_back(pInstrument);
1288           return pInstrument;
1289        }
1290    
1291        /** @brief Delete an instrument.
1292         *
1293         * This will delete the given Instrument object from the DLS file. You
1294         * have to call Save() to make this persistent to the file.
1295         *
1296         * @param pInstrument - instrument to delete
1297         */
1298        void File::DeleteInstrument(Instrument* pInstrument) {
1299            if (!pInstruments) return;
1300            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1301            if (iter == pInstruments->end()) return;
1302            pInstruments->erase(iter);
1303            delete pInstrument;
1304        }
1305    
1306        /**
1307         * Apply all the DLS file's current instruments, samples and settings to
1308         * the respective RIFF chunks. You have to call Save() to make changes
1309         * persistent.
1310         *
1311         * @throws Exception - on errors
1312         */
1313        void File::UpdateChunks() {
1314            // first update base class's chunks
1315            Resource::UpdateChunks();
1316    
1317            // if version struct exists, update 'vers' chunk
1318            if (pVersion) {
1319                RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1320                if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1321                uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1322                memcpy(pData, pVersion, 2 * 4);
1323            }
1324    
1325            // update 'colh' chunk
1326            Instruments = (pInstruments) ? pInstruments->size() : 0;
1327            RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1328            if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1329            uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1330            memcpy(pData, &Instruments, 4);
1331    
1332            // update instrument's chunks
1333            if (pInstruments) {
1334                InstrumentList::iterator iter = pInstruments->begin();
1335                InstrumentList::iterator end  = pInstruments->end();
1336                for (; iter != end; ++iter) {
1337                    (*iter)->UpdateChunks();
1338                }
1339            }
1340    
1341            // update 'ptbl' chunk
1342            const int iSamples = (pSamples) ? pSamples->size() : 0;
1343            const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1344            RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1345            if (!ptbl)   ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
1346            const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1347            ptbl->Resize(iPtblSize);
1348            pData = (uint8_t*) ptbl->LoadChunkData();
1349            WavePoolCount = iSamples;
1350            memcpy(&pData[4], &WavePoolCount, 4);
1351            // we actually update the sample offsets in the pool table when we Save()
1352            memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1353    
1354            // update sample's chunks
1355            if (pSamples) {
1356                SampleList::iterator iter = pSamples->begin();
1357                SampleList::iterator end  = pSamples->end();
1358                for (; iter != end; ++iter) {
1359                    (*iter)->UpdateChunks();
1360                }
1361            }
1362        }
1363    
1364        /** @brief Save changes to another file.
1365         *
1366         * Make all changes persistent by writing them to another file.
1367         * <b>Caution:</b> this method is optimized for writing to
1368         * <b>another</b> file, do not use it to save the changes to the same
1369         * file! Use Save() (without path argument) in that case instead!
1370         * Ignoring this might result in a corrupted file!
1371         *
1372         * After calling this method, this File object will be associated with
1373         * the new file (given by \a Path) afterwards.
1374         *
1375         * @param Path - path and file name where everything should be written to
1376         */
1377        void File::Save(const String& Path) {
1378            UpdateChunks();
1379            pRIFF->Save(Path);
1380            __UpdateWavePoolTableChunk();
1381        }
1382    
1383        /** @brief Save changes to same file.
1384         *
1385         * Make all changes persistent by writing them to the actual (same)
1386         * file. The file might temporarily grow to a higher size than it will
1387         * have at the end of the saving process.
1388         *
1389         * @throws RIFF::Exception if any kind of IO error occured
1390         * @throws DLS::Exception  if any kind of DLS specific error occured
1391         */
1392        void File::Save() {
1393            UpdateChunks();
1394            pRIFF->Save();
1395            __UpdateWavePoolTableChunk();
1396        }
1397    
1398        /**
1399         * Checks if all (for DLS) mandatory chunks exist, if not they will be
1400         * created. Note that those chunks will not be made persistent until
1401         * Save() was called.
1402         */
1403        void File::__ensureMandatoryChunksExist() {
1404           // enusre 'lins' list chunk exists (mandatory for instrument definitions)
1405           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1406           if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
1407           // ensure 'ptbl' chunk exists (mandatory for samples)
1408           RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1409           if (!ptbl) {
1410               const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1411               ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
1412           }
1413           // enusre 'wvpl' list chunk exists (mandatory for samples)
1414           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1415           if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
1416        }
1417    
1418        /**
1419         * Updates (persistently) the wave pool table with offsets to all
1420         * currently available samples. <b>Caution:</b> this method assumes the
1421         * 'ptbl' chunk to be already of the correct size and the file to be
1422         * writable, so usually this method is only called after a Save() call.
1423         *
1424         * @throws Exception - if 'ptbl' chunk is too small (should only occur
1425         *                     if there's a bug)
1426         */
1427        void File::__UpdateWavePoolTableChunk() {
1428            __UpdateWavePoolTable();
1429            RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1430            const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1431            // check if 'ptbl' chunk is large enough
1432            WavePoolCount = (pSamples) ? pSamples->size() : 0;
1433            const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1434            if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1435            // save the 'ptbl' chunk's current read/write position
1436            unsigned long ulOriginalPos = ptbl->GetPos();
1437            // update headers
1438            ptbl->SetPos(0);
1439            ptbl->WriteUint32(&WavePoolHeaderSize);
1440            ptbl->WriteUint32(&WavePoolCount);
1441            // update offsets
1442            ptbl->SetPos(WavePoolHeaderSize);
1443            if (b64BitWavePoolOffsets) {
1444                for (int i = 0 ; i < WavePoolCount ; i++) {
1445                    ptbl->WriteUint32(&pWavePoolTableHi[i]);
1446                    ptbl->WriteUint32(&pWavePoolTable[i]);
1447                }
1448            } else { // conventional 32 bit offsets
1449                for (int i = 0 ; i < WavePoolCount ; i++)
1450                    ptbl->WriteUint32(&pWavePoolTable[i]);
1451            }
1452            // restore 'ptbl' chunk's original read/write position
1453            ptbl->SetPos(ulOriginalPos);
1454        }
1455    
1456        /**
1457         * Updates the wave pool table with offsets to all currently available
1458         * samples. <b>Caution:</b> this method assumes the 'wvpl' list chunk
1459         * exists already.
1460         */
1461        void File::__UpdateWavePoolTable() {
1462            WavePoolCount = (pSamples) ? pSamples->size() : 0;
1463            // resize wave pool table arrays
1464            if (pWavePoolTable)   delete[] pWavePoolTable;
1465            if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1466            pWavePoolTable   = new uint32_t[WavePoolCount];
1467            pWavePoolTableHi = new uint32_t[WavePoolCount];
1468            if (!pSamples) return;
1469            // update offsets int wave pool table
1470            RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1471            uint64_t wvplFileOffset = wvpl->GetFilePos();
1472            if (b64BitWavePoolOffsets) {
1473                SampleList::iterator iter = pSamples->begin();
1474                SampleList::iterator end  = pSamples->end();
1475                for (int i = 0 ; iter != end ; ++iter, i++) {
1476                    uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1477                    (*iter)->ulWavePoolOffset = _64BitOffset;
1478                    pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1479                    pWavePoolTable[i]   = (uint32_t) _64BitOffset;
1480                }
1481            } else { // conventional 32 bit offsets
1482                SampleList::iterator iter = pSamples->begin();
1483                SampleList::iterator end  = pSamples->end();
1484                for (int i = 0 ; iter != end ; ++iter, i++) {
1485                    uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;
1486                    (*iter)->ulWavePoolOffset = _64BitOffset;
1487                    pWavePoolTable[i] = (uint32_t) _64BitOffset;
1488                }
1489            }
1490        }
1491    
1492    
1493    
1494  // *************** Exception ***************  // *************** Exception ***************
# Line 540  namespace DLS { Line 1501  namespace DLS {
1501          std::cout << "DLS::Exception: " << Message << std::endl;          std::cout << "DLS::Exception: " << Message << std::endl;
1502      }      }
1503    
1504    
1505    // *************** functions ***************
1506    // *
1507    
1508        /**
1509         * Returns the name of this C++ library. This is usually "libgig" of
1510         * course. This call is equivalent to RIFF::libraryName() and
1511         * gig::libraryName().
1512         */
1513        String libraryName() {
1514            return PACKAGE;
1515        }
1516    
1517        /**
1518         * Returns version of this C++ library. This call is equivalent to
1519         * RIFF::libraryVersion() and gig::libraryVersion().
1520         */
1521        String libraryVersion() {
1522            return VERSION;
1523        }
1524    
1525  } // namespace DLS  } // namespace DLS

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

  ViewVC Help
Powered by ViewVC