/[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 799 by persson, Sun Jun 19 15:18:59 2005 UTC revision 800 by schoenebeck, Wed Nov 9 20:04:11 2005 UTC
# 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                  0x00000001
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            memccpy(&pData[0], &HeaderSize, 1, 2);
146            memccpy(&pData[2], &Connections, 1, 2);
147            for (uint32_t i = 0; i < Connections; i++) {
148                Connection::conn_block_t c = pConnections[i].ToConnBlock();
149                memccpy(&pData[HeaderSize + i * iEntrySize],     &c.source, 1, 2);
150                memccpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 1, 2);
151                memccpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 1, 2);
152                memccpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 1, 2);
153                memccpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 1, 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            ArticulationList::iterator iter = pArticulations->begin();
216            ArticulationList::iterator end  = pArticulations->end();
217            for (; iter != end; ++iter) {
218                (*iter)->UpdateChunks();
219            }
220        }
221    
222    
223    
224  // *************** Info  ***************  // *************** Info  ***************
225  // *  // *
226    
227        /** @brief Constructor.
228         *
229         * Initializes the info strings with values provided by a INFO list chunk.
230         *
231         * @param list - pointer to a list chunk which contains a INFO list chunk
232         */
233      Info::Info(RIFF::List* list) {      Info::Info(RIFF::List* list) {
234            pResourceListChunk = list;
235          if (list) {          if (list) {
236              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
237              if (lstINFO) {              if (lstINFO) {
# Line 154  namespace DLS { Line 255  namespace DLS {
255          }          }
256      }      }
257    
258        /** @brief Load given INFO field.
259         *
260         * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO
261         * list chunk \a lstINFO and save value to \a s.
262         */
263        void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
264            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
265            if (ck) {
266                // TODO: no check for ZSTR terminated strings yet
267                s = (char*) ck->LoadChunkData();
268                ck->ReleaseChunkData();
269            }
270        }
271    
272        /** @brief Apply given INFO field to the respective chunk.
273         *
274         * Apply given info value to info chunk with ID \a ChunkID, which is a
275         * subchunk of INFO list chunk \a lstINFO. If the given chunk already
276         * exists, value \a s will be applied, otherwise if it doesn't exist yet
277         * and \a sDefault is not an empty string, such a chunk will be created
278         * and \a sDefault will be applied.
279         *
280         * @param ChunkID  - 32 bit RIFF chunk ID of INFO subchunk
281         * @param lstINFO  - parent (INFO) RIFF list chunk
282         * @param s        - current value of info field
283         * @param sDefault - default value
284         */
285        void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
286            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
287            if (ck) { // if chunk exists already, use 's' as value
288                ck->Resize(s.size() + 1);
289                char* pData = (char*) ck->LoadChunkData();
290                memcpy(pData, s.c_str(), s.size() + 1);
291            } else if (sDefault != "") { // create chunk and use default value
292                ck = lstINFO->AddSubChunk(ChunkID, sDefault.size() + 1);
293                char* pData = (char*) ck->LoadChunkData();
294                memcpy(pData, sDefault.c_str(), sDefault.size() + 1);
295            }
296        }
297    
298        /** @brief Update chunks with current info values.
299         *
300         * Apply current INFO field values to the respective INFO chunks. You
301         * have to call File::Save() to make changes persistent.
302         */
303        void Info::UpdateChunks() {
304            if (!pResourceListChunk) return;
305    
306            // make sure INFO list chunk exists
307            RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
308            if (!lstINFO) lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
309    
310            // assemble default values in case the respective chunk is missing yet
311            String defaultName = "NONAME";
312            // get current date
313            time_t now = time(NULL);
314            tm* pNowBroken = localtime(&now);
315            String defaultCreationDate = ToString(pNowBroken->tm_year) + "-" +
316                                         ToString(pNowBroken->tm_mon)  + "-" +
317                                         ToString(pNowBroken->tm_mday);
318            String defaultSoftware = libraryName() + " " + libraryVersion();
319            String defaultComments = "Created with " + libraryName() + " " + libraryVersion();
320    
321            // save values
322            SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
323            SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
324            SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
325            SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
326            SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
327            SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
328            SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
329            SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
330            SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
331            SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
332            SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
333            SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
334            SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
335            SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
336            SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
337            SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
338        }
339    
340    
341    
342  // *************** Resource ***************  // *************** Resource ***************
343  // *  // *
344    
345        /** @brief Constructor.
346         *
347         * Initializes the 'Resource' object with values provided by a given
348         * INFO list chunk and a DLID chunk (the latter optional).
349         *
350         * @param Parent      - pointer to parent 'Resource', NULL if this is
351         *                      the toplevel 'Resource' object
352         * @param lstResource - pointer to an INFO list chunk
353         */
354      Resource::Resource(Resource* Parent, RIFF::List* lstResource) {      Resource::Resource(Resource* Parent, RIFF::List* lstResource) {
355          pParent = Parent;          pParent = Parent;
356            pResourceList = lstResource;
357    
358          pInfo = new Info(lstResource);          pInfo = new Info(lstResource);
359    
# Line 180  namespace DLS { Line 373  namespace DLS {
373          if (pInfo)  delete pInfo;          if (pInfo)  delete pInfo;
374      }      }
375    
376        /** @brief Update chunks with current Resource data.
377         *
378         * Apply Resource data persistently below the previously given resource
379         * list chunk. This will currently only include the INFO data. The DLSID
380         * will not be applied at the moment (yet).
381         *
382         * You have to call File::Save() to make changes persistent.
383         */
384        void Resource::UpdateChunks() {
385            pInfo->UpdateChunks();
386            //TODO: save DLSID
387        }
388    
389    
390    
391  // *************** Sampler ***************  // *************** Sampler ***************
392  // *  // *
393    
394      Sampler::Sampler(RIFF::List* ParentList) {      Sampler::Sampler(RIFF::List* ParentList) {
395            pParentList       = ParentList;
396          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
397          if (!wsmp) throw DLS::Exception("Mandatory <wsmp> chunk not found.");          if (wsmp) {
398          uint32_t headersize = wsmp->ReadUint32();              uiHeaderSize   = wsmp->ReadUint32();
399          UnityNote        = wsmp->ReadUint16();              UnityNote      = wsmp->ReadUint16();
400          FineTune         = wsmp->ReadInt16();              FineTune       = wsmp->ReadInt16();
401          Gain             = wsmp->ReadInt32();              Gain           = wsmp->ReadInt32();
402          SamplerOptions   = wsmp->ReadUint32();              SamplerOptions = wsmp->ReadUint32();
403                SampleLoops    = wsmp->ReadUint32();
404            } else { // 'wsmp' chunk missing
405                uiHeaderSize   = 0;
406                UnityNote      = 64;
407                FineTune       = 0; // +- 0 cents
408                Gain           = 0; // 0 dB
409                SamplerOptions = F_WSMP_NO_COMPRESSION;
410                SampleLoops    = 0;
411            }
412          NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;          NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;
413          NoSampleCompression     = SamplerOptions & F_WSMP_NO_COMPRESSION;          NoSampleCompression     = SamplerOptions & F_WSMP_NO_COMPRESSION;
         SampleLoops             = wsmp->ReadUint32();  
414          pSampleLoops            = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;          pSampleLoops            = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;
415          wsmp->SetPos(headersize);          if (SampleLoops) {
416          for (uint32_t i = 0; i < SampleLoops; i++) {              wsmp->SetPos(uiHeaderSize);
417              wsmp->Read(pSampleLoops + i, 4, 4);              for (uint32_t i = 0; i < SampleLoops; i++) {
418              if (pSampleLoops[i].Size > sizeof(sample_loop_t)) { // if loop struct was extended                  wsmp->Read(pSampleLoops + i, 4, 4);
419                  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
420                        wsmp->SetPos(pSampleLoops[i].Size - sizeof(sample_loop_t), RIFF::stream_curpos);
421                    }
422              }              }
423          }          }
424      }      }
# Line 210  namespace DLS { Line 427  namespace DLS {
427          if (pSampleLoops) delete[] pSampleLoops;          if (pSampleLoops) delete[] pSampleLoops;
428      }      }
429    
430        /**
431         * Apply all sample player options to the respective RIFF chunk. You
432         * have to call File::Save() to make changes persistent.
433         */
434        void Sampler::UpdateChunks() {
435            // make sure 'wsmp' chunk exists
436            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
437            if (!wsmp) {
438                uiHeaderSize = 20;
439                wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);
440            }
441            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
442            // update headers size
443            memccpy(&pData[0], &uiHeaderSize, 1, 4);
444            // update respective sampler options bits
445            SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
446                                                       : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
447            SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
448                                                   : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
449            // update loop definitions
450            for (uint32_t i = 0; i < SampleLoops; i++) {
451                //FIXME: this does not handle extended loop structs correctly
452                memccpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4, 4);
453            }
454        }
455    
456    
457    
458  // *************** Sample ***************  // *************** Sample ***************
459  // *  // *
460    
461        /** @brief Constructor.
462         *
463         * Load an existing sample or create a new one. A 'wave' list chunk must
464         * be given to this constructor. In case the given 'wave' list chunk
465         * contains a 'fmt' and 'data' chunk, the format and sample data will be
466         * loaded from there, otherwise default values will be used and those
467         * chunks will be created when File::Save() will be called later on.
468         *
469         * @param pFile          - pointer to DLS::File where this sample is
470         *                         located (or will be located)
471         * @param waveList       - pointer to 'wave' list chunk which is (or
472         *                         will be) associated with this sample
473         * @param WavePoolOffset - offset of this sample data from wave pool
474         *                         ('wvpl') list chunk
475         */
476      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) {
477            pWaveList = waveList;
478          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;
479          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
480          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
481          if (!pCkFormat || !pCkData) throw DLS::Exception("Mandatory chunks in wave list not found.");          if (pCkFormat) {
482                // common fields
483                FormatTag              = pCkFormat->ReadUint16();
484                Channels               = pCkFormat->ReadUint16();
485                SamplesPerSecond       = pCkFormat->ReadUint32();
486                AverageBytesPerSecond  = pCkFormat->ReadUint32();
487                BlockAlign             = pCkFormat->ReadUint16();
488                // PCM format specific
489                if (FormatTag == WAVE_FORMAT_PCM) {
490                    BitDepth     = pCkFormat->ReadUint16();
491                    FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels
492                                                                : 0;
493                } else { // unsupported sample data format
494                    BitDepth     = 0;
495                    FrameSize    = 0;
496                }
497            } else { // 'fmt' chunk missing
498                FormatTag              = WAVE_FORMAT_PCM;
499                BitDepth               = 16;
500                Channels               = 1;
501                SamplesPerSecond       = 44100;
502                AverageBytesPerSecond  = (BitDepth / 8) * SamplesPerSecond * Channels;
503                FrameSize              = (BitDepth / 8) * Channels;
504                BlockAlign             = FrameSize;
505            }
506            SamplesTotal = (pCkData) ? (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
507                                                                      : 0
508                                     : 0;
509        }
510    
511          // common fields      /** @brief Destructor.
512          FormatTag              = pCkFormat->ReadUint16();       *
513          Channels               = pCkFormat->ReadUint16();       * Removes RIFF chunks associated with this Sample and frees all
514          SamplesPerSecond       = pCkFormat->ReadUint32();       * memory occupied by this sample.
515          AverageBytesPerSecond  = pCkFormat->ReadUint32();       */
516          BlockAlign             = pCkFormat->ReadUint16();      Sample::~Sample() {
517            RIFF::List* pParent = pWaveList->GetParent();
518          // PCM format specific          pParent->DeleteSubChunk(pWaveList);
         if (FormatTag == WAVE_FORMAT_PCM) {  
             BitDepth     = pCkFormat->ReadUint16();  
             FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels  
                                                           : 0;  
             SamplesTotal = (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize  
                                                           : 0;  
         }  
         else {  
             BitDepth     = 0;  
             FrameSize    = 0;  
             SamplesTotal = 0;  
         }  
519      }      }
520    
521        /** @brief Load sample data into RAM.
522         *
523         * In case the respective 'data' chunk exists, the sample data will be
524         * loaded into RAM (if not done already) and a pointer to the data in
525         * RAM will be returned. If this is a new sample, you have to call
526         * Resize() with the desired sample size to create the mandatory RIFF
527         * chunk for the sample wave data.
528         *
529         * You can call LoadChunkData() again if you previously scheduled to
530         * enlarge the sample data RIFF chunk with a Resize() call. In that case
531         * the buffer will be enlarged to the new, scheduled size and you can
532         * already place the sample wave data to the buffer and finally call
533         * File::Save() to enlarge the sample data's chunk physically and write
534         * the new sample wave data in one rush. This approach is definitely
535         * recommended if you have to enlarge and write new sample data to a lot
536         * of samples.
537         *
538         * <b>Caution:</b> the buffer pointer will be invalidated once
539         * File::Save() was called. You have to call LoadChunkData() again to
540         * get a new, valid pointer whenever File::Save() was called.
541         *
542         * @returns pointer to sample data in RAM, NULL in case respective
543         *          'data' chunk does not exist (yet)
544         * @throws Exception if data buffer could not be enlarged
545         * @see Resize(), File::Save()
546         */
547      void* Sample::LoadSampleData() {      void* Sample::LoadSampleData() {
548          return pCkData->LoadChunkData();          return (pCkData) ? pCkData->LoadChunkData() : NULL;
549      }      }
550    
551        /** @brief Free sample data from RAM.
552         *
553         * In case sample data was previously successfully loaded into RAM with
554         * LoadSampleData(), this method will free the sample data from RAM.
555         */
556      void Sample::ReleaseSampleData() {      void Sample::ReleaseSampleData() {
557          pCkData->ReleaseChunkData();          if (pCkData) pCkData->ReleaseChunkData();
558        }
559    
560        /** @brief Returns sample size.
561         *
562         * Returns the sample wave form's data size (in sample points). This is
563         * actually the current, physical size (converted to sample points) of
564         * the RIFF chunk which encapsulates the sample's wave data. The
565         * returned value is dependant to the current FrameSize value.
566         *
567         * @returns number of sample points or 0 if FormatTag != WAVE_FORMAT_PCM
568         * @see FrameSize, FormatTag
569         */
570        unsigned long Sample::GetSize() {
571            if (FormatTag != WAVE_FORMAT_PCM) return 0;
572            return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
573        }
574    
575        /** @brief Resize sample.
576         *
577         * Resizes the sample's wave form data, that is the actual size of
578         * sample wave data possible to be written for this sample. This call
579         * will return immediately and just schedule the resize operation. You
580         * should call File::Save() to actually perform the resize operation(s)
581         * "physically" to the file. As this can take a while on large files, it
582         * is recommended to call Resize() first on all samples which have to be
583         * resized and finally to call File::Save() to perform all those resize
584         * operations in one rush.
585         *
586         * The actual size (in bytes) is dependant to the current FrameSize
587         * value. You may want to set FrameSize before calling Resize().
588         *
589         * <b>Caution:</b> You cannot directly write to enlarged samples before
590         * calling File::Save() as this might exceed the current sample's
591         * boundary!
592         *
593         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
594         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
595         * other formats will fail!
596         *
597         * @param iNewSize - new sample wave data size in sample points (must be
598         *                   greater than zero)
599         * @throws Excecption if FormatTag != WAVE_FORMAT_PCM
600         * @throws Exception if \a iNewSize is less than 1
601         * @see File::Save(), FrameSize, FormatTag
602         */
603        void Sample::Resize(int iNewSize) {
604            if (FormatTag != WAVE_FORMAT_PCM) throw Exception("Sample's format is not WAVE_FORMAT_PCM");
605            if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");
606            const int iSizeInBytes = iNewSize * FrameSize;
607            pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
608            if (pCkData) pCkData->Resize(iSizeInBytes);
609            else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);
610      }      }
611    
612      /**      /**
# Line 256  namespace DLS { Line 614  namespace DLS {
614       * 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
615       * the sample into RAM, thus for disk streaming.       * the sample into RAM, thus for disk streaming.
616       *       *
617         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
618         * FormatTag must be WAVE_FORMAT_PCM. Trying to reposition the sample
619         * with other formats will fail!
620         *
621       * @param SampleCount  number of sample points       * @param SampleCount  number of sample points
622       * @param Whence       to which relation \a SampleCount refers to       * @param Whence       to which relation \a SampleCount refers to
623         * @returns new position within the sample, 0 if
624         *          FormatTag != WAVE_FORMAT_PCM
625         * @throws Exception if no data RIFF chunk was created for the sample yet
626         * @see FrameSize, FormatTag
627       */       */
628      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
629          if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
630            if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
631          unsigned long orderedBytes = SampleCount * FrameSize;          unsigned long orderedBytes = SampleCount * FrameSize;
632          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          unsigned long result = pCkData->SetPos(orderedBytes, Whence);
633          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
# Line 281  namespace DLS { Line 648  namespace DLS {
648          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?
649      }      }
650    
651        /** @brief Write sample wave data.
652         *
653         * Writes \a SampleCount number of sample points from the buffer pointed
654         * by \a pBuffer and increments the position within the sample. Use this
655         * method to directly write the sample data to disk, i.e. if you don't
656         * want or cannot load the whole sample data into RAM.
657         *
658         * You have to Resize() the sample to the desired size and call
659         * File::Save() <b>before</b> using Write().
660         *
661         * @param pBuffer     - source buffer
662         * @param SampleCount - number of sample points to write
663         * @throws Exception if current sample size is too small
664         * @see LoadSampleData()
665         */
666        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
667            if (FormatTag != WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
668            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
669            return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
670        }
671    
672        /**
673         * Apply sample and its settings to the respective RIFF chunks. You have
674         * to call File::Save() to make changes persistent.
675         *
676         * @throws Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
677         *                   was provided yet
678         */
679        void Sample::UpdateChunks() {
680            if (FormatTag != WAVE_FORMAT_PCM)
681                throw Exception("Could not save sample, only PCM format is supported");
682            // we refuse to do anything if not sample wave form was provided yet
683            if (!pCkData)
684                throw Exception("Could not save sample, there is no sample data to save");
685            // update chunks of base class as well
686            Resource::UpdateChunks();
687            // make sure 'fmt' chunk exists
688            RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
689            if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
690            uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
691            // update 'fmt' chunk
692            memccpy(&pData[0], &FormatTag, 1, 2);
693            memccpy(&pData[2], &Channels,  1, 2);
694            memccpy(&pData[4], &SamplesPerSecond, 1, 4);
695            memccpy(&pData[8], &AverageBytesPerSecond, 1, 4);
696            memccpy(&pData[12], &BlockAlign, 1, 2);
697            memccpy(&pData[14], &BitDepth, 1, 2); // assuming PCM format
698        }
699    
700    
701    
702  // *************** Region ***************  // *************** Region ***************
# Line 289  namespace DLS { Line 705  namespace DLS {
705      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) {
706          pCkRegion = rgnList;          pCkRegion = rgnList;
707    
708            // articulation informations
709          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
710          rgnh->Read(&KeyRange, 2, 2);          if (rgnh) {
711          rgnh->Read(&VelocityRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
712          uint16_t optionflags = rgnh->ReadUint16();              rgnh->Read(&VelocityRange, 2, 2);
713          SelfNonExclusive = optionflags & F_RGN_OPTION_SELFNONEXCLUSIVE;              FormatOptionFlags = rgnh->ReadUint16();
714          KeyGroup = rgnh->ReadUint16();              KeyGroup = rgnh->ReadUint16();
715          // Layer is optional              // Layer is optional
716          if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {              if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
717              rgnh->Read(&Layer, 1, sizeof(uint16_t));                  rgnh->Read(&Layer, 1, sizeof(uint16_t));
718                } else Layer = 0;
719            } else { // 'rgnh' chunk is missing
720                KeyRange.low  = 0;
721                KeyRange.high = 127;
722                VelocityRange.low  = 0;
723                VelocityRange.high = 127;
724                FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
725                KeyGroup = 0;
726                Layer = 0;
727          }          }
728          else Layer = 0;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
729    
730            // sample informations
731          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
732          optionflags  = wlnk->ReadUint16();          if (wlnk) {
733          PhaseMaster  = optionflags & F_WAVELINK_PHASE_MASTER;              WaveLinkOptionFlags = wlnk->ReadUint16();
734          MultiChannel = optionflags & F_WAVELINK_MULTICHANNEL;              PhaseGroup          = wlnk->ReadUint16();
735          PhaseGroup         = wlnk->ReadUint16();              Channel             = wlnk->ReadUint32();
736          Channel            = wlnk->ReadUint32();              WavePoolTableIndex  = wlnk->ReadUint32();
737          WavePoolTableIndex = wlnk->ReadUint32();          } else { // 'wlnk' chunk is missing
738                WaveLinkOptionFlags = 0;
739                PhaseGroup          = 0;
740                Channel             = 0; // mono
741                WavePoolTableIndex  = 0; // first entry in wave pool table
742            }
743            PhaseMaster  = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
744            MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
745    
746          pSample = NULL;          pSample = NULL;
747      }      }
748    
749        /** @brief Destructor.
750         *
751         * Removes RIFF chunks associated with this Region.
752         */
753      Region::~Region() {      Region::~Region() {
754            RIFF::List* pParent = pCkRegion->GetParent();
755            pParent->DeleteSubChunk(pCkRegion);
756      }      }
757    
758      Sample* Region::GetSample() {      Sample* Region::GetSample() {
# Line 327  namespace DLS { Line 767  namespace DLS {
767          return NULL;          return NULL;
768      }      }
769    
770        /**
771         * Assign another sample to this Region.
772         *
773         * @param pSample - sample to be assigned
774         */
775        void Region::SetSample(Sample* pSample) {
776            this->pSample = pSample;
777            WavePoolTableIndex = 0; // we update this offset when we Save()
778        }
779    
780        /**
781         * Apply Region settings to the respective RIFF chunks. You have to
782         * call File::Save() to make changes persistent.
783         *
784         * @throws Exception - if the Region's sample could not be found
785         */
786        void Region::UpdateChunks() {
787            // make sure 'rgnh' chunk exists
788            RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
789            if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, 14);
790            uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
791            FormatOptionFlags = (SelfNonExclusive)
792                                    ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
793                                    : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
794            // update 'rgnh' chunk
795            memccpy(&pData[0], &KeyRange, 2, 2);
796            memccpy(&pData[4], &VelocityRange, 2, 2);
797            memccpy(&pData[8], &FormatOptionFlags, 1, 2);
798            memccpy(&pData[10], &KeyGroup, 1, 2);
799            memccpy(&pData[12], &Layer, 1, 2);
800    
801            // update chunks of base classes as well
802            Resource::UpdateChunks();
803            Articulator::UpdateChunks();
804            Sampler::UpdateChunks();
805    
806            // make sure 'wlnk' chunk exists
807            RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
808            if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
809            pData = (uint8_t*) wlnk->LoadChunkData();
810            WaveLinkOptionFlags = (PhaseMaster)
811                                      ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
812                                      : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
813            WaveLinkOptionFlags = (MultiChannel)
814                                      ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
815                                      : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
816            // get sample's wave pool table index
817            int index = -1;
818            File* pFile = (File*) GetParent()->GetParent();
819            File::SampleList::iterator iter = pFile->pSamples->begin();
820            File::SampleList::iterator end  = pFile->pSamples->end();
821            for (int i = 0; iter != end; ++iter, i++) {
822                if (*iter == pSample) {
823                    index = i;
824                    break;
825                }
826            }
827            if (index < 0) throw Exception("Could not save Region, could not find Region's sample");
828            WavePoolTableIndex = index;
829            // update 'wlnk' chunk
830            memccpy(&pData[0], &WaveLinkOptionFlags, 1, 2);
831            memccpy(&pData[2], &PhaseGroup, 1, 2);
832            memccpy(&pData[4], &Channel, 1, 4);
833            memccpy(&pData[8], &WavePoolTableIndex, 1, 4);
834        }
835    
836    
837    
838  // *************** Instrument ***************  // *************** Instrument ***************
839  // *  // *
840    
841        /** @brief Constructor.
842         *
843         * Load an existing instrument definition or create a new one. An 'ins'
844         * list chunk must be given to this constructor. In case this 'ins' list
845         * chunk contains a 'insh' chunk, the instrument data fields will be
846         * loaded from there, otherwise default values will be used and the
847         * 'insh' chunk will be created once File::Save() was called.
848         *
849         * @param pFile   - pointer to DLS::File where this instrument is
850         *                  located (or will be located)
851         * @param insList - pointer to 'ins' list chunk which is (or will be)
852         *                  associated with this instrument
853         */
854      Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
855          pCkInstrument = insList;          pCkInstrument = insList;
856    
         RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);  
         if (!insh) throw DLS::Exception("Mandatory chunks in <lins> list chunk not found.");  
         Regions = insh->ReadUint32();  
857          midi_locale_t locale;          midi_locale_t locale;
858          insh->Read(&locale, 2, 4);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
859            if (insh) {
860                Regions = insh->ReadUint32();
861                insh->Read(&locale, 2, 4);
862            } else { // 'insh' chunk missing
863                Regions = 0;
864                locale.bank       = 0;
865                locale.instrument = 0;
866            }
867    
868          MIDIProgram    = locale.instrument;          MIDIProgram    = locale.instrument;
869          IsDrum         = locale.bank & DRUM_TYPE_MASK;          IsDrum         = locale.bank & DRUM_TYPE_MASK;
870          MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);          MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
871          MIDIBankFine   = (uint8_t) MIDI_BANK_FINE(locale.bank);          MIDIBankFine   = (uint8_t) MIDI_BANK_FINE(locale.bank);
872          MIDIBank       = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);          MIDIBank       = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
873    
874          pRegions   = NULL;          pRegions = NULL;
875      }      }
876    
877      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
# Line 376  namespace DLS { Line 901  namespace DLS {
901          }          }
902      }      }
903    
904        Region* Instrument::AddRegion() {
905            if (!pRegions) pRegions = new RegionList;
906            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
907            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
908            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
909            Region* pNewRegion = new Region(this, rgn);
910            pRegions->push_back(pNewRegion);
911            return pNewRegion;
912        }
913    
914        void Instrument::DeleteRegion(Region* pRegion) {
915            RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
916            if (iter == pRegions->end()) return;
917            pRegions->erase(iter);
918            delete pRegion;
919        }
920    
921        /**
922         * Apply Instrument with all its Regions to the respective RIFF chunks.
923         * You have to call File::Save() to make changes persistent.
924         *
925         * @throws Exception - on errors
926         */
927        void Instrument::UpdateChunks() {
928            // first update base classes' chunks
929            Resource::UpdateChunks();
930            Articulator::UpdateChunks();
931            // make sure 'insh' chunk exists
932            RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
933            if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
934            uint8_t* pData = (uint8_t*) insh->LoadChunkData();
935            // update 'insh' chunk
936            Regions = pRegions->size();
937            midi_locale_t locale;
938            locale.instrument = MIDIProgram;
939            locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
940            locale.bank       = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
941            MIDIBank          = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
942            memccpy(&pData[0], &Regions, 1, 4);
943            memccpy(&pData[4], &locale, 2, 4);
944            // update Region's chunks
945            RegionList::iterator iter = pRegions->begin();
946            RegionList::iterator end  = pRegions->end();
947            for (; iter != end; ++iter) {
948                (*iter)->UpdateChunks();
949            }
950        }
951    
952        /** @brief Destructor.
953         *
954         * Removes RIFF chunks associated with this Instrument and frees all
955         * memory occupied by this instrument.
956         */
957      Instrument::~Instrument() {      Instrument::~Instrument() {
958          if (pRegions) {          if (pRegions) {
959              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
# Line 386  namespace DLS { Line 964  namespace DLS {
964              }              }
965              delete pRegions;              delete pRegions;
966          }          }
967            // remove instrument's chunks
968            RIFF::List* pParent = pCkInstrument->GetParent();
969            pParent->DeleteSubChunk(pCkInstrument);
970      }      }
971    
972    
# Line 393  namespace DLS { Line 974  namespace DLS {
974  // *************** File ***************  // *************** File ***************
975  // *  // *
976    
977        /** @brief Constructor.
978         *
979         * Default constructor, use this to create an empty DLS file. You have
980         * to add samples, instruments and finally call Save() to actually write
981         * a DLS file.
982         */
983        File::File() : pRIFF(new RIFF::File(RIFF_TYPE_DLS)), Resource(NULL, pRIFF) {
984            pVersion = new version_t;
985            pVersion->major   = 0;
986            pVersion->minor   = 0;
987            pVersion->release = 0;
988            pVersion->build   = 0;
989    
990            Instruments      = 0;
991            WavePoolCount    = 0;
992            pWavePoolTable   = NULL;
993            pWavePoolTableHi = NULL;
994            WavePoolHeaderSize = 8;
995    
996            pSamples     = NULL;
997            pInstruments = NULL;
998    
999            b64BitWavePoolOffsets = false;
1000        }
1001    
1002        /** @brief Constructor.
1003         *
1004         * Load an existing DLS file.
1005         *
1006         * @param pRIFF - pointer to a RIFF file which is actually the DLS file
1007         *                to load
1008         * @throws Exception if given file is not a DLS file, expected chunks
1009         *                   are missing
1010         */
1011      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1012          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1013          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
# Line 410  namespace DLS { Line 1025  namespace DLS {
1025    
1026          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1027          if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");          if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");
1028          uint32_t headersize = ptbl->ReadUint32();          WavePoolHeaderSize = ptbl->ReadUint32();
1029          WavePoolCount  = ptbl->ReadUint32();          WavePoolCount  = ptbl->ReadUint32();
1030          pWavePoolTable = new uint32_t[WavePoolCount];          pWavePoolTable = new uint32_t[WavePoolCount];
1031          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
1032          ptbl->SetPos(headersize);          ptbl->SetPos(WavePoolHeaderSize);
1033    
1034          // Check for 64 bit offsets (used in gig v3 files)          // Check for 64 bit offsets (used in gig v3 files)
1035          if (ptbl->GetSize() - headersize == WavePoolCount * 8) {          b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1036            if (b64BitWavePoolOffsets) {
1037              for (int i = 0 ; i < WavePoolCount ; i++) {              for (int i = 0 ; i < WavePoolCount ; i++) {
1038                  pWavePoolTableHi[i] = ptbl->ReadUint32();                  pWavePoolTableHi[i] = ptbl->ReadUint32();
1039                  pWavePoolTable[i] = ptbl->ReadUint32();                  pWavePoolTable[i] = ptbl->ReadUint32();
1040                  if (pWavePoolTable[i] & 0x80000000)                  if (pWavePoolTable[i] & 0x80000000)
1041                      throw DLS::Exception("Files larger than 2 GB not yet supported");                      throw DLS::Exception("Files larger than 2 GB not yet supported");
1042              }              }
1043          }          } else { // conventional 32 bit offsets
         else {  
1044              ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));              ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1045              for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;              for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1046          }          }
# Line 504  namespace DLS { Line 1119  namespace DLS {
1119          }          }
1120      }      }
1121    
1122        /** @brief Add a new sample.
1123         *
1124         * This will create a new Sample object for the DLS file. You have to
1125         * call Save() to make this persistent to the file.
1126         *
1127         * @returns pointer to new Sample object
1128         */
1129        Sample* File::AddSample() {
1130           __ensureMandatoryChunksExist();
1131           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1132           // create new Sample object and its respective 'wave' list chunk
1133           if (!pSamples) pSamples = new SampleList;
1134           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1135           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1136           pSamples->push_back(pSample);
1137           return pSample;
1138        }
1139    
1140        /** @brief Delete a sample.
1141         *
1142         * This will delete the given Sample object from the DLS file. You have
1143         * to call Save() to make this persistent to the file.
1144         *
1145         * @param pSample - sample to delete
1146         */
1147        void File::DeleteSample(Sample* pSample) {
1148            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1149            if (iter == pSamples->end()) return;
1150            pSamples->erase(iter);
1151            delete pSample;
1152        }
1153    
1154      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
1155          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
1156          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
# Line 530  namespace DLS { Line 1177  namespace DLS {
1177              }              }
1178          }          }
1179      }      }
1180    
1181        /** @brief Add a new instrument definition.
1182         *
1183         * This will create a new Instrument object for the DLS file. You have
1184         * to call Save() to make this persistent to the file.
1185         *
1186         * @returns pointer to new Instrument object
1187         */
1188        Instrument* File::AddInstrument() {
1189           __ensureMandatoryChunksExist();
1190           if (!pInstruments) pInstruments = new InstrumentList;
1191           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1192           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1193           Instrument* pInstrument = new Instrument(this, lstInstr);
1194           pInstruments->push_back(pInstrument);
1195           return pInstrument;
1196        }
1197    
1198        /** @brief Delete a instrument.
1199         *
1200         * This will delete the given Instrument object from the DLS file. You
1201         * have to call Save() to make this persistent to the file.
1202         *
1203         * @param pInstrument - instrument to delete
1204         */
1205        void File::DeleteInstrument(Instrument* pInstrument) {
1206            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1207            if (iter == pInstruments->end()) return;
1208            pInstruments->erase(iter);
1209            delete pInstrument;
1210        }
1211    
1212        /**
1213         * Apply all the DLS file's current instruments, samples and settings to
1214         * the respective RIFF chunks. You have to call Save() to make changes
1215         * persistent.
1216         *
1217         * @throws Exception - on errors
1218         */
1219        void File::UpdateChunks() {
1220            // first update base class's chunks
1221            Resource::UpdateChunks();
1222    
1223            // if version struct exists, update 'vers' chunk
1224            if (pVersion) {
1225                RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1226                if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1227                uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1228                memccpy(pData, pVersion, 2, 4);
1229            }
1230    
1231            // update 'colh' chunk
1232            Instruments = (pInstruments) ? pInstruments->size() : 0;
1233            RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1234            if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1235            uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1236            memccpy(pData, &Instruments, 1, 4);
1237    
1238            // update instrument's chunks
1239            if (pInstruments) {
1240                InstrumentList::iterator iter = pInstruments->begin();
1241                InstrumentList::iterator end  = pInstruments->end();
1242                for (; iter != end; ++iter) {
1243                    (*iter)->UpdateChunks();
1244                }
1245            }
1246    
1247            // update 'ptbl' chunk
1248            const int iSamples = (pSamples) ? pSamples->size() : 0;
1249            const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1250            RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1251            if (!ptbl)   ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
1252            const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1253            ptbl->Resize(iPtblSize);
1254            pData = (uint8_t*) ptbl->LoadChunkData();
1255            WavePoolCount = iSamples;
1256            memccpy(&pData[4], &WavePoolCount, 1, 4);
1257            // we actually update the sample offsets in the pool table when we Save()
1258            memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1259    
1260            // update sample's chunks
1261            if (pSamples) {
1262                SampleList::iterator iter = pSamples->begin();
1263                SampleList::iterator end  = pSamples->end();
1264                for (; iter != end; ++iter) {
1265                    (*iter)->UpdateChunks();
1266                }
1267            }
1268        }
1269    
1270        /** @brief Save changes to another file.
1271         *
1272         * Make all changes persistent by writing them to another file.
1273         * <b>Caution:</b> this method is optimized for writing to
1274         * <b>another</b> file, do not use it to save the changes to the same
1275         * file! Use Save() (without path argument) in that case instead!
1276         * Ignoring this might result in a corrupted file!
1277         *
1278         * After calling this method, this File object will be associated with
1279         * the new file (given by \a Path) afterwards.
1280         *
1281         * @param Path - path and file name where everything should be written to
1282         */
1283        void File::Save(const String& Path) {
1284            UpdateChunks();
1285            pRIFF->Save(Path);
1286            __UpdateWavePoolTableChunk();
1287        }
1288    
1289        /** @brief Save changes to same file.
1290         *
1291         * Make all changes persistent by writing them to the actual (same)
1292         * file. The file might temporarily grow to a higher size than it will
1293         * have at the end of the saving process.
1294         *
1295         * @throws RIFF::Exception if any kind of IO error occured
1296         * @throws DLS::Exception  if any kind of DLS specific error occured
1297         */
1298        void File::Save() {
1299            UpdateChunks();
1300            pRIFF->Save();
1301            __UpdateWavePoolTableChunk();
1302        }
1303    
1304        /**
1305         * Checks if all (for DLS) mandatory chunks exist, if not they will be
1306         * created. Note that those chunks will not be made persistent until
1307         * Save() was called.
1308         */
1309        void File::__ensureMandatoryChunksExist() {
1310           // enusre 'lins' list chunk exists (mandatory for instrument definitions)
1311           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1312           if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
1313           // ensure 'ptbl' chunk exists (mandatory for samples)
1314           RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1315           if (!ptbl) {
1316               const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1317               ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
1318           }
1319           // enusre 'wvpl' list chunk exists (mandatory for samples)
1320           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1321           if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
1322        }
1323    
1324        /**
1325         * Updates (persistently) the wave pool table with offsets to all
1326         * currently available samples. <b>Caution:</b> this method assumes the
1327         * 'ptbl' chunk to be already of the correct size, so usually this
1328         * method is only called after a Save() call.
1329         *
1330         * @throws Exception - if 'ptbl' chunk is too small (should only occur
1331         *                     if there's a bug)
1332         */
1333        void File::__UpdateWavePoolTableChunk() {
1334            __UpdateWavePoolTable();
1335            RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1336            const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1337            // check if 'ptbl' chunk is large enough
1338            WavePoolCount = pSamples->size();
1339            const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1340            if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1341            uint8_t* pData = (uint8_t*) ptbl->LoadChunkData();
1342            // update headers
1343            memccpy(&pData[0], &WavePoolHeaderSize, 1, 4);
1344            memccpy(&pData[4], &WavePoolCount, 1, 4);
1345            // update offsets
1346            if (b64BitWavePoolOffsets) {
1347                for (int i = 0 ; i < WavePoolCount ; i++) {
1348                    memccpy(&pData[WavePoolHeaderSize + i*iOffsetSize], &pWavePoolTableHi[i], 1, 4);
1349                    memccpy(&pData[WavePoolHeaderSize + i*iOffsetSize], &pWavePoolTable[i],   1, 4);
1350                }
1351            } else { // conventional 32 bit offsets
1352                for (int i = 0 ; i < WavePoolCount ; i++)
1353                    memccpy(&pData[WavePoolHeaderSize + i*iOffsetSize], &pWavePoolTable[i], 1, 4);
1354            }
1355        }
1356    
1357        /**
1358         * Updates the wave pool table with offsets to all currently available
1359         * samples. <b>Caution:</b> this method assumes the 'wvpl' list chunk
1360         * exists already.
1361         */
1362        void File::__UpdateWavePoolTable() {
1363            WavePoolCount = pSamples->size();
1364            // resize wave pool table arrays
1365            if (pWavePoolTable)   delete[] pWavePoolTable;
1366            if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1367            pWavePoolTable   = new uint32_t[WavePoolCount];
1368            pWavePoolTableHi = new uint32_t[WavePoolCount];
1369            // update offsets int wave pool table
1370            RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1371            uint64_t wvplFileOffset = wvpl->GetFilePos();
1372            if (b64BitWavePoolOffsets) {
1373                SampleList::iterator iter = pSamples->begin();
1374                SampleList::iterator end  = pSamples->end();
1375                for (int i = 0 ; iter != end ; ++iter, i++) {
1376                    uint64_t _64BitOffset = wvplFileOffset - (*iter)->pWaveList->GetFilePos() - LIST_HEADER_SIZE;
1377                    (*iter)->ulWavePoolOffset = _64BitOffset;
1378                    pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1379                    pWavePoolTable[i]   = (uint32_t) _64BitOffset;
1380                }
1381            } else { // conventional 32 bit offsets
1382                SampleList::iterator iter = pSamples->begin();
1383                SampleList::iterator end  = pSamples->end();
1384                for (int i = 0 ; iter != end ; ++iter, i++) {
1385                    uint64_t _64BitOffset = wvplFileOffset - (*iter)->pWaveList->GetFilePos() - LIST_HEADER_SIZE;
1386                    (*iter)->ulWavePoolOffset = _64BitOffset;
1387                    pWavePoolTable[i] = (uint32_t) _64BitOffset;
1388                }
1389            }
1390        }
1391    
1392    
1393    

Legend:
Removed from v.799  
changed lines
  Added in v.800

  ViewVC Help
Powered by ViewVC