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

Legend:
Removed from v.666  
changed lines
  Added in v.834

  ViewVC Help
Powered by ViewVC