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

Legend:
Removed from v.518  
changed lines
  Added in v.804

  ViewVC Help
Powered by ViewVC