libgig  4.4.1.svn7
DLS.cpp
1 /***************************************************************************
2  * *
3  * libgig - C++ cross-platform Gigasampler format file access library *
4  * *
5  * Copyright (C) 2003-2025 by Christian Schoenebeck *
6  * <cuse@users.sourceforge.net> *
7  * *
8  * This library is free software; you can redistribute it and/or modify *
9  * it under the terms of the GNU General Public License as published by *
10  * the Free Software Foundation; either version 2 of the License, or *
11  * (at your option) any later version. *
12  * *
13  * This library is distributed in the hope that it will be useful, *
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16  * GNU General Public License for more details. *
17  * *
18  * You should have received a copy of the GNU General Public License *
19  * along with this library; if not, write to the Free Software *
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21  * MA 02111-1307 USA *
22  ***************************************************************************/
23 
24 #include "DLS.h"
25 
26 #include <algorithm>
27 #include <vector>
28 #include <time.h>
29 
30 #ifdef __APPLE__
31 #include <CoreFoundation/CFUUID.h>
32 #elif defined(HAVE_UUID_UUID_H)
33 #include <uuid/uuid.h>
34 #endif
35 
36 #include "helper.h"
37 
38 // macros to decode connection transforms
39 #define CONN_TRANSFORM_SRC(x) ((x >> 10) & 0x000F)
40 #define CONN_TRANSFORM_CTL(x) ((x >> 4) & 0x000F)
41 #define CONN_TRANSFORM_DST(x) (x & 0x000F)
42 #define CONN_TRANSFORM_BIPOLAR_SRC(x) (x & 0x4000)
43 #define CONN_TRANSFORM_BIPOLAR_CTL(x) (x & 0x0100)
44 #define CONN_TRANSFORM_INVERT_SRC(x) (x & 0x8000)
45 #define CONN_TRANSFORM_INVERT_CTL(x) (x & 0x0200)
46 
47 // macros to encode connection transforms
48 #define CONN_TRANSFORM_SRC_ENCODE(x) ((x & 0x000F) << 10)
49 #define CONN_TRANSFORM_CTL_ENCODE(x) ((x & 0x000F) << 4)
50 #define CONN_TRANSFORM_DST_ENCODE(x) (x & 0x000F)
51 #define CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(x) ((x) ? 0x4000 : 0)
52 #define CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(x) ((x) ? 0x0100 : 0)
53 #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x) ((x) ? 0x8000 : 0)
54 #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x) ((x) ? 0x0200 : 0)
55 
56 #define DRUM_TYPE_MASK 0x80000000
57 
58 #define F_RGN_OPTION_SELFNONEXCLUSIVE 0x0001
59 
60 #define F_WAVELINK_PHASE_MASTER 0x0001
61 #define F_WAVELINK_MULTICHANNEL 0x0002
62 
63 #define F_WSMP_NO_TRUNCATION 0x0001
64 #define F_WSMP_NO_COMPRESSION 0x0002
65 
66 #define MIDI_BANK_COARSE(x) ((x & 0x00007F00) >> 8) // CC0
67 #define MIDI_BANK_FINE(x) (x & 0x0000007F) // CC32
68 #define MIDI_BANK_MERGE(coarse, fine) ((((uint16_t) coarse) << 7) | fine) // CC0 + CC32
69 #define MIDI_BANK_ENCODE(coarse, fine) (((coarse & 0x0000007F) << 8) | (fine & 0x0000007F))
70 
71 namespace DLS {
72 
73 // *************** Connection ***************
74 // *
75 
76  void Connection::Init(conn_block_t* Header) {
77  Source = (conn_src_t) Header->source;
78  Control = (conn_src_t) Header->control;
79  Destination = (conn_dst_t) Header->destination;
80  Scale = Header->scale;
81  SourceTransform = (conn_trn_t) CONN_TRANSFORM_SRC(Header->transform);
82  ControlTransform = (conn_trn_t) CONN_TRANSFORM_CTL(Header->transform);
83  DestinationTransform = (conn_trn_t) CONN_TRANSFORM_DST(Header->transform);
84  SourceInvert = CONN_TRANSFORM_INVERT_SRC(Header->transform);
85  SourceBipolar = CONN_TRANSFORM_BIPOLAR_SRC(Header->transform);
86  ControlInvert = CONN_TRANSFORM_INVERT_CTL(Header->transform);
87  ControlBipolar = CONN_TRANSFORM_BIPOLAR_CTL(Header->transform);
88  }
89 
90  Connection::conn_block_t Connection::ToConnBlock() {
91  conn_block_t c;
92  c.source = Source;
93  c.control = Control;
94  c.destination = Destination;
95  c.scale = Scale;
96  c.transform = CONN_TRANSFORM_SRC_ENCODE(SourceTransform) |
97  CONN_TRANSFORM_CTL_ENCODE(ControlTransform) |
98  CONN_TRANSFORM_DST_ENCODE(DestinationTransform) |
99  CONN_TRANSFORM_INVERT_SRC_ENCODE(SourceInvert) |
100  CONN_TRANSFORM_BIPOLAR_SRC_ENCODE(SourceBipolar) |
101  CONN_TRANSFORM_INVERT_CTL_ENCODE(ControlInvert) |
102  CONN_TRANSFORM_BIPOLAR_CTL_ENCODE(ControlBipolar);
103  return c;
104  }
105 
106 
107 
108 // *************** Articulation ***************
109 // *
110 
120  pArticulationCk = artl;
121  if (artl->GetChunkID() != CHUNK_ID_ART2 &&
122  artl->GetChunkID() != CHUNK_ID_ARTL) {
123  throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
124  }
125 
126  artl->SetPos(0);
127 
128  HeaderSize = artl->ReadUint32();
129  Connections = artl->ReadUint32();
130  artl->SetPos(HeaderSize);
131 
133  Connection::conn_block_t connblock;
134  for (uint32_t i = 0; i < Connections; i++) {
135  artl->Read(&connblock.source, 1, 2);
136  artl->Read(&connblock.control, 1, 2);
137  artl->Read(&connblock.destination, 1, 2);
138  artl->Read(&connblock.transform, 1, 2);
139  artl->Read(&connblock.scale, 1, 4);
140  pConnections[i].Init(&connblock);
141  }
142  }
143 
144  Articulation::~Articulation() {
145  if (pConnections) delete[] pConnections;
146  }
147 
154  void Articulation::UpdateChunks(progress_t* /*pProgress*/) {
155  const int iEntrySize = 12; // 12 bytes per connection block
156  pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
157  uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
158  store16(&pData[0], HeaderSize);
159  store16(&pData[2], Connections);
160  for (uint32_t i = 0; i < Connections; i++) {
161  Connection::conn_block_t c = pConnections[i].ToConnBlock();
162  store16(&pData[HeaderSize + i * iEntrySize], c.source);
163  store16(&pData[HeaderSize + i * iEntrySize + 2], c.control);
164  store16(&pData[HeaderSize + i * iEntrySize + 4], c.destination);
165  store16(&pData[HeaderSize + i * iEntrySize + 6], c.transform);
166  store32(&pData[HeaderSize + i * iEntrySize + 8], c.scale);
167  }
168  }
169 
180  }
181 
182 
183 
184 // *************** Articulator ***************
185 // *
186 
187  Articulator::Articulator(RIFF::List* ParentList) {
188  pParentList = ParentList;
189  pArticulations = NULL;
190  }
191 
201  if (!pArticulations) LoadArticulations();
202  if (!pArticulations) return NULL;
203  if (pos >= pArticulations->size()) return NULL;
204  return (*pArticulations)[pos];
205  }
206 
217  if (!pArticulations) LoadArticulations();
218  if (!pArticulations) return NULL;
219  ArticulationsIterator = pArticulations->begin();
220  return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
221  }
222 
235  if (!pArticulations) return NULL;
236  ArticulationsIterator++;
237  return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
238  }
239 
240  void Articulator::LoadArticulations() {
241  // prefer articulation level 2
242  RIFF::List* lart = pParentList->GetSubList(LIST_TYPE_LAR2);
243  if (!lart) lart = pParentList->GetSubList(LIST_TYPE_LART);
244  if (lart) {
245  uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2
246  : CHUNK_ID_ARTL;
247  size_t i = 0;
248  for (RIFF::Chunk* art = lart->GetSubChunkAt(i); art;
249  art = lart->GetSubChunkAt(++i))
250  {
251  if (art->GetChunkID() == artCkType) {
252  if (!pArticulations) pArticulations = new ArticulationList;
253  pArticulations->push_back(new Articulation(art));
254  }
255  }
256  }
257  }
258 
259  Articulator::~Articulator() {
260  if (pArticulations) {
261  ArticulationList::iterator iter = pArticulations->begin();
262  ArticulationList::iterator end = pArticulations->end();
263  while (iter != end) {
264  delete *iter;
265  iter++;
266  }
267  delete pArticulations;
268  }
269  }
270 
278  if (pArticulations) {
279  ArticulationList::iterator iter = pArticulations->begin();
280  ArticulationList::iterator end = pArticulations->end();
281  for (; iter != end; ++iter) {
282  (*iter)->UpdateChunks(pProgress);
283  }
284  }
285  }
286 
292  if (pArticulations) {
293  ArticulationList::iterator iter = pArticulations->begin();
294  ArticulationList::iterator end = pArticulations->end();
295  for (; iter != end; ++iter) {
296  (*iter)->DeleteChunks();
297  }
298  }
299  }
300 
306  void Articulator::CopyAssign(const Articulator* /*orig*/) {
307  //TODO: implement deep copy assignment for this class
308  }
309 
310 
311 
312 // *************** Info ***************
313 // *
314 
315  // Pacify false -Wdeprecated-declarations warning raised by GCC bug
316  // when initializing 'UseFixedLengthStrings' member variable below,
317  // which GCC even raises if member variable is not initializes at all.
318  // Only do this for GCC >= 4.6, as older GCC versions don't support
319  // pragma push/pop. We don't have to include clang here at all, because
320  // clang does not have this bug.
321  #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
322  # pragma GCC diagnostic push
323  # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
324  #endif
325 
333  UseFixedLengthStrings(false)
334  {
335  // re-enable -Wdeprecated-declarations (see comment on preceeding pragma above)
336  #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
337  # pragma GCC diagnostic pop
338  #endif
339  pFixedStringLengths = NULL;
340  pResourceListChunk = list;
341  if (list) {
342  RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
343  if (lstINFO) {
344  LoadString(CHUNK_ID_INAM, lstINFO, Name);
345  LoadString(CHUNK_ID_IARL, lstINFO, ArchivalLocation);
346  LoadString(CHUNK_ID_ICRD, lstINFO, CreationDate);
347  LoadString(CHUNK_ID_ICMT, lstINFO, Comments);
348  LoadString(CHUNK_ID_IPRD, lstINFO, Product);
349  LoadString(CHUNK_ID_ICOP, lstINFO, Copyright);
350  LoadString(CHUNK_ID_IART, lstINFO, Artists);
351  LoadString(CHUNK_ID_IGNR, lstINFO, Genre);
352  LoadString(CHUNK_ID_IKEY, lstINFO, Keywords);
353  LoadString(CHUNK_ID_IENG, lstINFO, Engineer);
354  LoadString(CHUNK_ID_ITCH, lstINFO, Technician);
355  LoadString(CHUNK_ID_ISFT, lstINFO, Software);
356  LoadString(CHUNK_ID_IMED, lstINFO, Medium);
357  LoadString(CHUNK_ID_ISRC, lstINFO, Source);
358  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
359  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
360  LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
361  }
362  }
363  }
364 
365  Info::~Info() {
366  }
367 
379  void Info::SetFixedStringLengths(const string_length_t* lengths) {
380  pFixedStringLengths = lengths;
381  }
382 
388  void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
389  RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
390  ::LoadString(ck, s); // function from helper.h
391  }
392 
408  void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
409  int size = 0;
410  if (pFixedStringLengths) {
411  for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
412  if (pFixedStringLengths[i].chunkId == ChunkID) {
413  size = pFixedStringLengths[i].length;
414  break;
415  }
416  }
417  }
418  RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
419  ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h
420  }
421 
429  void Info::UpdateChunks(progress_t* /*pProgress*/) {
430  if (!pResourceListChunk) return;
431 
432  // make sure INFO list chunk exists
433  RIFF::List* lstINFO = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
434 
435  String defaultName = "";
436  String defaultCreationDate = "";
437  String defaultSoftware = "";
438  String defaultComments = "";
439 
440  uint32_t resourceType = pResourceListChunk->GetListType();
441 
442  if (!lstINFO) {
443  lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
444 
445  // assemble default values
446  defaultName = "NONAME";
447 
448  if (resourceType == RIFF_TYPE_DLS) {
449  // get current date
450  time_t now = time(NULL);
451  tm* pNowBroken = localtime(&now);
452  char buf[11];
453  strftime(buf, 11, "%F", pNowBroken);
454  defaultCreationDate = buf;
455 
456  defaultComments = "Created with " + libraryName() + " " + libraryVersion();
457  }
458  if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
459  {
460  defaultSoftware = libraryName() + " " + libraryVersion();
461  }
462  }
463 
464  // save values
465 
466  SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
467  SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
468  SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
469  SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
470  SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
471  SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
472  SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
473  SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
474  SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
475  SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
476  SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
477  SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
478  SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
479  SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
480  SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
481  SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
482  SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
483  }
484 
495  }
496 
503  void Info::CopyAssign(const Info* orig) {
504  Name = orig->Name;
506  CreationDate = orig->CreationDate;
507  Comments = orig->Comments;
508  Product = orig->Product;
509  Copyright = orig->Copyright;
510  Artists = orig->Artists;
511  Genre = orig->Genre;
512  Keywords = orig->Keywords;
513  Engineer = orig->Engineer;
514  Technician = orig->Technician;
515  Software = orig->Software;
516  Medium = orig->Medium;
517  Source = orig->Source;
518  SourceForm = orig->SourceForm;
519  Commissioned = orig->Commissioned;
520  Subject = orig->Subject;
521  //FIXME: hmm, is copying this pointer a good idea?
522  pFixedStringLengths = orig->pFixedStringLengths;
523  }
524 
525 
526 
527 // *************** Resource ***************
528 // *
529 
539  Resource::Resource(Resource* Parent, RIFF::List* lstResource) {
540  pParent = Parent;
541  pResourceList = lstResource;
542 
543  pInfo = new Info(lstResource);
544 
545  RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
546  if (ckDLSID) {
547  ckDLSID->SetPos(0);
548 
549  pDLSID = new dlsid_t;
550  ckDLSID->Read(&pDLSID->ulData1, 1, 4);
551  ckDLSID->Read(&pDLSID->usData2, 1, 2);
552  ckDLSID->Read(&pDLSID->usData3, 1, 2);
553  ckDLSID->Read(pDLSID->abData, 8, 1);
554  }
555  else pDLSID = NULL;
556  }
557 
558  Resource::~Resource() {
559  if (pDLSID) delete pDLSID;
560  if (pInfo) delete pInfo;
561  }
562 
573  }
574 
586  pInfo->UpdateChunks(pProgress);
587 
588  if (pDLSID) {
589  // make sure 'dlid' chunk exists
590  RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID);
591  if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16);
592  uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
593  // update 'dlid' chunk
594  store32(&pData[0], pDLSID->ulData1);
595  store16(&pData[4], pDLSID->usData2);
596  store16(&pData[6], pDLSID->usData3);
597  memcpy(&pData[8], pDLSID->abData, 8);
598  }
599  }
600 
605  #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
606  if (!pDLSID) pDLSID = new dlsid_t;
608  #endif
609  }
610 
611  void Resource::GenerateDLSID(dlsid_t* pDLSID) {
612 #ifdef WIN32
613  UUID uuid;
614  UuidCreate(&uuid);
615  pDLSID->ulData1 = uuid.Data1;
616  pDLSID->usData2 = uuid.Data2;
617  pDLSID->usData3 = uuid.Data3;
618  memcpy(pDLSID->abData, uuid.Data4, 8);
619 
620 #elif defined(__APPLE__)
621 
622  CFUUIDRef uuidRef = CFUUIDCreate(NULL);
623  CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef);
624  CFRelease(uuidRef);
625  pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24;
626  pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8;
627  pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8;
628  pDLSID->abData[0] = uuid.byte8;
629  pDLSID->abData[1] = uuid.byte9;
630  pDLSID->abData[2] = uuid.byte10;
631  pDLSID->abData[3] = uuid.byte11;
632  pDLSID->abData[4] = uuid.byte12;
633  pDLSID->abData[5] = uuid.byte13;
634  pDLSID->abData[6] = uuid.byte14;
635  pDLSID->abData[7] = uuid.byte15;
636 #elif defined(HAVE_UUID_GENERATE)
637  uuid_t uuid;
638  uuid_generate(uuid);
639  pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
640  pDLSID->usData2 = uuid[4] | uuid[5] << 8;
641  pDLSID->usData3 = uuid[6] | uuid[7] << 8;
642  memcpy(pDLSID->abData, &uuid[8], 8);
643 #else
644 # error "Missing support for uuid generation"
645 #endif
646  }
647 
654  void Resource::CopyAssign(const Resource* orig) {
655  pInfo->CopyAssign(orig->pInfo);
656  }
657 
658 
659 // *************** Sampler ***************
660 // *
661 
662  Sampler::Sampler(RIFF::List* ParentList) {
663  pParentList = ParentList;
664  RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
665  if (wsmp) {
666  wsmp->SetPos(0);
667 
668  uiHeaderSize = wsmp->ReadUint32();
669  UnityNote = wsmp->ReadUint16();
670  FineTune = wsmp->ReadInt16();
671  Gain = wsmp->ReadInt32();
672  SamplerOptions = wsmp->ReadUint32();
673  SampleLoops = wsmp->ReadUint32();
674  } else { // 'wsmp' chunk missing
675  uiHeaderSize = 20;
676  UnityNote = 60;
677  FineTune = 0; // +- 0 cents
678  Gain = 0; // 0 dB
679  SamplerOptions = F_WSMP_NO_COMPRESSION;
680  SampleLoops = 0;
681  }
682  NoSampleDepthTruncation = SamplerOptions & F_WSMP_NO_TRUNCATION;
683  NoSampleCompression = SamplerOptions & F_WSMP_NO_COMPRESSION;
684  pSampleLoops = (SampleLoops) ? new sample_loop_t[SampleLoops] : NULL;
685  if (SampleLoops) {
686  wsmp->SetPos(uiHeaderSize);
687  for (uint32_t i = 0; i < SampleLoops; i++) {
688  wsmp->Read(pSampleLoops + i, 4, 4);
689  if (pSampleLoops[i].Size > sizeof(sample_loop_t)) { // if loop struct was extended
690  wsmp->SetPos(pSampleLoops[i].Size - sizeof(sample_loop_t), RIFF::stream_curpos);
691  }
692  }
693  }
694  }
695 
696  Sampler::~Sampler() {
697  if (pSampleLoops) delete[] pSampleLoops;
698  }
699 
700  void Sampler::SetGain(int32_t gain) {
701  Gain = gain;
702  }
703 
710  void Sampler::UpdateChunks(progress_t* /*pProgress*/) {
711  // make sure 'wsmp' chunk exists
712  RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
713  int wsmpSize = uiHeaderSize + SampleLoops * 16;
714  if (!wsmp) {
715  wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
716  } else if (wsmp->GetSize() != wsmpSize) {
717  wsmp->Resize(wsmpSize);
718  }
719  uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
720  // update headers size
721  store32(&pData[0], uiHeaderSize);
722  // update respective sampler options bits
723  SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
724  : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
725  SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
726  : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
727  store16(&pData[4], UnityNote);
728  store16(&pData[6], FineTune);
729  store32(&pData[8], Gain);
730  store32(&pData[12], SamplerOptions);
731  store32(&pData[16], SampleLoops);
732  // update loop definitions
733  for (uint32_t i = 0; i < SampleLoops; i++) {
734  //FIXME: this does not handle extended loop structs correctly
735  store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
736  store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
737  store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
738  store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
739  }
740  }
741 
752  }
753 
760  sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
761  // copy old loops array
762  for (int i = 0; i < SampleLoops; i++) {
763  pNewLoops[i] = pSampleLoops[i];
764  }
765  // add the new loop
766  pNewLoops[SampleLoops] = *pLoopDef;
767  // auto correct size field
768  pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
769  // free the old array and update the member variables
770  if (SampleLoops) delete[] pSampleLoops;
771  pSampleLoops = pNewLoops;
772  SampleLoops++;
773  }
774 
782  sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
783  // copy old loops array (skipping given loop)
784  for (int i = 0, o = 0; i < SampleLoops; i++) {
785  if (&pSampleLoops[i] == pLoopDef) continue;
786  if (o == SampleLoops - 1) {
787  delete[] pNewLoops;
788  throw Exception("Could not delete Sample Loop, because it does not exist");
789  }
790  pNewLoops[o] = pSampleLoops[i];
791  o++;
792  }
793  // free the old array and update the member variables
794  if (SampleLoops) delete[] pSampleLoops;
795  pSampleLoops = pNewLoops;
796  SampleLoops--;
797  }
798 
805  void Sampler::CopyAssign(const Sampler* orig) {
806  // copy trivial scalars
807  UnityNote = orig->UnityNote;
808  FineTune = orig->FineTune;
809  Gain = orig->Gain;
810  NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
811  NoSampleCompression = orig->NoSampleCompression;
812  SamplerOptions = orig->SamplerOptions;
813 
814  // copy sample loops
815  if (SampleLoops) delete[] pSampleLoops;
817  memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
818  SampleLoops = orig->SampleLoops;
819  }
820 
821 
822 // *************** Sample ***************
823 // *
824 
840  Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset) : Resource(pFile, waveList) {
841  pWaveList = waveList;
842  ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
843  pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
844  pCkData = waveList->GetSubChunk(CHUNK_ID_DATA);
845  if (pCkFormat) {
846  pCkFormat->SetPos(0);
847 
848  // common fields
849  FormatTag = pCkFormat->ReadUint16();
850  Channels = pCkFormat->ReadUint16();
851  SamplesPerSecond = pCkFormat->ReadUint32();
852  AverageBytesPerSecond = pCkFormat->ReadUint32();
853  BlockAlign = pCkFormat->ReadUint16();
854  // PCM format specific
855  if (FormatTag == DLS_WAVE_FORMAT_PCM) {
856  BitDepth = pCkFormat->ReadUint16();
857  FrameSize = (BitDepth / 8) * Channels;
858  } else { // unsupported sample data format
859  BitDepth = 0;
860  FrameSize = 0;
861  }
862  } else { // 'fmt' chunk missing
863  FormatTag = DLS_WAVE_FORMAT_PCM;
864  BitDepth = 16;
865  Channels = 1;
866  SamplesPerSecond = 44100;
868  FrameSize = (BitDepth / 8) * Channels;
870  }
871  SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
872  : 0
873  : 0;
874  }
875 
881  if (pCkData)
882  pCkData->ReleaseChunkData();
883  if (pCkFormat)
884  pCkFormat->ReleaseChunkData();
885  }
886 
892  // handle base class
894 
895  // handle own RIFF chunks
896  if (pWaveList) {
897  RIFF::List* pParent = pWaveList->GetParent();
898  pParent->DeleteSubChunk(pWaveList);
899  pWaveList = NULL;
900  }
901  }
902 
914  void Sample::CopyAssignCore(const Sample* orig) {
915  // handle base classes
916  Resource::CopyAssign(orig);
917  // handle actual own attributes of this class
918  FormatTag = orig->FormatTag;
919  Channels = orig->Channels;
922  BlockAlign = orig->BlockAlign;
923  BitDepth = orig->BitDepth;
924  SamplesTotal = orig->SamplesTotal;
925  FrameSize = orig->FrameSize;
926  }
927 
934  void Sample::CopyAssign(const Sample* orig) {
935  CopyAssignCore(orig);
936 
937  // copy sample waveform data (reading directly from disc)
938  Resize(orig->GetSize());
939  char* buf = (char*) LoadSampleData();
940  Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
941  const file_offset_t restorePos = pOrig->pCkData->GetPos();
942  pOrig->SetPos(0);
943  for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
944  const int iReadAtOnce = 64*1024;
945  file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
946  n = pOrig->Read(&buf[i], n);
947  if (!n) break;
948  todo -= n;
949  i += (n * pOrig->FrameSize);
950  }
951  pOrig->pCkData->SetPos(restorePos);
952  }
953 
981  return (pCkData) ? pCkData->LoadChunkData() : NULL;
982  }
983 
990  if (pCkData) pCkData->ReleaseChunkData();
991  }
992 
1003  file_offset_t Sample::GetSize() const {
1004  if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
1005  return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
1006  }
1007 
1036  void Sample::Resize(file_offset_t NewSize) {
1037  if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
1038  if (NewSize < 1) throw Exception("Sample size must be at least one sample point");
1039  if ((NewSize >> 48) != 0)
1040  throw Exception("Unrealistic high DLS sample size detected");
1041  const file_offset_t sizeInBytes = NewSize * FrameSize;
1042  pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
1043  if (pCkData) pCkData->Resize(sizeInBytes);
1044  else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
1045  }
1046 
1063  file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
1064  if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1065  if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
1066  file_offset_t orderedBytes = SampleCount * FrameSize;
1067  file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
1068  return (result == orderedBytes) ? SampleCount
1069  : result / FrameSize;
1070  }
1071 
1081  file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
1082  if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1083  return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
1084  }
1085 
1101  file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1102  if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1103  if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1104  return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
1105  }
1106 
1116  if (FormatTag != DLS_WAVE_FORMAT_PCM)
1117  throw Exception("Could not save sample, only PCM format is supported");
1118  // we refuse to do anything if not sample wave form was provided yet
1119  if (!pCkData)
1120  throw Exception("Could not save sample, there is no sample data to save");
1121  // update chunks of base class as well
1122  Resource::UpdateChunks(pProgress);
1123  // make sure 'fmt' chunk exists
1124  RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
1125  if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
1126  uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
1127  // update 'fmt' chunk
1128  store16(&pData[0], FormatTag);
1129  store16(&pData[2], Channels);
1130  store32(&pData[4], SamplesPerSecond);
1131  store32(&pData[8], AverageBytesPerSecond);
1132  store16(&pData[12], BlockAlign);
1133  store16(&pData[14], BitDepth); // assuming PCM format
1134  }
1135 
1136 
1137 
1138 // *************** Region ***************
1139 // *
1140 
1141  Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
1142  pCkRegion = rgnList;
1143 
1144  // articulation information
1145  RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1146  if (rgnh) {
1147  rgnh->SetPos(0);
1148 
1149  rgnh->Read(&KeyRange, 2, 2);
1150  rgnh->Read(&VelocityRange, 2, 2);
1151  FormatOptionFlags = rgnh->ReadUint16();
1152  KeyGroup = rgnh->ReadUint16();
1153  // Layer is optional
1154  if (rgnh->RemainingBytes() >= sizeof(uint16_t)) {
1155  rgnh->Read(&Layer, 1, sizeof(uint16_t));
1156  } else Layer = 0;
1157  } else { // 'rgnh' chunk is missing
1158  KeyRange.low = 0;
1159  KeyRange.high = 127;
1160  VelocityRange.low = 0;
1161  VelocityRange.high = 127;
1162  FormatOptionFlags = F_RGN_OPTION_SELFNONEXCLUSIVE;
1163  KeyGroup = 0;
1164  Layer = 0;
1165  }
1166  SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1167 
1168  // sample information
1169  RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1170  if (wlnk) {
1171  wlnk->SetPos(0);
1172 
1173  WaveLinkOptionFlags = wlnk->ReadUint16();
1174  PhaseGroup = wlnk->ReadUint16();
1175  Channel = wlnk->ReadUint32();
1176  WavePoolTableIndex = wlnk->ReadUint32();
1177  } else { // 'wlnk' chunk is missing
1178  WaveLinkOptionFlags = 0;
1179  PhaseGroup = 0;
1180  Channel = 0; // mono
1181  WavePoolTableIndex = 0; // first entry in wave pool table
1182  }
1183  PhaseMaster = WaveLinkOptionFlags & F_WAVELINK_PHASE_MASTER;
1184  MultiChannel = WaveLinkOptionFlags & F_WAVELINK_MULTICHANNEL;
1185 
1186  pSample = NULL;
1187  }
1188 
1195  }
1196 
1202  // handle base classes
1206 
1207  // handle own RIFF chunks
1208  if (pCkRegion) {
1209  RIFF::List* pParent = pCkRegion->GetParent();
1210  pParent->DeleteSubChunk(pCkRegion);
1211  pCkRegion = NULL;
1212  }
1213  }
1214 
1215  Sample* Region::GetSample() {
1216  if (pSample) return pSample;
1217  File* file = (File*) GetParent()->GetParent();
1218  uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1219  size_t i = 0;
1220  for (Sample* sample = file->GetSample(i); sample;
1221  sample = file->GetSample(++i))
1222  {
1223  if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1224  }
1225  return NULL;
1226  }
1227 
1233  void Region::SetSample(Sample* pSample) {
1234  this->pSample = pSample;
1235  WavePoolTableIndex = 0; // we update this offset when we Save()
1236  }
1237 
1245  void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1246  KeyRange.low = Low;
1247  KeyRange.high = High;
1248 
1249  // make sure regions are already loaded
1250  Instrument* pInstrument = (Instrument*) GetParent();
1251  if (!pInstrument->pRegions) pInstrument->LoadRegions();
1252  if (!pInstrument->pRegions) return;
1253 
1254  // find the r which is the first one to the right of this region
1255  // at its new position
1256  Region* r = NULL;
1257  Region* prev_region = NULL;
1258  for (
1259  Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1260  iter != pInstrument->pRegions->end(); iter++
1261  ) {
1262  if ((*iter)->KeyRange.low > this->KeyRange.low) {
1263  r = *iter;
1264  break;
1265  }
1266  prev_region = *iter;
1267  }
1268 
1269  // place this region before r if it's not already there
1270  if (prev_region != this) pInstrument->MoveRegion(this, r);
1271  }
1272 
1281  // make sure 'rgnh' chunk exists
1282  RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1283  if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
1284  uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
1285  FormatOptionFlags = (SelfNonExclusive)
1286  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
1287  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
1288  // update 'rgnh' chunk
1289  store16(&pData[0], KeyRange.low);
1290  store16(&pData[2], KeyRange.high);
1291  store16(&pData[4], VelocityRange.low);
1292  store16(&pData[6], VelocityRange.high);
1293  store16(&pData[8], FormatOptionFlags);
1294  store16(&pData[10], KeyGroup);
1295  if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
1296 
1297  // update chunks of base classes as well (but skip Resource,
1298  // as a rgn doesn't seem to have dlid and INFO chunks)
1299  Articulator::UpdateChunks(pProgress);
1300  Sampler::UpdateChunks(pProgress);
1301 
1302  // make sure 'wlnk' chunk exists
1303  RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
1304  if (!wlnk) wlnk = pCkRegion->AddSubChunk(CHUNK_ID_WLNK, 12);
1305  pData = (uint8_t*) wlnk->LoadChunkData();
1306  WaveLinkOptionFlags = (PhaseMaster)
1307  ? WaveLinkOptionFlags | F_WAVELINK_PHASE_MASTER
1308  : WaveLinkOptionFlags & (~F_WAVELINK_PHASE_MASTER);
1309  WaveLinkOptionFlags = (MultiChannel)
1310  ? WaveLinkOptionFlags | F_WAVELINK_MULTICHANNEL
1311  : WaveLinkOptionFlags & (~F_WAVELINK_MULTICHANNEL);
1312  // get sample's wave pool table index
1313  int index = -1;
1314  File* pFile = (File*) GetParent()->GetParent();
1315  if (pFile->pSamples) {
1316  File::SampleList::iterator iter = pFile->pSamples->begin();
1317  File::SampleList::iterator end = pFile->pSamples->end();
1318  for (int i = 0; iter != end; ++iter, i++) {
1319  if (*iter == pSample) {
1320  index = i;
1321  break;
1322  }
1323  }
1324  }
1325  WavePoolTableIndex = index;
1326  // update 'wlnk' chunk
1327  store16(&pData[0], WaveLinkOptionFlags);
1328  store16(&pData[2], PhaseGroup);
1329  store32(&pData[4], Channel);
1330  store32(&pData[8], WavePoolTableIndex);
1331  }
1332 
1342  void Region::CopyAssign(const Region* orig) {
1343  // handle base classes
1344  Resource::CopyAssign(orig);
1346  Sampler::CopyAssign(orig);
1347  // handle actual own attributes of this class
1348  // (the trivial ones)
1349  VelocityRange = orig->VelocityRange;
1350  KeyGroup = orig->KeyGroup;
1351  Layer = orig->Layer;
1352  SelfNonExclusive = orig->SelfNonExclusive;
1353  PhaseMaster = orig->PhaseMaster;
1354  PhaseGroup = orig->PhaseGroup;
1355  MultiChannel = orig->MultiChannel;
1356  Channel = orig->Channel;
1357  // only take the raw sample reference if the two Region objects are
1358  // part of the same file
1359  if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1360  WavePoolTableIndex = orig->WavePoolTableIndex;
1361  pSample = orig->pSample;
1362  } else {
1363  WavePoolTableIndex = -1;
1364  pSample = NULL;
1365  }
1366  FormatOptionFlags = orig->FormatOptionFlags;
1367  WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1368  // handle the last, a bit sensible attribute
1369  SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1370  }
1371 
1372 
1373 // *************** Instrument ***************
1374 // *
1375 
1389  Instrument::Instrument(File* pFile, RIFF::List* insList) : Resource(pFile, insList), Articulator(insList) {
1390  pCkInstrument = insList;
1391 
1392  midi_locale_t locale;
1393  RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1394  if (insh) {
1395  insh->SetPos(0);
1396 
1397  Regions = insh->ReadUint32();
1398  insh->Read(&locale, 2, 4);
1399  } else { // 'insh' chunk missing
1400  Regions = 0;
1401  locale.bank = 0;
1402  locale.instrument = 0;
1403  }
1404 
1405  MIDIProgram = locale.instrument;
1406  IsDrum = locale.bank & DRUM_TYPE_MASK;
1407  MIDIBankCoarse = (uint8_t) MIDI_BANK_COARSE(locale.bank);
1408  MIDIBankFine = (uint8_t) MIDI_BANK_FINE(locale.bank);
1409  MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine);
1410 
1411  pRegions = NULL;
1412  }
1413 
1420  if (!pRegions) LoadRegions();
1421  if (!pRegions) return 0;
1422  return pRegions->size();
1423  }
1424 
1436  if (!pRegions) LoadRegions();
1437  if (!pRegions) return NULL;
1438  if (pos >= pRegions->size()) return NULL;
1439  return (*pRegions)[pos];
1440  }
1441 
1452  if (!pRegions) LoadRegions();
1453  if (!pRegions) return NULL;
1454  RegionsIterator = pRegions->begin();
1455  return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1456  }
1457 
1469  if (!pRegions) return NULL;
1470  RegionsIterator++;
1471  return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1472  }
1473 
1474  void Instrument::LoadRegions() {
1475  if (!pRegions) pRegions = new RegionList;
1476  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1477  if (lrgn) {
1478  uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2
1479  size_t i = 0;
1480  for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn;
1481  rgn = lrgn->GetSubListAt(++i))
1482  {
1483  if (rgn->GetListType() == regionCkType) {
1484  pRegions->push_back(new Region(this, rgn));
1485  }
1486  }
1487  }
1488  }
1489 
1490  Region* Instrument::AddRegion() {
1491  if (!pRegions) LoadRegions();
1492  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1493  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
1494  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1495  Region* pNewRegion = new Region(this, rgn);
1496  const size_t idxIt = RegionsIterator - pRegions->begin();
1497  pRegions->push_back(pNewRegion);
1498  RegionsIterator = pRegions->begin() + std::min(idxIt, pRegions->size()); // avoid iterator invalidation
1499  Regions = (uint32_t) pRegions->size();
1500  return pNewRegion;
1501  }
1502 
1503  void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1504  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1505  lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1506  for (size_t i = 0; i < pRegions->size(); ++i) {
1507  if ((*pRegions)[i] == pSrc) {
1508  const size_t idxIt = RegionsIterator - pRegions->begin();
1509  pRegions->erase(pRegions->begin() + i);
1510  RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1511  pRegions->insert(iter, pSrc);
1512  RegionsIterator = pRegions->begin() + std::min(idxIt, pRegions->size()); // avoid iterator invalidation
1513  }
1514  }
1515  }
1516 
1517  void Instrument::DeleteRegion(Region* pRegion) {
1518  if (!pRegions) return;
1519  RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1520  if (iter == pRegions->end()) return;
1521  const size_t idxIt = RegionsIterator - pRegions->begin();
1522  pRegions->erase(iter);
1523  RegionsIterator = pRegions->begin() + std::min(idxIt, pRegions->size()); // avoid iterator invalidation
1524  Regions = (uint32_t) pRegions->size();
1525  pRegion->DeleteChunks();
1526  delete pRegion;
1527  }
1528 
1537  // first update base classes' chunks
1538  Resource::UpdateChunks(pProgress);
1539  Articulator::UpdateChunks(pProgress);
1540  // make sure 'insh' chunk exists
1541  RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1542  if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1543  uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1544  // update 'insh' chunk
1545  Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1546  midi_locale_t locale;
1547  locale.instrument = MIDIProgram;
1548  locale.bank = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1549  locale.bank = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
1550  MIDIBank = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
1551  store32(&pData[0], Regions);
1552  store32(&pData[4], locale.bank);
1553  store32(&pData[8], locale.instrument);
1554  // update Region's chunks
1555  if (!pRegions) return;
1556  RegionList::iterator iter = pRegions->begin();
1557  RegionList::iterator end = pRegions->end();
1558  for (int i = 0; iter != end; ++iter, ++i) {
1559  if (pProgress) {
1560  // divide local progress into subprogress
1561  progress_t subprogress;
1562  __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1563  // do the actual work
1564  (*iter)->UpdateChunks(&subprogress);
1565  } else
1566  (*iter)->UpdateChunks(NULL);
1567  }
1568  if (pProgress)
1569  __notify_progress(pProgress, 1.0); // notify done
1570  }
1571 
1577  if (pRegions) {
1578  RegionList::iterator iter = pRegions->begin();
1579  RegionList::iterator end = pRegions->end();
1580  while (iter != end) {
1581  delete *iter;
1582  iter++;
1583  }
1584  delete pRegions;
1585  }
1586  }
1587 
1593  // handle base classes
1596 
1597  // handle RIFF chunks of members
1598  if (pRegions) {
1599  RegionList::iterator it = pRegions->begin();
1600  RegionList::iterator end = pRegions->end();
1601  for (; it != end; ++it)
1602  (*it)->DeleteChunks();
1603  }
1604 
1605  // handle own RIFF chunks
1606  if (pCkInstrument) {
1607  RIFF::List* pParent = pCkInstrument->GetParent();
1608  pParent->DeleteSubChunk(pCkInstrument);
1609  pCkInstrument = NULL;
1610  }
1611  }
1612 
1613  void Instrument::CopyAssignCore(const Instrument* orig) {
1614  // handle base classes
1615  Resource::CopyAssign(orig);
1617  // handle actual own attributes of this class
1618  // (the trivial ones)
1619  IsDrum = orig->IsDrum;
1620  MIDIBank = orig->MIDIBank;
1622  MIDIBankFine = orig->MIDIBankFine;
1623  MIDIProgram = orig->MIDIProgram;
1624  }
1625 
1636  CopyAssignCore(orig);
1637  // delete all regions first
1638  while (Regions) DeleteRegion(GetRegionAt(0));
1639  // now recreate and copy regions
1640  {
1641  RegionList::const_iterator it = orig->pRegions->begin();
1642  for (int i = 0; i < orig->Regions; ++i, ++it) {
1643  Region* dstRgn = AddRegion();
1644  //NOTE: Region does semi-deep copy !
1645  dstRgn->CopyAssign(*it);
1646  }
1647  }
1648  }
1649 
1650 
1651 // *************** File ***************
1652 // *
1653 
1660  File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1661  pRIFF->SetByteOrder(RIFF::endian_little);
1662  bOwningRiff = true;
1663  pVersion = new version_t;
1664  pVersion->major = 0;
1665  pVersion->minor = 0;
1666  pVersion->release = 0;
1667  pVersion->build = 0;
1668 
1669  Instruments = 0;
1670  WavePoolCount = 0;
1671  pWavePoolTable = NULL;
1672  pWavePoolTableHi = NULL;
1673  WavePoolHeaderSize = 8;
1674 
1675  pSamples = NULL;
1676  pInstruments = NULL;
1677 
1678  b64BitWavePoolOffsets = false;
1679  }
1680 
1690  File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1691  if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1692  this->pRIFF = pRIFF;
1693  bOwningRiff = false;
1694  RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1695  if (ckVersion) {
1696  ckVersion->SetPos(0);
1697 
1698  pVersion = new version_t;
1699  ckVersion->Read(pVersion, 4, 2);
1700  }
1701  else pVersion = NULL;
1702 
1703  RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1704  if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1705  colh->SetPos(0);
1706  Instruments = colh->ReadUint32();
1707 
1708  RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1709  if (!ptbl) { // pool table is missing - this is probably an ".art" file
1710  WavePoolCount = 0;
1711  pWavePoolTable = NULL;
1712  pWavePoolTableHi = NULL;
1713  WavePoolHeaderSize = 8;
1714  b64BitWavePoolOffsets = false;
1715  } else {
1716  ptbl->SetPos(0);
1717 
1718  WavePoolHeaderSize = ptbl->ReadUint32();
1719  WavePoolCount = ptbl->ReadUint32();
1720  pWavePoolTable = new uint32_t[WavePoolCount];
1721  pWavePoolTableHi = new uint32_t[WavePoolCount];
1722  ptbl->SetPos(WavePoolHeaderSize);
1723 
1724  // Check for 64 bit offsets (used in gig v3 files)
1725  b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1726  if (b64BitWavePoolOffsets) {
1727  for (int i = 0 ; i < WavePoolCount ; i++) {
1728  pWavePoolTableHi[i] = ptbl->ReadUint32();
1729  pWavePoolTable[i] = ptbl->ReadUint32();
1730  //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1731  //if (pWavePoolTable[i] & 0x80000000)
1732  // throw DLS::Exception("Files larger than 2 GB not yet supported");
1733  }
1734  } else { // conventional 32 bit offsets
1735  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1736  for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1737  }
1738  }
1739 
1740  pSamples = NULL;
1741  pInstruments = NULL;
1742  }
1743 
1744  File::~File() {
1745  if (pInstruments) {
1746  InstrumentList::iterator iter = pInstruments->begin();
1747  InstrumentList::iterator end = pInstruments->end();
1748  while (iter != end) {
1749  delete *iter;
1750  iter++;
1751  }
1752  delete pInstruments;
1753  }
1754 
1755  if (pSamples) {
1756  SampleList::iterator iter = pSamples->begin();
1757  SampleList::iterator end = pSamples->end();
1758  while (iter != end) {
1759  delete *iter;
1760  iter++;
1761  }
1762  delete pSamples;
1763  }
1764 
1765  if (pWavePoolTable) delete[] pWavePoolTable;
1766  if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1767  if (pVersion) delete pVersion;
1768  for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1769  delete *i;
1770  if (bOwningRiff)
1771  delete pRIFF;
1772  }
1773 
1780  Sample* File::GetSample(size_t index) {
1781  if (!pSamples) LoadSamples();
1782  if (!pSamples) return NULL;
1783  if (index >= pSamples->size()) return NULL;
1784  return (*pSamples)[index];
1785  }
1786 
1795  if (!pSamples) LoadSamples();
1796  if (!pSamples) return NULL;
1797  SamplesIterator = pSamples->begin();
1798  return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1799  }
1800 
1809  if (!pSamples) return NULL;
1810  SamplesIterator++;
1811  return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1812  }
1813 
1814  void File::LoadSamples() {
1815  if (!pSamples) pSamples = new SampleList;
1816  RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1817  if (wvpl) {
1818  file_offset_t wvplFileOffset = wvpl->GetFilePos() -
1819  wvpl->GetPos(); // should be zero, but just to be sure
1820  size_t i = 0;
1821  for (RIFF::List* wave = wvpl->GetSubListAt(i); wave;
1822  wave = wvpl->GetSubListAt(++i))
1823  {
1824  if (wave->GetListType() == LIST_TYPE_WAVE) {
1825  file_offset_t waveFileOffset = wave->GetFilePos() -
1826  wave->GetPos(); // should be zero, but just to be sure
1827  pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1828  }
1829  }
1830  }
1831  else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)
1832  RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1833  if (dwpl) {
1834  file_offset_t dwplFileOffset = dwpl->GetFilePos() -
1835  dwpl->GetPos(); // should be zero, but just to be sure
1836  size_t i = 0;
1837  for (RIFF::List* wave = dwpl->GetSubListAt(i); wave;
1838  wave = dwpl->GetSubListAt(++i))
1839  {
1840  if (wave->GetListType() == LIST_TYPE_WAVE) {
1841  file_offset_t waveFileOffset = wave->GetFilePos() -
1842  wave->GetPos(); // should be zero, but just to be sure
1843  pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1844  }
1845  }
1846  }
1847  }
1848  }
1849 
1859  if (!pSamples) LoadSamples();
1860  if (!pSamples) return 0;
1861  return pSamples->size();
1862  }
1863 
1872  if (!pSamples) LoadSamples();
1874  RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1875  // create new Sample object and its respective 'wave' list chunk
1876  RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1877  Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1878  const size_t idxIt = SamplesIterator - pSamples->begin();
1879  pSamples->push_back(pSample);
1880  SamplesIterator = pSamples->begin() + std::min(idxIt, pSamples->size()); // avoid iterator invalidation
1881  return pSample;
1882  }
1883 
1891  void File::DeleteSample(Sample* pSample) {
1892  if (!pSamples) return;
1893  SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1894  if (iter == pSamples->end()) return;
1895  const size_t idxIt = SamplesIterator - pSamples->begin();
1896  pSamples->erase(iter);
1897  SamplesIterator = pSamples->begin() + std::min(idxIt, pSamples->size()); // avoid iterator invalidation
1898  pSample->DeleteChunks();
1899  delete pSample;
1900  }
1901 
1910  if (!pInstruments) LoadInstruments();
1911  if (!pInstruments) return NULL;
1912  if (index >= pInstruments->size()) return NULL;
1913  return (*pInstruments)[index];
1914  }
1915 
1924  if (!pInstruments) LoadInstruments();
1925  if (!pInstruments) return NULL;
1926  InstrumentsIterator = pInstruments->begin();
1927  return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1928  }
1929 
1938  if (!pInstruments) return NULL;
1939  InstrumentsIterator++;
1940  return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1941  }
1942 
1943  void File::LoadInstruments() {
1944  if (!pInstruments) pInstruments = new InstrumentList;
1945  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1946  if (lstInstruments) {
1947  size_t i = 0;
1948  for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i);
1949  lstInstr; lstInstr = lstInstruments->GetSubListAt(++i))
1950  {
1951  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1952  pInstruments->push_back(new Instrument(this, lstInstr));
1953  }
1954  }
1955  }
1956  }
1957 
1966  if (!pInstruments) LoadInstruments();
1968  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1969  RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1970  Instrument* pInstrument = new Instrument(this, lstInstr);
1971  const size_t idxIt = InstrumentsIterator - pInstruments->begin();
1972  pInstruments->push_back(pInstrument);
1973  InstrumentsIterator = pInstruments->begin() + std::min(idxIt, pInstruments->size()); // avoid iterator invalidation
1974  return pInstrument;
1975  }
1976 
1984  void File::DeleteInstrument(Instrument* pInstrument) {
1985  if (!pInstruments) return;
1986  InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1987  if (iter == pInstruments->end()) return;
1988  const size_t idxIt = InstrumentsIterator - pInstruments->begin();
1989  pInstruments->erase(iter);
1990  InstrumentsIterator = pInstruments->begin() + std::min(idxIt, pInstruments->size()); // avoid iterator invalidation
1991  pInstrument->DeleteChunks();
1992  delete pInstrument;
1993  }
1994 
2000  return pRIFF;
2001  }
2002 
2016  if (index < 0 || index >= ExtensionFiles.size()) return NULL;
2017  std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
2018  for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
2019  if (i == index) return *iter;
2020  return NULL;
2021  }
2022 
2033  return pRIFF->GetFileName();
2034  }
2035 
2040  void File::SetFileName(const String& name) {
2041  pRIFF->SetFileName(name);
2042  }
2043 
2052  void File::UpdateChunks(progress_t* pProgress) {
2053  // first update base class's chunks
2054  Resource::UpdateChunks(pProgress);
2055 
2056  // if version struct exists, update 'vers' chunk
2057  if (pVersion) {
2058  RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
2059  if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
2060  uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
2061  store16(&pData[0], pVersion->minor);
2062  store16(&pData[2], pVersion->major);
2063  store16(&pData[4], pVersion->build);
2064  store16(&pData[6], pVersion->release);
2065  }
2066 
2067  // update 'colh' chunk
2068  Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
2069  RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
2070  if (!colh) colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
2071  uint8_t* pData = (uint8_t*) colh->LoadChunkData();
2072  store32(pData, Instruments);
2073 
2074  // update instrument's chunks
2075  if (pInstruments) {
2076  if (pProgress) {
2077  // divide local progress into subprogress
2078  progress_t subprogress;
2079  __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
2080 
2081  // do the actual work
2082  InstrumentList::iterator iter = pInstruments->begin();
2083  InstrumentList::iterator end = pInstruments->end();
2084  for (int i = 0; iter != end; ++iter, ++i) {
2085  // divide subprogress into sub-subprogress
2086  progress_t subsubprogress;
2087  __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
2088  // do the actual work
2089  (*iter)->UpdateChunks(&subsubprogress);
2090  }
2091 
2092  __notify_progress(&subprogress, 1.0); // notify subprogress done
2093  } else {
2094  InstrumentList::iterator iter = pInstruments->begin();
2095  InstrumentList::iterator end = pInstruments->end();
2096  for (int i = 0; iter != end; ++iter, ++i) {
2097  (*iter)->UpdateChunks(NULL);
2098  }
2099  }
2100  }
2101 
2102  // update 'ptbl' chunk
2103  const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
2104  int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2105  RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2106  if (!ptbl) ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
2107  int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2108  ptbl->Resize(iPtblSize);
2109  pData = (uint8_t*) ptbl->LoadChunkData();
2110  WavePoolCount = iSamples;
2111  store32(&pData[4], WavePoolCount);
2112  // we actually update the sample offsets in the pool table when we Save()
2113  memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
2114 
2115  // update sample's chunks
2116  if (pSamples) {
2117  if (pProgress) {
2118  // divide local progress into subprogress
2119  progress_t subprogress;
2120  __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
2121 
2122  // do the actual work
2123  SampleList::iterator iter = pSamples->begin();
2124  SampleList::iterator end = pSamples->end();
2125  for (int i = 0; iter != end; ++iter, ++i) {
2126  // divide subprogress into sub-subprogress
2127  progress_t subsubprogress;
2128  __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
2129  // do the actual work
2130  (*iter)->UpdateChunks(&subsubprogress);
2131  }
2132 
2133  __notify_progress(&subprogress, 1.0); // notify subprogress done
2134  } else {
2135  SampleList::iterator iter = pSamples->begin();
2136  SampleList::iterator end = pSamples->end();
2137  for (int i = 0; iter != end; ++iter, ++i) {
2138  (*iter)->UpdateChunks(NULL);
2139  }
2140  }
2141  }
2142 
2143  // if there are any extension files, gather which ones are regular
2144  // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
2145  // and which one is probably a convolution (GigaPulse) file (always to
2146  // be saved as .gx99)
2147  std::list<RIFF::File*> poolFiles; // < for (.gx00, .gx01, ... , .gx98) files
2148  RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
2149  if (!ExtensionFiles.empty()) {
2150  std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2151  for (; it != ExtensionFiles.end(); ++it) {
2152  //FIXME: the .gx99 file is always used by GSt for convolution
2153  // data (GigaPulse); so we should better detect by subchunk
2154  // whether the extension file is intended for convolution
2155  // instead of checkking for a file name, because the latter does
2156  // not work for saving new gigs created from scratch
2157  const std::string oldName = (*it)->GetFileName();
2158  const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2159  if (isGigaPulseFile)
2160  pGigaPulseFile = *it;
2161  else
2162  poolFiles.push_back(*it);
2163  }
2164  }
2165 
2166  // update the 'xfil' chunk which describes all extension files (wave
2167  // pool files) except the .gx99 file
2168  if (!poolFiles.empty()) {
2169  const int n = poolFiles.size();
2170  const int iHeaderSize = 4;
2171  const int iEntrySize = 144;
2172 
2173  // make sure chunk exists, and with correct size
2174  RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2175  if (ckXfil)
2176  ckXfil->Resize(iHeaderSize + n * iEntrySize);
2177  else
2178  ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
2179 
2180  uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
2181 
2182  // re-assemble the chunk's content
2183  store32(pData, n);
2184  std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
2185  for (int i = 0, iOffset = 4; i < n;
2186  ++itExtFile, ++i, iOffset += iEntrySize)
2187  {
2188  // update the filename string and 5 byte extension of each extension file
2189  std::string file = lastPathComponent(
2190  (*itExtFile)->GetFileName()
2191  );
2192  if (file.length() + 6 > 128)
2193  throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
2194  uint8_t* pStrings = &pData[iOffset];
2195  memset(pStrings, 0, 128);
2196  memcpy(pStrings, file.c_str(), file.length());
2197  pStrings += file.length() + 1;
2198  std::string ext = file.substr(file.length()-5);
2199  memcpy(pStrings, ext.c_str(), 5);
2200  // update the dlsid of the extension file
2201  uint8_t* pId = &pData[iOffset + 128];
2202  dlsid_t id;
2203  RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
2204  if (ckDLSID) {
2205  ckDLSID->Read(&id.ulData1, 1, 4);
2206  ckDLSID->Read(&id.usData2, 1, 2);
2207  ckDLSID->Read(&id.usData3, 1, 2);
2208  ckDLSID->Read(id.abData, 8, 1);
2209  } else {
2210  ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
2212  uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
2213  store32(&pData[0], id.ulData1);
2214  store16(&pData[4], id.usData2);
2215  store16(&pData[6], id.usData3);
2216  memcpy(&pData[8], id.abData, 8);
2217  }
2218  store32(&pId[0], id.ulData1);
2219  store16(&pId[4], id.usData2);
2220  store16(&pId[6], id.usData3);
2221  memcpy(&pId[8], id.abData, 8);
2222  }
2223  } else {
2224  // in case there was a 'xfil' chunk, remove it
2225  RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2226  if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2227  }
2228 
2229  // update the 'doxf' chunk which describes a .gx99 extension file
2230  // which contains convolution data (GigaPulse)
2231  if (pGigaPulseFile) {
2232  RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2233  if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2234 
2235  uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2236 
2237  // update the dlsid from the extension file
2238  uint8_t* pId = &pData[132];
2239  RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2240  if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2241  throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2242  } else {
2243  dlsid_t id;
2244  // read DLS ID from extension files's DLS ID chunk
2245  uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2246  id.ulData1 = load32(&pData[0]);
2247  id.usData2 = load16(&pData[4]);
2248  id.usData3 = load16(&pData[6]);
2249  memcpy(id.abData, &pData[8], 8);
2250  // store DLS ID to 'doxf' chunk
2251  store32(&pId[0], id.ulData1);
2252  store16(&pId[4], id.usData2);
2253  store16(&pId[6], id.usData3);
2254  memcpy(&pId[8], id.abData, 8);
2255  }
2256  } else {
2257  // in case there was a 'doxf' chunk, remove it
2258  RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2259  if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2260  }
2261 
2262  // the RIFF file to be written might now been grown >= 4GB or might
2263  // been shrunk < 4GB, so we might need to update the wave pool offset
2264  // size and thus accordingly we would need to resize the wave pool
2265  // chunk
2266  const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2267  const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2268  poolFiles.size() > 0; // < 32 bit gig file where the hi 32 bits are used as extension file nr
2269  if (b64BitWavePoolOffsets != bRequires64Bit) {
2270  b64BitWavePoolOffsets = bRequires64Bit;
2271  iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2272  iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2273  ptbl->Resize(iPtblSize);
2274  }
2275 
2276  if (pProgress)
2277  __notify_progress(pProgress, 1.0); // notify done
2278  }
2279 
2294  void File::Save(const String& Path, progress_t* pProgress) {
2295  // ensure original file is open at least in read-only mode
2296  // (because it might be closed if this method is called from another
2297  // thread than file was loaded on - if IsIOPerThread() was enabled)
2298  if (pRIFF->GetMode() == RIFF::stream_mode_closed && !pRIFF->IsNew())
2299  pRIFF->SetMode(RIFF::stream_mode_read);
2300 
2301  // calculate number of tasks to notify progress appropriately
2302  const size_t nExtFiles = ExtensionFiles.size();
2303  const float tasks = nExtFiles + 1.f;
2304 
2305  // save extension files (if required)
2306  if (!ExtensionFiles.empty()) {
2307  if (pProgress) {
2308  pProgress->activity = "Saving extension files ...";
2309  __notify_progress(pProgress, 0.f);
2310  }
2311  // for assembling path of extension files to be saved to
2312  const std::string baseName = pathWithoutExtension(Path);
2313  // save the individual extension files
2314  std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2315  for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2316  //FIXME: the .gx99 file is always used by GSt for convolution
2317  // data (GigaPulse); so we should better detect by subchunk
2318  // whether the extension file is intended for convolution
2319  // instead of checkking for a file name, because the latter does
2320  // not work for saving new gigs created from scratch
2321  const std::string oldName = (*it)->GetFileName();
2322  const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2323  std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx%02d", i+1);
2324  std::string newPath = baseName + ext;
2325  // save extension file to its new location
2326  if (pProgress) {
2327  // divide local progress into subprogress
2328  progress_t subprogress;
2329  __divide_progress(pProgress, &subprogress, tasks, float(i)); // subdivided into amount of extension files
2330  // do the actual work
2331  (*it)->Save(newPath, &subprogress);
2332  } else
2333  (*it)->Save(newPath);
2334  }
2335  }
2336 
2337  progress_t subprogress;
2338  if (pProgress)
2339  __divide_progress(pProgress, &subprogress, tasks, nExtFiles);
2340 
2341  if (pProgress) {
2342  // divide local progress into subprogress
2343  progress_t subsubprogress;
2344  __divide_progress(&subprogress, &subsubprogress, 1.f, 0.f, 0.05f); // assume 5% of time
2345  subsubprogress.activity = "Updating chunks ...";
2346  __notify_progress(&subsubprogress, 0.f);
2347  // do the actual work
2348  UpdateChunks(&subsubprogress);
2349  } else
2350  UpdateChunks(NULL);
2351 
2352  if (pProgress) {
2353  // divide local progress into subprogress
2354  progress_t subsubprogress;
2355  __divide_progress(&subprogress, &subsubprogress, 1.f, 0.05f, 0.98f); // assume 93% of time
2356  subsubprogress.activity = "Writing file ...";
2357  __notify_progress(&subsubprogress, 0.f);
2358  // do the actual work
2359  pRIFF->Save(Path, &subsubprogress);
2360  } else
2361  pRIFF->Save(Path);
2362 
2363  if (pProgress) {
2364  pProgress->activity = "Updating file offsets ...";
2365  __notify_progress(pProgress, 0.98); // assume 2% of time
2366  }
2368 
2369  if (pProgress) {
2370  pProgress->activity = "Done.";
2371  __notify_progress(pProgress, 1.0); // notify done
2372  }
2373  }
2374 
2385  void File::Save(progress_t* pProgress) {
2386  // ensure file is open in read-write mode
2387  // (file might be closed entirely if this method is called from another
2388  // thread than file was loaded on - if IsIOPerThread() was enabled)
2389  if (pRIFF->GetMode() != RIFF::stream_mode_read_write && !pRIFF->IsNew())
2390  pRIFF->SetMode(RIFF::stream_mode_read_write);
2391 
2392  // calculate number of tasks to notify progress appropriately
2393  const size_t nExtFiles = ExtensionFiles.size();
2394  const float tasks = nExtFiles + 1.f;
2395 
2396  // save extension files (if required)
2397  if (!ExtensionFiles.empty()) {
2398  if (pProgress) {
2399  pProgress->activity = "Saving extension files ...";
2400  __notify_progress(pProgress, 0.f);
2401  }
2402  std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2403  for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2404  // save extension file
2405  if (pProgress) {
2406  // divide local progress into subprogress
2407  progress_t subprogress;
2408  __divide_progress(pProgress, &subprogress, tasks, float(i)); // subdivided into amount of extension files
2409  // do the actual work
2410  (*it)->Save(&subprogress);
2411  } else
2412  (*it)->Save();
2413  }
2414  }
2415 
2416  progress_t subprogress;
2417  if (pProgress)
2418  __divide_progress(pProgress, &subprogress, tasks, nExtFiles);
2419 
2420  if (pProgress) {
2421  // divide local progress into subprogress
2422  progress_t subsubprogress;
2423  __divide_progress(&subprogress, &subsubprogress, 1.f, 0.f, 0.05f); // assume 5% of time
2424  subsubprogress.activity = "Updating chunks ...";
2425  __notify_progress(&subsubprogress, 0.f);
2426  // do the actual work
2427  UpdateChunks(&subsubprogress);
2428  } else
2429  UpdateChunks(NULL);
2430 
2431  if (pProgress) {
2432  // divide local progress into subprogress
2433  progress_t subsubprogress;
2434  __divide_progress(&subprogress, &subsubprogress, 1.f, 0.05f, 0.98f); // assume 93% of time
2435  subsubprogress.activity = "Writing file ...";
2436  __notify_progress(&subsubprogress, 0.f);
2437  // do the actual work
2438  pRIFF->Save(&subsubprogress);
2439  } else
2440  pRIFF->Save();
2441 
2442  if (pProgress) {
2443  pProgress->activity = "Updating file offsets ...";
2444  __notify_progress(pProgress, 0.98); // assume 2% of time
2445  }
2447 
2448  if (pProgress)
2449  __notify_progress(pProgress, 1.0); // notify done
2450  }
2451 
2463  __UpdateWavePoolTableChunk();
2464  }
2465 
2472  // enusre 'lins' list chunk exists (mandatory for instrument definitions)
2473  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2474  if (!lstInstruments) pRIFF->AddSubList(LIST_TYPE_LINS);
2475  // ensure 'ptbl' chunk exists (mandatory for samples)
2476  RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2477  if (!ptbl) {
2478  const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2479  ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, WavePoolHeaderSize + iOffsetSize);
2480  }
2481  // enusre 'wvpl' list chunk exists (mandatory for samples)
2482  RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2483  if (!wvpl) pRIFF->AddSubList(LIST_TYPE_WVPL);
2484  }
2485 
2495  void File::__UpdateWavePoolTableChunk() {
2496  __UpdateWavePoolTable();
2497  RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2498  const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2499  // check if 'ptbl' chunk is large enough
2500  WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2501  const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2502  if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2503  // save the 'ptbl' chunk's current read/write position
2504  file_offset_t ullOriginalPos = ptbl->GetPos();
2505  // update headers
2506  ptbl->SetPos(0);
2507  uint32_t tmp = WavePoolHeaderSize;
2508  ptbl->WriteUint32(&tmp);
2509  tmp = WavePoolCount;
2510  ptbl->WriteUint32(&tmp);
2511  // update offsets
2512  ptbl->SetPos(WavePoolHeaderSize);
2513  if (b64BitWavePoolOffsets) {
2514  for (int i = 0 ; i < WavePoolCount ; i++) {
2515  tmp = pWavePoolTableHi[i];
2516  ptbl->WriteUint32(&tmp);
2517  tmp = pWavePoolTable[i];
2518  ptbl->WriteUint32(&tmp);
2519  }
2520  } else { // conventional 32 bit offsets
2521  for (int i = 0 ; i < WavePoolCount ; i++) {
2522  tmp = pWavePoolTable[i];
2523  ptbl->WriteUint32(&tmp);
2524  }
2525  }
2526  // restore 'ptbl' chunk's original read/write position
2527  ptbl->SetPos(ullOriginalPos);
2528  }
2529 
2535  void File::__UpdateWavePoolTable() {
2536  WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2537  // resize wave pool table arrays
2538  if (pWavePoolTable) delete[] pWavePoolTable;
2539  if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2540  pWavePoolTable = new uint32_t[WavePoolCount];
2541  pWavePoolTableHi = new uint32_t[WavePoolCount];
2542  if (!pSamples) return;
2543  // update offsets in wave pool table
2544  RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2545  uint64_t wvplFileOffset = wvpl->GetFilePos() -
2546  wvpl->GetPos(); // mandatory, since position might have changed
2547  if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2548  SampleList::iterator iter = pSamples->begin();
2549  SampleList::iterator end = pSamples->end();
2550  for (int i = 0 ; iter != end ; ++iter, i++) {
2551  uint64_t _64BitOffset =
2552  (*iter)->pWaveList->GetFilePos() -
2553  (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2554  wvplFileOffset -
2555  LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2556  (*iter)->ullWavePoolOffset = _64BitOffset;
2557  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2558  }
2559  } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2560  if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2561  SampleList::iterator iter = pSamples->begin();
2562  SampleList::iterator end = pSamples->end();
2563  for (int i = 0 ; iter != end ; ++iter, i++) {
2564  uint64_t _64BitOffset =
2565  (*iter)->pWaveList->GetFilePos() -
2566  (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2567  wvplFileOffset -
2568  LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2569  (*iter)->ullWavePoolOffset = _64BitOffset;
2570  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2571  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2572  }
2573  } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2574  // the main gig and the extension files may contain wave data
2575  std::vector<RIFF::File*> poolFiles;
2576  poolFiles.push_back(pRIFF);
2577  poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2578 
2579  RIFF::File* pCurPoolFile = NULL;
2580  int fileNo = 0;
2581  int waveOffset = 0;
2582  SampleList::iterator iter = pSamples->begin();
2583  SampleList::iterator end = pSamples->end();
2584  for (int i = 0 ; iter != end ; ++iter, i++) {
2585  RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2586  // if this sample is located in the same pool file as the
2587  // last we reuse the previously computed fileNo and waveOffset
2588  if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2589  pCurPoolFile = pPoolFile;
2590 
2591  std::vector<RIFF::File*>::iterator sIter;
2592  sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2593  if (sIter != poolFiles.end())
2594  fileNo = std::distance(poolFiles.begin(), sIter);
2595  else
2596  throw DLS::Exception("Fatal error, unknown pool file");
2597 
2598  RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2599  if (!extWvpl)
2600  throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2601  waveOffset =
2602  extWvpl->GetFilePos() -
2603  extWvpl->GetPos() + // mandatory, since position might have changed
2604  LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2605  }
2606  uint64_t _64BitOffset =
2607  (*iter)->pWaveList->GetFilePos() -
2608  (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2609  waveOffset;
2610  // pWavePoolTableHi stores file number when extension files are in use
2611  pWavePoolTableHi[i] = (uint32_t) fileNo;
2612  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2613  (*iter)->ullWavePoolOffset = _64BitOffset;
2614  }
2615  }
2616  }
2617  }
2618 
2619 
2620 // *************** Exception ***************
2621 // *
2622 
2623  Exception::Exception() : RIFF::Exception() {
2624  }
2625 
2626  Exception::Exception(String format, ...) : RIFF::Exception() {
2627  va_list arg;
2628  va_start(arg, format);
2629  Message = assemble(format, arg);
2630  va_end(arg);
2631  }
2632 
2633  Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2634  Message = assemble(format, arg);
2635  }
2636 
2637  void Exception::PrintMessage() const {
2638  std::cout << "DLS::Exception: " << Message << std::endl;
2639  }
2640 
2641 
2642 // *************** functions ***************
2643 // *
2644 
2650  String libraryName() {
2651  return PACKAGE;
2652  }
2653 
2658  String libraryVersion() {
2659  return VERSION;
2660  }
2661 
2662 } // namespace DLS
Provides access to the defined connections used for the synthesis model.
Definition: DLS.h:328
Connection * pConnections
Points to the beginning of a Connection array.
Definition: DLS.h:330
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Articulation object.
Definition: DLS.cpp:179
virtual void UpdateChunks(progress_t *pProgress)
Apply articulation connections to the respective RIFF chunks.
Definition: DLS.cpp:154
uint32_t Connections
Reflects the number of Connections.
Definition: DLS.h:331
Articulation(RIFF::Chunk *artl)
Constructor.
Definition: DLS.cpp:119
Abstract base class for classes that provide articulation information (thus for Instrument and Region...
Definition: DLS.h:343
virtual void UpdateChunks(progress_t *pProgress)
Apply all articulations to the respective RIFF chunks.
Definition: DLS.cpp:277
Articulation * GetNextArticulation()
Returns the next Articulation from the list of articulations.
Definition: DLS.cpp:234
Articulation * GetFirstArticulation()
Returns the first Articulation in the list of articulations.
Definition: DLS.cpp:216
Articulation * GetArticulation(size_t pos)
Returns Articulation at supplied pos position within the articulation list.
Definition: DLS.cpp:200
virtual void CopyAssign(const Articulator *orig)
Not yet implemented in this version, since the .gig format does not need to copy DLS articulators and...
Definition: DLS.cpp:306
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Articulator object.
Definition: DLS.cpp:291
Defines a connection within the synthesis model.
Definition: DLS.h:249
Will be thrown whenever a DLS specific error occurs while trying to access a DLS File.
Definition: DLS.h:624
Parses DLS Level 1 and 2 compliant files and provides abstract access to the data.
Definition: DLS.h:564
version_t * pVersion
Points to a version_t structure if the file provided a version number else is set to NULL.
Definition: DLS.h:566
Instrument * AddInstrument()
Add a new instrument definition.
Definition: DLS.cpp:1965
virtual void UpdateChunks(progress_t *pProgress)
Apply all the DLS file's current instruments, samples and settings to the respective RIFF chunks.
Definition: DLS.cpp:2052
void __ensureMandatoryChunksExist()
Checks if all (for DLS) mandatory chunks exist, if not they will be created.
Definition: DLS.cpp:2471
File()
Constructor.
Definition: DLS.cpp:1660
Instrument * GetNextInstrument()
Returns a pointer to the next Instrument object of the file, NULL otherwise.
Definition: DLS.cpp:1937
Sample * GetSample(size_t index)
Returns Sample object of index.
Definition: DLS.cpp:1780
Sample * GetNextSample()
Returns a pointer to the next Sample object of the file, NULL otherwise.
Definition: DLS.cpp:1808
void SetFileName(const String &name)
You may call this method store a future file name, so you don't have to to pass it to the Save() call...
Definition: DLS.cpp:2040
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition: DLS.cpp:2462
void DeleteInstrument(Instrument *pInstrument)
Delete an instrument.
Definition: DLS.cpp:1984
uint32_t Instruments
Reflects the number of available Instrument objects.
Definition: DLS.h:567
virtual void Save(const String &Path, progress_t *pProgress=NULL)
Save changes to another file.
Definition: DLS.cpp:2294
Instrument * GetInstrument(size_t index)
Returns the instrument with the given index from the list of instruments of this file.
Definition: DLS.cpp:1909
bool bOwningRiff
If true then pRIFF was implicitly allocated by this class and hence pRIFF will automatically be freed...
Definition: DLS.h:605
size_t CountSamples()
Returns the total amount of samples of this DLS file.
Definition: DLS.cpp:1858
void DeleteSample(Sample *pSample)
Delete a sample.
Definition: DLS.cpp:1891
RIFF::File * GetRiffFile()
Returns the underlying RIFF::File used for persistency of this DLS::File object.
Definition: DLS.cpp:1999
Sample * GetFirstSample()
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: DLS.cpp:1794
Instrument * GetFirstInstrument()
Returns a pointer to the first Instrument object of the file, NULL otherwise.
Definition: DLS.cpp:1923
Sample * AddSample()
Add a new sample.
Definition: DLS.cpp:1871
RIFF::File * GetExtensionFile(int index)
Returns extension file of given index.
Definition: DLS.cpp:2015
String GetFileName()
File name of this DLS file.
Definition: DLS.cpp:2032
Optional information for DLS files, instruments, samples, etc.
Definition: DLS.h:363
String Subject
<ISBJ-ck>. Describes the contents of the file.
Definition: DLS.h:381
String Genre
<IGNR-ck>. Descirbes the original work, such as, Jazz, Classic, Rock, Techno, Rave,...
Definition: DLS.h:372
String Keywords
<IKEY-ck>. Provides a list of keywords that refer to the file or subject of the file....
Definition: DLS.h:373
String SourceForm
<ISRF-ck>. Identifies the original form of the material that was digitized, such as record,...
Definition: DLS.h:379
String Comments
<ICMT-ck>. Provides general comments about the file or the subject of the file. Sentences might end w...
Definition: DLS.h:368
String Medium
<IMED-ck>. Describes the original subject of the file, such as, record, CD, and so forth.
Definition: DLS.h:377
void SetFixedStringLengths(const string_length_t *lengths)
Forces specific Info fields to be of a fixed length when being saved to a file.
Definition: DLS.cpp:379
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Info object.
Definition: DLS.cpp:494
Info(RIFF::List *list)
Constructor.
Definition: DLS.cpp:332
String Software
<ISFT-ck>. Identifies the name of the sofware package used to create the file.
Definition: DLS.h:376
String Artists
<IART-ck>. Lists the artist of the original subject of the file.
Definition: DLS.h:371
String Product
<IPRD-ck>. Specifies the name of the title the file was originally intended for, such as World Ruler ...
Definition: DLS.h:369
virtual void CopyAssign(const Info *orig)
Make a deep copy of the Info object given by orig and assign it to this object.
Definition: DLS.cpp:503
String Name
<INAM-ck>. Stores the title of the subject of the file, such as, Seattle From Above.
Definition: DLS.h:365
String CreationDate
<ICRD-ck>. Specifies the date the subject of the file was created. List dates in yyyy-mm-dd format.
Definition: DLS.h:367
String ArchivalLocation
<IARL-ck>. Indicates where the subject of the file is stored.
Definition: DLS.h:366
String Engineer
<IENG-ck>. Stores the name of the engineer who worked on the file. Multiple engineer names are separa...
Definition: DLS.h:374
virtual void UpdateChunks(progress_t *pProgress)
Update chunks with current info values.
Definition: DLS.cpp:429
String Commissioned
<ICMS-ck>. Lists the name of the person or organization that commissioned the subject of the file,...
Definition: DLS.h:380
String Copyright
<ICOP-ck>. Records the copyright information for the file.
Definition: DLS.h:370
String Source
<ISRC-ck>. Identifies the name of the person or organization who supplied the original subject of the...
Definition: DLS.h:378
String Technician
<ITCH-ck>. Identifies the technician who sampled the subject file.
Definition: DLS.h:375
Provides all neccessary information for the synthesis of a DLS Instrument.
Definition: DLS.h:524
virtual ~Instrument()
Destructor.
Definition: DLS.cpp:1576
virtual void CopyAssign(const Instrument *orig)
Make a (semi) deep copy of the Instrument object given by orig and assign it to this object.
Definition: DLS.cpp:1635
uint8_t MIDIBankFine
Reflects the MIDI Bank number for MIDI Control Change 32 (bank 1 - 128).
Definition: DLS.h:529
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Instrument object.
Definition: DLS.cpp:1592
Region * GetFirstRegion()
Returns the first Region of the instrument.
Definition: DLS.cpp:1451
Region * GetNextRegion()
Returns the next Region of the instrument.
Definition: DLS.cpp:1468
uint8_t MIDIBankCoarse
Reflects the MIDI Bank number for MIDI Control Change 0 (bank 1 - 128).
Definition: DLS.h:528
bool IsDrum
Indicates if the Instrument is a drum type, as they differ in the synthesis model of DLS from melodic...
Definition: DLS.h:526
uint32_t Regions
Reflects the number of Region defintions this Instrument has.
Definition: DLS.h:531
uint16_t MIDIBank
Reflects combination of MIDIBankCoarse and MIDIBankFine (bank 1 - bank 16384). Do not change this val...
Definition: DLS.h:527
Instrument(File *pFile, RIFF::List *insList)
Constructor.
Definition: DLS.cpp:1389
uint32_t MIDIProgram
Specifies the MIDI Program Change Number this Instrument should be assigned to.
Definition: DLS.h:530
Region * GetRegionAt(size_t pos)
Returns Region at supplied pos position within the region list of this instrument.
Definition: DLS.cpp:1435
size_t CountRegions()
Returns the amount of regions of this instrument.
Definition: DLS.cpp:1419
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition: DLS.cpp:1536
Defines Region information of an Instrument.
Definition: DLS.h:493
virtual void CopyAssign(const Region *orig)
Make a (semi) deep copy of the Region object given by orig and assign it to this object.
Definition: DLS.cpp:1342
virtual ~Region()
Destructor.
Definition: DLS.cpp:1194
void SetSample(Sample *pSample)
Assign another sample to this Region.
Definition: DLS.cpp:1233
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings to the respective RIFF chunks.
Definition: DLS.cpp:1280
range_t KeyRange
Definition: DLS.h:495
virtual void SetKeyRange(uint16_t Low, uint16_t High)
Modifies the key range of this Region and makes sure the respective chunks are in correct order.
Definition: DLS.cpp:1245
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Region object.
Definition: DLS.cpp:1201
Abstract base class which encapsulates data structures which all DLS resources are able to provide.
Definition: DLS.h:404
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Resource object.
Definition: DLS.cpp:572
Resource(Resource *Parent, RIFF::List *lstResource)
Constructor.
Definition: DLS.cpp:539
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
Definition: DLS.h:406
dlsid_t * pDLSID
Points to a dlsid_t structure if the file provided a DLS ID else is NULL.
Definition: DLS.h:407
virtual void UpdateChunks(progress_t *pProgress)
Update chunks with current Resource data.
Definition: DLS.cpp:585
void GenerateDLSID()
Generates a new DLSID for the resource.
Definition: DLS.cpp:604
virtual void CopyAssign(const Resource *orig)
Make a deep copy of the Resource object given by orig and assign it to this object.
Definition: DLS.cpp:654
Encapsulates sample waves used for playback.
Definition: DLS.h:457
file_offset_t Read(void *pBuffer, file_offset_t SampleCount)
Reads SampleCount number of sample points from the current position into the buffer pointed by pBuffe...
Definition: DLS.cpp:1081
void ReleaseSampleData()
Free sample data from RAM.
Definition: DLS.cpp:989
void CopyAssignCore(const Sample *orig)
Make a deep copy of the Sample object given by orig (without the actual sample waveform data however)...
Definition: DLS.cpp:914
uint16_t BlockAlign
The block alignment (in bytes) of the waveform data. Playback software needs to process a multiple of...
Definition: DLS.h:463
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
Definition: DLS.cpp:1115
void Resize(file_offset_t NewSize)
Resize sample.
Definition: DLS.cpp:1036
file_offset_t SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence=RIFF::stream_start)
Sets the position within the sample (in sample points, not in bytes).
Definition: DLS.cpp:1063
uint16_t BitDepth
Size of each sample per channel (only if known sample data format is used, 0 otherwise).
Definition: DLS.h:464
virtual void CopyAssign(const Sample *orig)
Make a deep copy of the Sample object given by orig and assign it to this object.
Definition: DLS.cpp:934
void * LoadSampleData()
Load sample data into RAM.
Definition: DLS.cpp:980
uint16_t Channels
Number of channels represented in the waveform data, e.g. 1 for mono, 2 for stereo (defaults to 1=mon...
Definition: DLS.h:460
file_offset_t GetSize() const
Returns sample size.
Definition: DLS.cpp:1003
uint32_t SamplesPerSecond
Sampling rate at which each channel should be played (defaults to 44100 if Sample was created with In...
Definition: DLS.h:461
file_offset_t SamplesTotal
Reflects total number of sample points (only if known sample data format is used, 0 otherwise),...
Definition: DLS.h:465
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Sample object.
Definition: DLS.cpp:891
uint16_t FormatTag
Format ID of the waveform data (should be DLS_WAVE_FORMAT_PCM for DLS1 compliant files,...
Definition: DLS.h:459
uint FrameSize
Reflects the size (in bytes) of one single sample point (only if known sample data format is used,...
Definition: DLS.h:466
uint32_t AverageBytesPerSecond
The average number of bytes per second at which the waveform data should be transferred (Playback sof...
Definition: DLS.h:462
virtual ~Sample()
Destructor.
Definition: DLS.cpp:880
Sample(File *pFile, RIFF::List *waveList, file_offset_t WavePoolOffset)
Constructor.
Definition: DLS.cpp:840
file_offset_t Write(void *pBuffer, file_offset_t SampleCount)
Write sample wave data.
Definition: DLS.cpp:1101
Abstract base class which provides mandatory informations about sample players in general.
Definition: DLS.h:425
virtual void DeleteChunks()
Remove all RIFF chunks associated with this Sampler object.
Definition: DLS.cpp:751
virtual void UpdateChunks(progress_t *pProgress)
Apply all sample player options to the respective RIFF chunk.
Definition: DLS.cpp:710
virtual void CopyAssign(const Sampler *orig)
Make a deep copy of the Sampler object given by orig and assign it to this object.
Definition: DLS.cpp:805
void AddSampleLoop(sample_loop_t *pLoopDef)
Adds a new sample loop with the provided loop definition.
Definition: DLS.cpp:759
uint32_t SampleLoops
Reflects the number of sample loops.
Definition: DLS.h:432
sample_loop_t * pSampleLoops
Points to the beginning of a sample loop array, or is NULL if there are no loops defined.
Definition: DLS.h:433
void DeleteSampleLoop(sample_loop_t *pLoopDef)
Deletes an existing sample loop.
Definition: DLS.cpp:781
int32_t Gain
Definition: DLS.h:429
Ordinary RIFF Chunk.
Definition: RIFF.h:186
void Resize(file_offset_t NewSize)
Resize chunk.
Definition: RIFF.cpp:1058
file_offset_t SetPos(file_offset_t Where, stream_whence_t Whence=stream_start)
Sets the position within the chunk body, thus within the data portion of the chunk (in bytes).
Definition: RIFF.cpp:365
file_offset_t GetFilePos() const
Current, actual offset in file of current chunk data body read/write position.
Definition: RIFF.cpp:348
void ReleaseChunkData()
Free loaded chunk body from RAM.
Definition: RIFF.cpp:1033
file_offset_t Write(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Writes WordCount number of data words with given WordSize from the buffer pointed by pData.
Definition: RIFF.cpp:541
file_offset_t RemainingBytes() const
Returns the number of bytes left to read in the chunk body.
Definition: RIFF.cpp:400
file_offset_t ReadUint32(uint32_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 32 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition: RIFF.cpp:812
file_offset_t GetPos() const
Current read/write position within the chunk data body (starting with 0).
Definition: RIFF.cpp:335
file_offset_t ReadUint16(uint16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition: RIFF.cpp:734
file_offset_t Read(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Reads WordCount number of data words with given WordSize and copies it into a buffer pointed by pData...
Definition: RIFF.cpp:465
file_offset_t ReadInt16(int16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit signed integer words and copies it into the buffer pointed by pData.
Definition: RIFF.cpp:695
uint32_t GetChunkID() const
Chunk ID in unsigned integer representation.
Definition: RIFF.h:190
void * LoadChunkData()
Load chunk body into RAM.
Definition: RIFF.cpp:984
file_offset_t ReadInt32(int32_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 32 Bit signed integer words and copies it into the buffer pointed by pData.
Definition: RIFF.cpp:773
List * GetParent() const
Returns pointer to the chunk's parent list chunk.
Definition: RIFF.h:192
file_offset_t WriteUint32(uint32_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 32 Bit unsigned integer words from the buffer pointed by pData to the chun...
Definition: RIFF.cpp:852
file_offset_t GetSize() const
Chunk size in bytes (without header, thus the chunk data body)
Definition: RIFF.h:193
File * GetFile() const
Returns pointer to the chunk's File object.
Definition: RIFF.h:191
RIFF File.
Definition: RIFF.h:314
bool SetMode(stream_mode_t NewMode)
Change file access mode.
Definition: RIFF.cpp:2085
int GetFileOffsetSize() const
Returns the current size (in bytes) of file offsets stored in the headers of all chunks of this file.
Definition: RIFF.cpp:2591
void SetByteOrder(endian_t Endian)
Set the byte order to be used when saving.
Definition: RIFF.cpp:2190
bool IsNew() const
Returns true if this file has been created new from scratch and has not been stored to disk yet.
Definition: RIFF.cpp:2475
file_offset_t GetRequiredFileSize()
Returns the required size (in bytes) for this RIFF File to be saved to disk.
Definition: RIFF.cpp:2527
stream_mode_t GetMode() const
Returns the file I/O mode currently being available for the calling thread for this RIFF file (either...
Definition: RIFF.cpp:2065
virtual void Save(progress_t *pProgress=NULL)
Save changes to same file.
Definition: RIFF.cpp:2208
RIFF List Chunk.
Definition: RIFF.h:262
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition: RIFF.cpp:1273
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
Definition: RIFF.cpp:1511
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
Definition: RIFF.cpp:1568
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
Definition: RIFF.cpp:1591
List * GetSubListAt(size_t pos)
Returns sublist chunk with list type ListType at supplied pos position among all subchunks of type Li...
Definition: RIFF.cpp:1291
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
Definition: RIFF.cpp:1314
uint32_t GetListType() const
Returns unsigned integer representation of the list's ID.
Definition: RIFF.h:266
Chunk * AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize)
Creates a new sub chunk.
Definition: RIFF.cpp:1485
Chunk * GetSubChunkAt(size_t pos)
Returns subchunk at supplied pos position within this chunk list.
Definition: RIFF.cpp:1256
DLS specific classes and definitions.
Definition: DLS.h:108
String libraryName()
Returns the name of this C++ library.
Definition: DLS.cpp:2650
String libraryVersion()
Returns version of this C++ library.
Definition: DLS.cpp:2658
conn_src_t
Connection Sources.
Definition: DLS.h:131
conn_dst_t
Connection Destinations.
Definition: DLS.h:157
conn_trn_t
Connection Transforms.
Definition: DLS.h:202
RIFF specific classes and definitions.
Definition: RIFF.h:101
stream_whence_t
File stream position dependent to these relations.
Definition: RIFF.h:128
uint64_t file_offset_t
Type used by libgig for handling file positioning during file I/O tasks.
Definition: RIFF.h:111
Every subject of an DLS file and the file itself can have an unique, computer generated ID.
Definition: DLS.h:123
uint16_t low
Low value of range.
Definition: DLS.h:211
uint16_t high
High value of range.
Definition: DLS.h:212
Defines Sample Loop Points.
Definition: DLS.h:235
uint32_t Size
For internal usage only: usually reflects exactly sizeof(sample_loop_t), otherwise if the value is la...
Definition: DLS.h:236
Quadtuple version number ("major.minor.release.build").
Definition: DLS.h:115
Used for indicating the progress of a certain task.
Definition: RIFF.h:167
const char * activity
Text which describes current ongoing action (e.g. to be displayed along a progress bar).
Definition: RIFF.h:171