libgig  3.3.0.19svn2660
gig.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * *
3  * libgig - C++ cross-platform Gigasampler format file access library *
4  * *
5  * Copyright (C) 2003-2014 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 "gig.h"
25 
26 #include "helper.h"
27 
28 #include <algorithm>
29 #include <math.h>
30 #include <iostream>
31 #include <assert.h>
32 
38 #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
39 
41 #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
42 #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
43 #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
44 #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
45 #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
46 #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
47 #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
48 #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
49 #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
50 #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
51 #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
52 #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
53 
54 namespace gig {
55 
56 // *************** progress_t ***************
57 // *
58 
60  callback = NULL;
61  custom = NULL;
62  __range_min = 0.0f;
63  __range_max = 1.0f;
64  }
65 
66  // private helper function to convert progress of a subprocess into the global progress
67  static void __notify_progress(progress_t* pProgress, float subprogress) {
68  if (pProgress && pProgress->callback) {
69  const float totalrange = pProgress->__range_max - pProgress->__range_min;
70  const float totalprogress = pProgress->__range_min + subprogress * totalrange;
71  pProgress->factor = totalprogress;
72  pProgress->callback(pProgress); // now actually notify about the progress
73  }
74  }
75 
76  // private helper function to divide a progress into subprogresses
77  static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
78  if (pParentProgress && pParentProgress->callback) {
79  const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
80  pSubProgress->callback = pParentProgress->callback;
81  pSubProgress->custom = pParentProgress->custom;
82  pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
83  pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
84  }
85  }
86 
87 
88 // *************** Internal functions for sample decompression ***************
89 // *
90 
91 namespace {
92 
93  inline int get12lo(const unsigned char* pSrc)
94  {
95  const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
96  return x & 0x800 ? x - 0x1000 : x;
97  }
98 
99  inline int get12hi(const unsigned char* pSrc)
100  {
101  const int x = pSrc[1] >> 4 | pSrc[2] << 4;
102  return x & 0x800 ? x - 0x1000 : x;
103  }
104 
105  inline int16_t get16(const unsigned char* pSrc)
106  {
107  return int16_t(pSrc[0] | pSrc[1] << 8);
108  }
109 
110  inline int get24(const unsigned char* pSrc)
111  {
112  const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
113  return x & 0x800000 ? x - 0x1000000 : x;
114  }
115 
116  inline void store24(unsigned char* pDst, int x)
117  {
118  pDst[0] = x;
119  pDst[1] = x >> 8;
120  pDst[2] = x >> 16;
121  }
122 
123  void Decompress16(int compressionmode, const unsigned char* params,
124  int srcStep, int dstStep,
125  const unsigned char* pSrc, int16_t* pDst,
126  unsigned long currentframeoffset,
127  unsigned long copysamples)
128  {
129  switch (compressionmode) {
130  case 0: // 16 bit uncompressed
131  pSrc += currentframeoffset * srcStep;
132  while (copysamples) {
133  *pDst = get16(pSrc);
134  pDst += dstStep;
135  pSrc += srcStep;
136  copysamples--;
137  }
138  break;
139 
140  case 1: // 16 bit compressed to 8 bit
141  int y = get16(params);
142  int dy = get16(params + 2);
143  while (currentframeoffset) {
144  dy -= int8_t(*pSrc);
145  y -= dy;
146  pSrc += srcStep;
147  currentframeoffset--;
148  }
149  while (copysamples) {
150  dy -= int8_t(*pSrc);
151  y -= dy;
152  *pDst = y;
153  pDst += dstStep;
154  pSrc += srcStep;
155  copysamples--;
156  }
157  break;
158  }
159  }
160 
161  void Decompress24(int compressionmode, const unsigned char* params,
162  int dstStep, const unsigned char* pSrc, uint8_t* pDst,
163  unsigned long currentframeoffset,
164  unsigned long copysamples, int truncatedBits)
165  {
166  int y, dy, ddy, dddy;
167 
168 #define GET_PARAMS(params) \
169  y = get24(params); \
170  dy = y - get24((params) + 3); \
171  ddy = get24((params) + 6); \
172  dddy = get24((params) + 9)
173 
174 #define SKIP_ONE(x) \
175  dddy -= (x); \
176  ddy -= dddy; \
177  dy = -dy - ddy; \
178  y += dy
179 
180 #define COPY_ONE(x) \
181  SKIP_ONE(x); \
182  store24(pDst, y << truncatedBits); \
183  pDst += dstStep
184 
185  switch (compressionmode) {
186  case 2: // 24 bit uncompressed
187  pSrc += currentframeoffset * 3;
188  while (copysamples) {
189  store24(pDst, get24(pSrc) << truncatedBits);
190  pDst += dstStep;
191  pSrc += 3;
192  copysamples--;
193  }
194  break;
195 
196  case 3: // 24 bit compressed to 16 bit
197  GET_PARAMS(params);
198  while (currentframeoffset) {
199  SKIP_ONE(get16(pSrc));
200  pSrc += 2;
201  currentframeoffset--;
202  }
203  while (copysamples) {
204  COPY_ONE(get16(pSrc));
205  pSrc += 2;
206  copysamples--;
207  }
208  break;
209 
210  case 4: // 24 bit compressed to 12 bit
211  GET_PARAMS(params);
212  while (currentframeoffset > 1) {
213  SKIP_ONE(get12lo(pSrc));
214  SKIP_ONE(get12hi(pSrc));
215  pSrc += 3;
216  currentframeoffset -= 2;
217  }
218  if (currentframeoffset) {
219  SKIP_ONE(get12lo(pSrc));
220  currentframeoffset--;
221  if (copysamples) {
222  COPY_ONE(get12hi(pSrc));
223  pSrc += 3;
224  copysamples--;
225  }
226  }
227  while (copysamples > 1) {
228  COPY_ONE(get12lo(pSrc));
229  COPY_ONE(get12hi(pSrc));
230  pSrc += 3;
231  copysamples -= 2;
232  }
233  if (copysamples) {
234  COPY_ONE(get12lo(pSrc));
235  }
236  break;
237 
238  case 5: // 24 bit compressed to 8 bit
239  GET_PARAMS(params);
240  while (currentframeoffset) {
241  SKIP_ONE(int8_t(*pSrc++));
242  currentframeoffset--;
243  }
244  while (copysamples) {
245  COPY_ONE(int8_t(*pSrc++));
246  copysamples--;
247  }
248  break;
249  }
250  }
251 
252  const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
253  const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
254  const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
255  const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
256 }
257 
258 
259 
260 // *************** Internal CRC-32 (Cyclic Redundancy Check) functions ***************
261 // *
262 
263  static uint32_t* __initCRCTable() {
264  static uint32_t res[256];
265 
266  for (int i = 0 ; i < 256 ; i++) {
267  uint32_t c = i;
268  for (int j = 0 ; j < 8 ; j++) {
269  c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
270  }
271  res[i] = c;
272  }
273  return res;
274  }
275 
276  static const uint32_t* __CRCTable = __initCRCTable();
277 
283  inline static void __resetCRC(uint32_t& crc) {
284  crc = 0xffffffff;
285  }
286 
306  static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
307  for (int i = 0 ; i < bufSize ; i++) {
308  crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
309  }
310  }
311 
317  inline static uint32_t __encodeCRC(const uint32_t& crc) {
318  return crc ^ 0xffffffff;
319  }
320 
321 
322 
323 // *************** Other Internal functions ***************
324 // *
325 
326  static split_type_t __resolveSplitType(dimension_t dimension) {
327  return (
328  dimension == dimension_layer ||
329  dimension == dimension_samplechannel ||
330  dimension == dimension_releasetrigger ||
331  dimension == dimension_keyboard ||
332  dimension == dimension_roundrobin ||
333  dimension == dimension_random ||
334  dimension == dimension_smartmidi ||
335  dimension == dimension_roundrobinkeyboard
337  }
338 
339  static int __resolveZoneSize(dimension_def_t& dimension_definition) {
340  return (dimension_definition.split_type == split_type_normal)
341  ? int(128.0 / dimension_definition.zones) : 0;
342  }
343 
344 
345 
346 // *************** Sample ***************
347 // *
348 
349  unsigned int Sample::Instances = 0;
351 
370  Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
371  static const DLS::Info::string_length_t fixedStringLengths[] = {
372  { CHUNK_ID_INAM, 64 },
373  { 0, 0 }
374  };
375  pInfo->SetFixedStringLengths(fixedStringLengths);
376  Instances++;
377  FileNo = fileNo;
378 
379  __resetCRC(crc);
380 
381  pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
382  if (pCk3gix) {
383  uint16_t iSampleGroup = pCk3gix->ReadInt16();
384  pGroup = pFile->GetGroup(iSampleGroup);
385  } else { // '3gix' chunk missing
386  // by default assigned to that mandatory "Default Group"
387  pGroup = pFile->GetGroup(0);
388  }
389 
390  pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
391  if (pCkSmpl) {
397  pCkSmpl->Read(&SMPTEFormat, 1, 4);
399  Loops = pCkSmpl->ReadInt32();
400  pCkSmpl->ReadInt32(); // manufByt
401  LoopID = pCkSmpl->ReadInt32();
402  pCkSmpl->Read(&LoopType, 1, 4);
407  } else { // 'smpl' chunk missing
408  // use default values
409  Manufacturer = 0;
410  Product = 0;
411  SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
412  MIDIUnityNote = 60;
413  FineTune = 0;
415  SMPTEOffset = 0;
416  Loops = 0;
417  LoopID = 0;
419  LoopStart = 0;
420  LoopEnd = 0;
421  LoopFraction = 0;
422  LoopPlayCount = 0;
423  }
424 
425  FrameTable = NULL;
426  SamplePos = 0;
427  RAMCache.Size = 0;
428  RAMCache.pStart = NULL;
430 
431  if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
432 
433  RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
434  Compressed = ewav;
435  Dithered = false;
436  TruncatedBits = 0;
437  if (Compressed) {
438  uint32_t version = ewav->ReadInt32();
439  if (version == 3 && BitDepth == 24) {
440  Dithered = ewav->ReadInt32();
441  ewav->SetPos(Channels == 2 ? 84 : 64);
442  TruncatedBits = ewav->ReadInt32();
443  }
444  ScanCompressedSample();
445  }
446 
447  // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
451  }
452  FrameOffset = 0; // just for streaming compressed samples
453 
454  LoopSize = LoopEnd - LoopStart + 1;
455  }
456 
472  void Sample::CopyAssignMeta(const Sample* orig) {
473  // handle base classes
475 
476  // handle actual own attributes of this class
477  Manufacturer = orig->Manufacturer;
478  Product = orig->Product;
479  SamplePeriod = orig->SamplePeriod;
481  FineTune = orig->FineTune;
482  SMPTEFormat = orig->SMPTEFormat;
483  SMPTEOffset = orig->SMPTEOffset;
484  Loops = orig->Loops;
485  LoopID = orig->LoopID;
486  LoopType = orig->LoopType;
487  LoopStart = orig->LoopStart;
488  LoopEnd = orig->LoopEnd;
489  LoopSize = orig->LoopSize;
490  LoopFraction = orig->LoopFraction;
492 
493  // schedule resizing this sample to the given sample's size
494  Resize(orig->GetSize());
495  }
496 
508  void Sample::CopyAssignWave(const Sample* orig) {
509  const int iReadAtOnce = 32*1024;
510  char* buf = new char[iReadAtOnce * orig->FrameSize];
511  Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
512  unsigned long restorePos = pOrig->GetPos();
513  pOrig->SetPos(0);
514  SetPos(0);
515  for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
516  n = pOrig->Read(buf, iReadAtOnce))
517  {
518  Write(buf, n);
519  }
520  pOrig->SetPos(restorePos);
521  delete [] buf;
522  }
523 
536  // first update base class's chunks
538 
539  // make sure 'smpl' chunk exists
541  if (!pCkSmpl) {
543  memset(pCkSmpl->LoadChunkData(), 0, 60);
544  }
545  // update 'smpl' chunk
546  uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
547  SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
548  store32(&pData[0], Manufacturer);
549  store32(&pData[4], Product);
550  store32(&pData[8], SamplePeriod);
551  store32(&pData[12], MIDIUnityNote);
552  store32(&pData[16], FineTune);
553  store32(&pData[20], SMPTEFormat);
554  store32(&pData[24], SMPTEOffset);
555  store32(&pData[28], Loops);
556 
557  // we skip 'manufByt' for now (4 bytes)
558 
559  store32(&pData[36], LoopID);
560  store32(&pData[40], LoopType);
561  store32(&pData[44], LoopStart);
562  store32(&pData[48], LoopEnd);
563  store32(&pData[52], LoopFraction);
564  store32(&pData[56], LoopPlayCount);
565 
566  // make sure '3gix' chunk exists
569  // determine appropriate sample group index (to be stored in chunk)
570  uint16_t iSampleGroup = 0; // 0 refers to default sample group
571  File* pFile = static_cast<File*>(pParent);
572  if (pFile->pGroups) {
573  std::list<Group*>::iterator iter = pFile->pGroups->begin();
574  std::list<Group*>::iterator end = pFile->pGroups->end();
575  for (int i = 0; iter != end; i++, iter++) {
576  if (*iter == pGroup) {
577  iSampleGroup = i;
578  break; // found
579  }
580  }
581  }
582  // update '3gix' chunk
583  pData = (uint8_t*) pCk3gix->LoadChunkData();
584  store16(&pData[0], iSampleGroup);
585 
586  // if the library user toggled the "Compressed" attribute from true to
587  // false, then the EWAV chunk associated with compressed samples needs
588  // to be deleted
590  if (ewav && !Compressed) {
591  pWaveList->DeleteSubChunk(ewav);
592  }
593  }
594 
596  void Sample::ScanCompressedSample() {
597  //TODO: we have to add some more scans here (e.g. determine compression rate)
598  this->SamplesTotal = 0;
599  std::list<unsigned long> frameOffsets;
600 
601  SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
602  WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
603 
604  // Scanning
605  pCkData->SetPos(0);
606  if (Channels == 2) { // Stereo
607  for (int i = 0 ; ; i++) {
608  // for 24 bit samples every 8:th frame offset is
609  // stored, to save some memory
610  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
611 
612  const int mode_l = pCkData->ReadUint8();
613  const int mode_r = pCkData->ReadUint8();
614  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
615  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
616 
617  if (pCkData->RemainingBytes() <= frameSize) {
619  ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
620  (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
622  break;
623  }
625  pCkData->SetPos(frameSize, RIFF::stream_curpos);
626  }
627  }
628  else { // Mono
629  for (int i = 0 ; ; i++) {
630  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
631 
632  const int mode = pCkData->ReadUint8();
633  if (mode > 5) throw gig::Exception("Unknown compression mode");
634  const unsigned long frameSize = bytesPerFrame[mode];
635 
636  if (pCkData->RemainingBytes() <= frameSize) {
638  ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
640  break;
641  }
643  pCkData->SetPos(frameSize, RIFF::stream_curpos);
644  }
645  }
646  pCkData->SetPos(0);
647 
648  // Build the frames table (which is used for fast resolving of a frame's chunk offset)
649  if (FrameTable) delete[] FrameTable;
650  FrameTable = new unsigned long[frameOffsets.size()];
651  std::list<unsigned long>::iterator end = frameOffsets.end();
652  std::list<unsigned long>::iterator iter = frameOffsets.begin();
653  for (int i = 0; iter != end; i++, iter++) {
654  FrameTable[i] = *iter;
655  }
656  }
657 
668  return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
669  }
670 
693  buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
694  return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
695  }
696 
717  return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
718  }
719 
752  buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
753  if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
754  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
755  unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
756  SetPos(0); // reset read position to begin of sample
757  RAMCache.pStart = new int8_t[allocationsize];
758  RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
759  RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
760  // fill the remaining buffer space with silence samples
761  memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
762  return GetCache();
763  }
764 
776  // return a copy of the buffer_t structure
777  buffer_t result;
778  result.Size = this->RAMCache.Size;
779  result.pStart = this->RAMCache.pStart;
781  return result;
782  }
783 
791  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
792  RAMCache.pStart = NULL;
793  RAMCache.Size = 0;
795  }
796 
827  void Sample::Resize(int iNewSize) {
828  if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
829  DLS::Sample::Resize(iNewSize);
830  }
831 
853  unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
854  if (Compressed) {
855  switch (Whence) {
856  case RIFF::stream_curpos:
857  this->SamplePos += SampleCount;
858  break;
859  case RIFF::stream_end:
860  this->SamplePos = this->SamplesTotal - 1 - SampleCount;
861  break;
863  this->SamplePos -= SampleCount;
864  break;
865  case RIFF::stream_start: default:
866  this->SamplePos = SampleCount;
867  break;
868  }
869  if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
870 
871  unsigned long frame = this->SamplePos / 2048; // to which frame to jump
872  this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
873  pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
874  return this->SamplePos;
875  }
876  else { // not compressed
877  unsigned long orderedBytes = SampleCount * this->FrameSize;
878  unsigned long result = pCkData->SetPos(orderedBytes, Whence);
879  return (result == orderedBytes) ? SampleCount
880  : result / this->FrameSize;
881  }
882  }
883 
887  unsigned long Sample::GetPos() const {
888  if (Compressed) return SamplePos;
889  else return pCkData->GetPos() / FrameSize;
890  }
891 
926  unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
927  DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
928  unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
929  uint8_t* pDst = (uint8_t*) pBuffer;
930 
931  SetPos(pPlaybackState->position); // recover position from the last time
932 
933  if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
934 
935  const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
936  const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
937 
938  if (GetPos() <= loopEnd) {
939  switch (loop.LoopType) {
940 
941  case loop_type_bidirectional: { //TODO: not tested yet!
942  do {
943  // if not endless loop check if max. number of loop cycles have been passed
944  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
945 
946  if (!pPlaybackState->reverse) { // forward playback
947  do {
948  samplestoloopend = loopEnd - GetPos();
949  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
950  samplestoread -= readsamples;
951  totalreadsamples += readsamples;
952  if (readsamples == samplestoloopend) {
953  pPlaybackState->reverse = true;
954  break;
955  }
956  } while (samplestoread && readsamples);
957  }
958  else { // backward playback
959 
960  // as we can only read forward from disk, we have to
961  // determine the end position within the loop first,
962  // read forward from that 'end' and finally after
963  // reading, swap all sample frames so it reflects
964  // backward playback
965 
966  unsigned long swapareastart = totalreadsamples;
967  unsigned long loopoffset = GetPos() - loop.LoopStart;
968  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
969  unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
970 
971  SetPos(reverseplaybackend);
972 
973  // read samples for backward playback
974  do {
975  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
976  samplestoreadinloop -= readsamples;
977  samplestoread -= readsamples;
978  totalreadsamples += readsamples;
979  } while (samplestoreadinloop && readsamples);
980 
981  SetPos(reverseplaybackend); // pretend we really read backwards
982 
983  if (reverseplaybackend == loop.LoopStart) {
984  pPlaybackState->loop_cycles_left--;
985  pPlaybackState->reverse = false;
986  }
987 
988  // reverse the sample frames for backward playback
989  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
990  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
991  }
992  } while (samplestoread && readsamples);
993  break;
994  }
995 
996  case loop_type_backward: { // TODO: not tested yet!
997  // forward playback (not entered the loop yet)
998  if (!pPlaybackState->reverse) do {
999  samplestoloopend = loopEnd - GetPos();
1000  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1001  samplestoread -= readsamples;
1002  totalreadsamples += readsamples;
1003  if (readsamples == samplestoloopend) {
1004  pPlaybackState->reverse = true;
1005  break;
1006  }
1007  } while (samplestoread && readsamples);
1008 
1009  if (!samplestoread) break;
1010 
1011  // as we can only read forward from disk, we have to
1012  // determine the end position within the loop first,
1013  // read forward from that 'end' and finally after
1014  // reading, swap all sample frames so it reflects
1015  // backward playback
1016 
1017  unsigned long swapareastart = totalreadsamples;
1018  unsigned long loopoffset = GetPos() - loop.LoopStart;
1019  unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1020  : samplestoread;
1021  unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1022 
1023  SetPos(reverseplaybackend);
1024 
1025  // read samples for backward playback
1026  do {
1027  // if not endless loop check if max. number of loop cycles have been passed
1028  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1029  samplestoloopend = loopEnd - GetPos();
1030  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1031  samplestoreadinloop -= readsamples;
1032  samplestoread -= readsamples;
1033  totalreadsamples += readsamples;
1034  if (readsamples == samplestoloopend) {
1035  pPlaybackState->loop_cycles_left--;
1036  SetPos(loop.LoopStart);
1037  }
1038  } while (samplestoreadinloop && readsamples);
1039 
1040  SetPos(reverseplaybackend); // pretend we really read backwards
1041 
1042  // reverse the sample frames for backward playback
1043  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1044  break;
1045  }
1046 
1047  default: case loop_type_normal: {
1048  do {
1049  // if not endless loop check if max. number of loop cycles have been passed
1050  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1051  samplestoloopend = loopEnd - GetPos();
1052  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1053  samplestoread -= readsamples;
1054  totalreadsamples += readsamples;
1055  if (readsamples == samplestoloopend) {
1056  pPlaybackState->loop_cycles_left--;
1057  SetPos(loop.LoopStart);
1058  }
1059  } while (samplestoread && readsamples);
1060  break;
1061  }
1062  }
1063  }
1064  }
1065 
1066  // read on without looping
1067  if (samplestoread) do {
1068  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1069  samplestoread -= readsamples;
1070  totalreadsamples += readsamples;
1071  } while (readsamples && samplestoread);
1072 
1073  // store current position
1074  pPlaybackState->position = GetPos();
1075 
1076  return totalreadsamples;
1077  }
1078 
1101  unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1102  if (SampleCount == 0) return 0;
1103  if (!Compressed) {
1104  if (BitDepth == 24) {
1105  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1106  }
1107  else { // 16 bit
1108  // (pCkData->Read does endian correction)
1109  return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1110  : pCkData->Read(pBuffer, SampleCount, 2);
1111  }
1112  }
1113  else {
1114  if (this->SamplePos >= this->SamplesTotal) return 0;
1115  //TODO: efficiency: maybe we should test for an average compression rate
1116  unsigned long assumedsize = GuessSize(SampleCount),
1117  remainingbytes = 0, // remaining bytes in the local buffer
1118  remainingsamples = SampleCount,
1119  copysamples, skipsamples,
1120  currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1121  this->FrameOffset = 0;
1122 
1123  buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1124 
1125  // if decompression buffer too small, then reduce amount of samples to read
1126  if (pDecompressionBuffer->Size < assumedsize) {
1127  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1128  SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1129  remainingsamples = SampleCount;
1130  assumedsize = GuessSize(SampleCount);
1131  }
1132 
1133  unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1134  int16_t* pDst = static_cast<int16_t*>(pBuffer);
1135  uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1136  remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1137 
1138  while (remainingsamples && remainingbytes) {
1139  unsigned long framesamples = SamplesPerFrame;
1140  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1141 
1142  int mode_l = *pSrc++, mode_r = 0;
1143 
1144  if (Channels == 2) {
1145  mode_r = *pSrc++;
1146  framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1147  rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1148  nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1149  if (remainingbytes < framebytes) { // last frame in sample
1150  framesamples = SamplesInLastFrame;
1151  if (mode_l == 4 && (framesamples & 1)) {
1152  rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1153  }
1154  else {
1155  rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1156  }
1157  }
1158  }
1159  else {
1160  framebytes = bytesPerFrame[mode_l] + 1;
1161  nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1162  if (remainingbytes < framebytes) {
1163  framesamples = SamplesInLastFrame;
1164  }
1165  }
1166 
1167  // determine how many samples in this frame to skip and read
1168  if (currentframeoffset + remainingsamples >= framesamples) {
1169  if (currentframeoffset <= framesamples) {
1170  copysamples = framesamples - currentframeoffset;
1171  skipsamples = currentframeoffset;
1172  }
1173  else {
1174  copysamples = 0;
1175  skipsamples = framesamples;
1176  }
1177  }
1178  else {
1179  // This frame has enough data for pBuffer, but not
1180  // all of the frame is needed. Set file position
1181  // to start of this frame for next call to Read.
1182  copysamples = remainingsamples;
1183  skipsamples = currentframeoffset;
1184  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1185  this->FrameOffset = currentframeoffset + copysamples;
1186  }
1187  remainingsamples -= copysamples;
1188 
1189  if (remainingbytes > framebytes) {
1190  remainingbytes -= framebytes;
1191  if (remainingsamples == 0 &&
1192  currentframeoffset + copysamples == framesamples) {
1193  // This frame has enough data for pBuffer, and
1194  // all of the frame is needed. Set file
1195  // position to start of next frame for next
1196  // call to Read. FrameOffset is 0.
1197  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1198  }
1199  }
1200  else remainingbytes = 0;
1201 
1202  currentframeoffset -= skipsamples;
1203 
1204  if (copysamples == 0) {
1205  // skip this frame
1206  pSrc += framebytes - Channels;
1207  }
1208  else {
1209  const unsigned char* const param_l = pSrc;
1210  if (BitDepth == 24) {
1211  if (mode_l != 2) pSrc += 12;
1212 
1213  if (Channels == 2) { // Stereo
1214  const unsigned char* const param_r = pSrc;
1215  if (mode_r != 2) pSrc += 12;
1216 
1217  Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1218  skipsamples, copysamples, TruncatedBits);
1219  Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1220  skipsamples, copysamples, TruncatedBits);
1221  pDst24 += copysamples * 6;
1222  }
1223  else { // Mono
1224  Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1225  skipsamples, copysamples, TruncatedBits);
1226  pDst24 += copysamples * 3;
1227  }
1228  }
1229  else { // 16 bit
1230  if (mode_l) pSrc += 4;
1231 
1232  int step;
1233  if (Channels == 2) { // Stereo
1234  const unsigned char* const param_r = pSrc;
1235  if (mode_r) pSrc += 4;
1236 
1237  step = (2 - mode_l) + (2 - mode_r);
1238  Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1239  Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1240  skipsamples, copysamples);
1241  pDst += copysamples << 1;
1242  }
1243  else { // Mono
1244  step = 2 - mode_l;
1245  Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1246  pDst += copysamples;
1247  }
1248  }
1249  pSrc += nextFrameOffset;
1250  }
1251 
1252  // reload from disk to local buffer if needed
1253  if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1254  assumedsize = GuessSize(remainingsamples);
1255  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1256  if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1257  remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1258  pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1259  }
1260  } // while
1261 
1262  this->SamplePos += (SampleCount - remainingsamples);
1263  if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1264  return (SampleCount - remainingsamples);
1265  }
1266  }
1267 
1290  unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1291  if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1292 
1293  // if this is the first write in this sample, reset the
1294  // checksum calculator
1295  if (pCkData->GetPos() == 0) {
1296  __resetCRC(crc);
1297  }
1298  if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1299  unsigned long res;
1300  if (BitDepth == 24) {
1301  res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1302  } else { // 16 bit
1303  res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1304  : pCkData->Write(pBuffer, SampleCount, 2);
1305  }
1306  __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1307 
1308  // if this is the last write, update the checksum chunk in the
1309  // file
1310  if (pCkData->GetPos() == pCkData->GetSize()) {
1311  File* pFile = static_cast<File*>(GetParent());
1312  pFile->SetSampleChecksum(this, __encodeCRC(crc));
1313  }
1314  return res;
1315  }
1316 
1333  buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1334  buffer_t result;
1335  const double worstCaseHeaderOverhead =
1336  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1337  result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1338  result.pStart = new int8_t[result.Size];
1339  result.NullExtensionSize = 0;
1340  return result;
1341  }
1342 
1350  void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1351  if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1352  delete[] (int8_t*) DecompressionBuffer.pStart;
1353  DecompressionBuffer.pStart = NULL;
1354  DecompressionBuffer.Size = 0;
1355  DecompressionBuffer.NullExtensionSize = 0;
1356  }
1357  }
1358 
1368  return pGroup;
1369  }
1370 
1372  Instances--;
1374  delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1377  }
1378  if (FrameTable) delete[] FrameTable;
1379  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1380  }
1381 
1382 
1383 
1384 // *************** DimensionRegion ***************
1385 // *
1386 
1387  uint DimensionRegion::Instances = 0;
1388  DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1389 
1390  DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1391  Instances++;
1392 
1393  pSample = NULL;
1394  pRegion = pParent;
1395 
1396  if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1397  else memset(&Crossfade, 0, 4);
1398 
1399  if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1400 
1401  RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1402  if (_3ewa) { // if '3ewa' chunk exists
1403  _3ewa->ReadInt32(); // unknown, always == chunk size ?
1404  LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1405  EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1406  _3ewa->ReadInt16(); // unknown
1407  LFO1InternalDepth = _3ewa->ReadUint16();
1408  _3ewa->ReadInt16(); // unknown
1409  LFO3InternalDepth = _3ewa->ReadInt16();
1410  _3ewa->ReadInt16(); // unknown
1411  LFO1ControlDepth = _3ewa->ReadUint16();
1412  _3ewa->ReadInt16(); // unknown
1413  LFO3ControlDepth = _3ewa->ReadInt16();
1414  EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1415  EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1416  _3ewa->ReadInt16(); // unknown
1417  EG1Sustain = _3ewa->ReadUint16();
1418  EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1419  EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1420  uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1421  EG1ControllerInvert = eg1ctrloptions & 0x01;
1425  EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1426  uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1427  EG2ControllerInvert = eg2ctrloptions & 0x01;
1431  LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1432  EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1433  EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1434  _3ewa->ReadInt16(); // unknown
1435  EG2Sustain = _3ewa->ReadUint16();
1436  EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1437  _3ewa->ReadInt16(); // unknown
1438  LFO2ControlDepth = _3ewa->ReadUint16();
1439  LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1440  _3ewa->ReadInt16(); // unknown
1441  LFO2InternalDepth = _3ewa->ReadUint16();
1442  int32_t eg1decay2 = _3ewa->ReadInt32();
1443  EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1444  EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1445  _3ewa->ReadInt16(); // unknown
1446  EG1PreAttack = _3ewa->ReadUint16();
1447  int32_t eg2decay2 = _3ewa->ReadInt32();
1448  EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1449  EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1450  _3ewa->ReadInt16(); // unknown
1451  EG2PreAttack = _3ewa->ReadUint16();
1452  uint8_t velocityresponse = _3ewa->ReadUint8();
1453  if (velocityresponse < 5) {
1455  VelocityResponseDepth = velocityresponse;
1456  } else if (velocityresponse < 10) {
1458  VelocityResponseDepth = velocityresponse - 5;
1459  } else if (velocityresponse < 15) {
1461  VelocityResponseDepth = velocityresponse - 10;
1462  } else {
1465  }
1466  uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1467  if (releasevelocityresponse < 5) {
1469  ReleaseVelocityResponseDepth = releasevelocityresponse;
1470  } else if (releasevelocityresponse < 10) {
1472  ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1473  } else if (releasevelocityresponse < 15) {
1475  ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1476  } else {
1479  }
1482  _3ewa->ReadInt32(); // unknown
1483  SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1484  _3ewa->ReadInt16(); // unknown
1485  uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1486  PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1487  if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1488  else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1490  uint8_t pan = _3ewa->ReadUint8();
1491  Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1492  SelfMask = _3ewa->ReadInt8() & 0x01;
1493  _3ewa->ReadInt8(); // unknown
1494  uint8_t lfo3ctrl = _3ewa->ReadUint8();
1495  LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1496  LFO3Sync = lfo3ctrl & 0x20; // bit 5
1497  InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1498  AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1499  uint8_t lfo2ctrl = _3ewa->ReadUint8();
1500  LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1501  LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1502  LFO2Sync = lfo2ctrl & 0x20; // bit 5
1503  bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1504  uint8_t lfo1ctrl = _3ewa->ReadUint8();
1505  LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1506  LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1507  LFO1Sync = lfo1ctrl & 0x40; // bit 6
1508  VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1510  uint16_t eg3depth = _3ewa->ReadUint16();
1511  EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1512  : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1513  _3ewa->ReadInt16(); // unknown
1514  ChannelOffset = _3ewa->ReadUint8() / 4;
1515  uint8_t regoptions = _3ewa->ReadUint8();
1516  MSDecode = regoptions & 0x01; // bit 0
1517  SustainDefeat = regoptions & 0x02; // bit 1
1518  _3ewa->ReadInt16(); // unknown
1519  VelocityUpperLimit = _3ewa->ReadInt8();
1520  _3ewa->ReadInt8(); // unknown
1521  _3ewa->ReadInt16(); // unknown
1522  ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1523  _3ewa->ReadInt8(); // unknown
1524  _3ewa->ReadInt8(); // unknown
1525  EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1526  uint8_t vcfcutoff = _3ewa->ReadUint8();
1527  VCFEnabled = vcfcutoff & 0x80; // bit 7
1528  VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1529  VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1530  uint8_t vcfvelscale = _3ewa->ReadUint8();
1531  VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1532  VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1533  _3ewa->ReadInt8(); // unknown
1534  uint8_t vcfresonance = _3ewa->ReadUint8();
1535  VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1536  VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1537  uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1538  VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1539  VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1540  uint8_t vcfvelocity = _3ewa->ReadUint8();
1541  VCFVelocityDynamicRange = vcfvelocity % 5;
1542  VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1543  VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1544  if (VCFType == vcf_type_lowpass) {
1545  if (lfo3ctrl & 0x40) // bit 6
1547  }
1548  if (_3ewa->RemainingBytes() >= 8) {
1549  _3ewa->Read(DimensionUpperLimits, 1, 8);
1550  } else {
1551  memset(DimensionUpperLimits, 0, 8);
1552  }
1553  } else { // '3ewa' chunk does not exist yet
1554  // use default values
1555  LFO3Frequency = 1.0;
1556  EG3Attack = 0.0;
1557  LFO1InternalDepth = 0;
1558  LFO3InternalDepth = 0;
1559  LFO1ControlDepth = 0;
1560  LFO3ControlDepth = 0;
1561  EG1Attack = 0.0;
1562  EG1Decay1 = 0.005;
1563  EG1Sustain = 1000;
1564  EG1Release = 0.3;
1567  EG1ControllerInvert = false;
1573  EG2ControllerInvert = false;
1577  LFO1Frequency = 1.0;
1578  EG2Attack = 0.0;
1579  EG2Decay1 = 0.005;
1580  EG2Sustain = 1000;
1581  EG2Release = 0.3;
1582  LFO2ControlDepth = 0;
1583  LFO2Frequency = 1.0;
1584  LFO2InternalDepth = 0;
1585  EG1Decay2 = 0.0;
1586  EG1InfiniteSustain = true;
1587  EG1PreAttack = 0;
1588  EG2Decay2 = 0.0;
1589  EG2InfiniteSustain = true;
1590  EG2PreAttack = 0;
1597  SampleStartOffset = 0;
1598  PitchTrack = true;
1600  Pan = 0;
1601  SelfMask = true;
1603  LFO3Sync = false;
1608  LFO2FlipPhase = false;
1609  LFO2Sync = false;
1611  LFO1FlipPhase = false;
1612  LFO1Sync = false;
1614  EG3Depth = 0;
1615  ChannelOffset = 0;
1616  MSDecode = false;
1617  SustainDefeat = false;
1618  VelocityUpperLimit = 0;
1619  ReleaseTriggerDecay = 0;
1620  EG1Hold = false;
1621  VCFEnabled = false;
1622  VCFCutoff = 0;
1624  VCFCutoffControllerInvert = false;
1625  VCFVelocityScale = 0;
1626  VCFResonance = 0;
1627  VCFResonanceDynamic = false;
1628  VCFKeyboardTracking = false;
1630  VCFVelocityDynamicRange = 0x04;
1633  memset(DimensionUpperLimits, 127, 8);
1634  }
1635 
1636  pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1639 
1640  pVelocityReleaseTable = GetReleaseVelocityTable(
1643  );
1644 
1645  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1649 
1650  SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1651  VelocityTable = 0;
1652  }
1653 
1654  /*
1655  * Constructs a DimensionRegion by copying all parameters from
1656  * another DimensionRegion
1657  */
1658  DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1659  Instances++;
1660  //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1661  *this = src; // default memberwise shallow copy of all parameters
1662  pParentList = _3ewl; // restore the chunk pointer
1663 
1664  // deep copy of owned structures
1665  if (src.VelocityTable) {
1666  VelocityTable = new uint8_t[128];
1667  for (int k = 0 ; k < 128 ; k++)
1668  VelocityTable[k] = src.VelocityTable[k];
1669  }
1670  if (src.pSampleLoops) {
1672  for (int k = 0 ; k < src.SampleLoops ; k++)
1673  pSampleLoops[k] = src.pSampleLoops[k];
1674  }
1675  }
1676 
1687  CopyAssign(orig, NULL);
1688  }
1689 
1698  void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1699  // delete all allocated data first
1700  if (VelocityTable) delete [] VelocityTable;
1701  if (pSampleLoops) delete [] pSampleLoops;
1702 
1703  // backup parent list pointer
1704  RIFF::List* p = pParentList;
1705 
1706  gig::Sample* pOriginalSample = pSample;
1707  gig::Region* pOriginalRegion = pRegion;
1708 
1709  //NOTE: copy code copied from assignment constructor above, see comment there as well
1710 
1711  *this = *orig; // default memberwise shallow copy of all parameters
1712 
1713  // restore members that shall not be altered
1714  pParentList = p; // restore the chunk pointer
1715  pRegion = pOriginalRegion;
1716 
1717  // only take the raw sample reference reference if the
1718  // two DimensionRegion objects are part of the same file
1719  if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1720  pSample = pOriginalSample;
1721  }
1722 
1723  if (mSamples && mSamples->count(orig->pSample)) {
1724  pSample = mSamples->find(orig->pSample)->second;
1725  }
1726 
1727  // deep copy of owned structures
1728  if (orig->VelocityTable) {
1729  VelocityTable = new uint8_t[128];
1730  for (int k = 0 ; k < 128 ; k++)
1731  VelocityTable[k] = orig->VelocityTable[k];
1732  }
1733  if (orig->pSampleLoops) {
1735  for (int k = 0 ; k < orig->SampleLoops ; k++)
1736  pSampleLoops[k] = orig->pSampleLoops[k];
1737  }
1738  }
1739 
1744  void DimensionRegion::SetGain(int32_t gain) {
1745  DLS::Sampler::SetGain(gain);
1746  SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1747  }
1748 
1757  // first update base class's chunk
1759 
1761  uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1762  pData[12] = Crossfade.in_start;
1763  pData[13] = Crossfade.in_end;
1764  pData[14] = Crossfade.out_start;
1765  pData[15] = Crossfade.out_end;
1766 
1767  // make sure '3ewa' chunk exists
1769  if (!_3ewa) {
1770  File* pFile = (File*) GetParent()->GetParent()->GetParent();
1771  bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1772  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1773  }
1774  pData = (uint8_t*) _3ewa->LoadChunkData();
1775 
1776  // update '3ewa' chunk with DimensionRegion's current settings
1777 
1778  const uint32_t chunksize = _3ewa->GetNewSize();
1779  store32(&pData[0], chunksize); // unknown, always chunk size?
1780 
1781  const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1782  store32(&pData[4], lfo3freq);
1783 
1784  const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1785  store32(&pData[8], eg3attack);
1786 
1787  // next 2 bytes unknown
1788 
1789  store16(&pData[14], LFO1InternalDepth);
1790 
1791  // next 2 bytes unknown
1792 
1793  store16(&pData[18], LFO3InternalDepth);
1794 
1795  // next 2 bytes unknown
1796 
1797  store16(&pData[22], LFO1ControlDepth);
1798 
1799  // next 2 bytes unknown
1800 
1801  store16(&pData[26], LFO3ControlDepth);
1802 
1803  const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1804  store32(&pData[28], eg1attack);
1805 
1806  const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1807  store32(&pData[32], eg1decay1);
1808 
1809  // next 2 bytes unknown
1810 
1811  store16(&pData[38], EG1Sustain);
1812 
1813  const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1814  store32(&pData[40], eg1release);
1815 
1816  const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1817  pData[44] = eg1ctl;
1818 
1819  const uint8_t eg1ctrloptions =
1820  (EG1ControllerInvert ? 0x01 : 0x00) |
1824  pData[45] = eg1ctrloptions;
1825 
1826  const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1827  pData[46] = eg2ctl;
1828 
1829  const uint8_t eg2ctrloptions =
1830  (EG2ControllerInvert ? 0x01 : 0x00) |
1834  pData[47] = eg2ctrloptions;
1835 
1836  const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1837  store32(&pData[48], lfo1freq);
1838 
1839  const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1840  store32(&pData[52], eg2attack);
1841 
1842  const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1843  store32(&pData[56], eg2decay1);
1844 
1845  // next 2 bytes unknown
1846 
1847  store16(&pData[62], EG2Sustain);
1848 
1849  const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1850  store32(&pData[64], eg2release);
1851 
1852  // next 2 bytes unknown
1853 
1854  store16(&pData[70], LFO2ControlDepth);
1855 
1856  const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1857  store32(&pData[72], lfo2freq);
1858 
1859  // next 2 bytes unknown
1860 
1861  store16(&pData[78], LFO2InternalDepth);
1862 
1863  const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1864  store32(&pData[80], eg1decay2);
1865 
1866  // next 2 bytes unknown
1867 
1868  store16(&pData[86], EG1PreAttack);
1869 
1870  const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1871  store32(&pData[88], eg2decay2);
1872 
1873  // next 2 bytes unknown
1874 
1875  store16(&pData[94], EG2PreAttack);
1876 
1877  {
1878  if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1879  uint8_t velocityresponse = VelocityResponseDepth;
1880  switch (VelocityResponseCurve) {
1881  case curve_type_nonlinear:
1882  break;
1883  case curve_type_linear:
1884  velocityresponse += 5;
1885  break;
1886  case curve_type_special:
1887  velocityresponse += 10;
1888  break;
1889  case curve_type_unknown:
1890  default:
1891  throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1892  }
1893  pData[96] = velocityresponse;
1894  }
1895 
1896  {
1897  if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1898  uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1899  switch (ReleaseVelocityResponseCurve) {
1900  case curve_type_nonlinear:
1901  break;
1902  case curve_type_linear:
1903  releasevelocityresponse += 5;
1904  break;
1905  case curve_type_special:
1906  releasevelocityresponse += 10;
1907  break;
1908  case curve_type_unknown:
1909  default:
1910  throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1911  }
1912  pData[97] = releasevelocityresponse;
1913  }
1914 
1915  pData[98] = VelocityResponseCurveScaling;
1916 
1917  pData[99] = AttenuationControllerThreshold;
1918 
1919  // next 4 bytes unknown
1920 
1921  store16(&pData[104], SampleStartOffset);
1922 
1923  // next 2 bytes unknown
1924 
1925  {
1926  uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1927  switch (DimensionBypass) {
1928  case dim_bypass_ctrl_94:
1929  pitchTrackDimensionBypass |= 0x10;
1930  break;
1931  case dim_bypass_ctrl_95:
1932  pitchTrackDimensionBypass |= 0x20;
1933  break;
1934  case dim_bypass_ctrl_none:
1935  //FIXME: should we set anything here?
1936  break;
1937  default:
1938  throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1939  }
1940  pData[108] = pitchTrackDimensionBypass;
1941  }
1942 
1943  const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1944  pData[109] = pan;
1945 
1946  const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1947  pData[110] = selfmask;
1948 
1949  // next byte unknown
1950 
1951  {
1952  uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1953  if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1954  if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1955  if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1956  pData[112] = lfo3ctrl;
1957  }
1958 
1959  const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1960  pData[113] = attenctl;
1961 
1962  {
1963  uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1964  if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1965  if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1966  if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1967  pData[114] = lfo2ctrl;
1968  }
1969 
1970  {
1971  uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1972  if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1973  if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1976  pData[115] = lfo1ctrl;
1977  }
1978 
1979  const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1980  : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1981  store16(&pData[116], eg3depth);
1982 
1983  // next 2 bytes unknown
1984 
1985  const uint8_t channeloffset = ChannelOffset * 4;
1986  pData[120] = channeloffset;
1987 
1988  {
1989  uint8_t regoptions = 0;
1990  if (MSDecode) regoptions |= 0x01; // bit 0
1991  if (SustainDefeat) regoptions |= 0x02; // bit 1
1992  pData[121] = regoptions;
1993  }
1994 
1995  // next 2 bytes unknown
1996 
1997  pData[124] = VelocityUpperLimit;
1998 
1999  // next 3 bytes unknown
2000 
2001  pData[128] = ReleaseTriggerDecay;
2002 
2003  // next 2 bytes unknown
2004 
2005  const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2006  pData[131] = eg1hold;
2007 
2008  const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
2009  (VCFCutoff & 0x7f); /* lower 7 bits */
2010  pData[132] = vcfcutoff;
2011 
2012  pData[133] = VCFCutoffController;
2013 
2014  const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2015  (VCFVelocityScale & 0x7f); /* lower 7 bits */
2016  pData[134] = vcfvelscale;
2017 
2018  // next byte unknown
2019 
2020  const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2021  (VCFResonance & 0x7f); /* lower 7 bits */
2022  pData[136] = vcfresonance;
2023 
2024  const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2025  (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2026  pData[137] = vcfbreakpoint;
2027 
2028  const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2029  VCFVelocityCurve * 5;
2030  pData[138] = vcfvelocity;
2031 
2032  const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2033  pData[139] = vcftype;
2034 
2035  if (chunksize >= 148) {
2036  memcpy(&pData[140], DimensionUpperLimits, 8);
2037  }
2038  }
2039 
2040  double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2041  curve_type_t curveType = releaseVelocityResponseCurve;
2042  uint8_t depth = releaseVelocityResponseDepth;
2043  // this models a strange behaviour or bug in GSt: two of the
2044  // velocity response curves for release time are not used even
2045  // if specified, instead another curve is chosen.
2046  if ((curveType == curve_type_nonlinear && depth == 0) ||
2047  (curveType == curve_type_special && depth == 4)) {
2048  curveType = curve_type_nonlinear;
2049  depth = 3;
2050  }
2051  return GetVelocityTable(curveType, depth, 0);
2052  }
2053 
2054  double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2055  uint8_t vcfVelocityDynamicRange,
2056  uint8_t vcfVelocityScale,
2057  vcf_cutoff_ctrl_t vcfCutoffController)
2058  {
2059  curve_type_t curveType = vcfVelocityCurve;
2060  uint8_t depth = vcfVelocityDynamicRange;
2061  // even stranger GSt: two of the velocity response curves for
2062  // filter cutoff are not used, instead another special curve
2063  // is chosen. This curve is not used anywhere else.
2064  if ((curveType == curve_type_nonlinear && depth == 0) ||
2065  (curveType == curve_type_special && depth == 4)) {
2066  curveType = curve_type_special;
2067  depth = 5;
2068  }
2069  return GetVelocityTable(curveType, depth,
2070  (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2071  ? vcfVelocityScale : 0);
2072  }
2073 
2074  // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2075  double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2076  {
2077  double* table;
2078  uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2079  if (pVelocityTables->count(tableKey)) { // if key exists
2080  table = (*pVelocityTables)[tableKey];
2081  }
2082  else {
2083  table = CreateVelocityTable(curveType, depth, scaling);
2084  (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2085  }
2086  return table;
2087  }
2088 
2090  return pRegion;
2091  }
2092 
2093 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2094 // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2095 // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2096 //#pragma GCC diagnostic push
2097 //#pragma GCC diagnostic error "-Wswitch"
2098 
2099  leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2100  leverage_ctrl_t decodedcontroller;
2101  switch (EncodedController) {
2102  // special controller
2103  case _lev_ctrl_none:
2104  decodedcontroller.type = leverage_ctrl_t::type_none;
2105  decodedcontroller.controller_number = 0;
2106  break;
2107  case _lev_ctrl_velocity:
2108  decodedcontroller.type = leverage_ctrl_t::type_velocity;
2109  decodedcontroller.controller_number = 0;
2110  break;
2111  case _lev_ctrl_channelaftertouch:
2112  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2113  decodedcontroller.controller_number = 0;
2114  break;
2115 
2116  // ordinary MIDI control change controller
2117  case _lev_ctrl_modwheel:
2118  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2119  decodedcontroller.controller_number = 1;
2120  break;
2121  case _lev_ctrl_breath:
2122  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2123  decodedcontroller.controller_number = 2;
2124  break;
2125  case _lev_ctrl_foot:
2126  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2127  decodedcontroller.controller_number = 4;
2128  break;
2129  case _lev_ctrl_effect1:
2130  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2131  decodedcontroller.controller_number = 12;
2132  break;
2133  case _lev_ctrl_effect2:
2134  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2135  decodedcontroller.controller_number = 13;
2136  break;
2137  case _lev_ctrl_genpurpose1:
2138  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2139  decodedcontroller.controller_number = 16;
2140  break;
2141  case _lev_ctrl_genpurpose2:
2142  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2143  decodedcontroller.controller_number = 17;
2144  break;
2145  case _lev_ctrl_genpurpose3:
2146  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2147  decodedcontroller.controller_number = 18;
2148  break;
2149  case _lev_ctrl_genpurpose4:
2150  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2151  decodedcontroller.controller_number = 19;
2152  break;
2153  case _lev_ctrl_portamentotime:
2154  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2155  decodedcontroller.controller_number = 5;
2156  break;
2157  case _lev_ctrl_sustainpedal:
2158  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2159  decodedcontroller.controller_number = 64;
2160  break;
2161  case _lev_ctrl_portamento:
2162  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2163  decodedcontroller.controller_number = 65;
2164  break;
2165  case _lev_ctrl_sostenutopedal:
2166  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2167  decodedcontroller.controller_number = 66;
2168  break;
2169  case _lev_ctrl_softpedal:
2170  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2171  decodedcontroller.controller_number = 67;
2172  break;
2173  case _lev_ctrl_genpurpose5:
2174  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2175  decodedcontroller.controller_number = 80;
2176  break;
2177  case _lev_ctrl_genpurpose6:
2178  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2179  decodedcontroller.controller_number = 81;
2180  break;
2181  case _lev_ctrl_genpurpose7:
2182  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2183  decodedcontroller.controller_number = 82;
2184  break;
2185  case _lev_ctrl_genpurpose8:
2186  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2187  decodedcontroller.controller_number = 83;
2188  break;
2189  case _lev_ctrl_effect1depth:
2190  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2191  decodedcontroller.controller_number = 91;
2192  break;
2193  case _lev_ctrl_effect2depth:
2194  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2195  decodedcontroller.controller_number = 92;
2196  break;
2197  case _lev_ctrl_effect3depth:
2198  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2199  decodedcontroller.controller_number = 93;
2200  break;
2201  case _lev_ctrl_effect4depth:
2202  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2203  decodedcontroller.controller_number = 94;
2204  break;
2205  case _lev_ctrl_effect5depth:
2206  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2207  decodedcontroller.controller_number = 95;
2208  break;
2209 
2210  // format extension (these controllers are so far only supported by
2211  // LinuxSampler & gigedit) they will *NOT* work with
2212  // Gigasampler/GigaStudio !
2213  case _lev_ctrl_CC3_EXT:
2214  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2215  decodedcontroller.controller_number = 3;
2216  break;
2217  case _lev_ctrl_CC6_EXT:
2218  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2219  decodedcontroller.controller_number = 6;
2220  break;
2221  case _lev_ctrl_CC7_EXT:
2222  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2223  decodedcontroller.controller_number = 7;
2224  break;
2225  case _lev_ctrl_CC8_EXT:
2226  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2227  decodedcontroller.controller_number = 8;
2228  break;
2229  case _lev_ctrl_CC9_EXT:
2230  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2231  decodedcontroller.controller_number = 9;
2232  break;
2233  case _lev_ctrl_CC10_EXT:
2234  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235  decodedcontroller.controller_number = 10;
2236  break;
2237  case _lev_ctrl_CC11_EXT:
2238  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239  decodedcontroller.controller_number = 11;
2240  break;
2241  case _lev_ctrl_CC14_EXT:
2242  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243  decodedcontroller.controller_number = 14;
2244  break;
2245  case _lev_ctrl_CC15_EXT:
2246  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247  decodedcontroller.controller_number = 15;
2248  break;
2249  case _lev_ctrl_CC20_EXT:
2250  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251  decodedcontroller.controller_number = 20;
2252  break;
2253  case _lev_ctrl_CC21_EXT:
2254  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255  decodedcontroller.controller_number = 21;
2256  break;
2257  case _lev_ctrl_CC22_EXT:
2258  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259  decodedcontroller.controller_number = 22;
2260  break;
2261  case _lev_ctrl_CC23_EXT:
2262  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263  decodedcontroller.controller_number = 23;
2264  break;
2265  case _lev_ctrl_CC24_EXT:
2266  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267  decodedcontroller.controller_number = 24;
2268  break;
2269  case _lev_ctrl_CC25_EXT:
2270  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271  decodedcontroller.controller_number = 25;
2272  break;
2273  case _lev_ctrl_CC26_EXT:
2274  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275  decodedcontroller.controller_number = 26;
2276  break;
2277  case _lev_ctrl_CC27_EXT:
2278  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279  decodedcontroller.controller_number = 27;
2280  break;
2281  case _lev_ctrl_CC28_EXT:
2282  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283  decodedcontroller.controller_number = 28;
2284  break;
2285  case _lev_ctrl_CC29_EXT:
2286  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287  decodedcontroller.controller_number = 29;
2288  break;
2289  case _lev_ctrl_CC30_EXT:
2290  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291  decodedcontroller.controller_number = 30;
2292  break;
2293  case _lev_ctrl_CC31_EXT:
2294  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295  decodedcontroller.controller_number = 31;
2296  break;
2297  case _lev_ctrl_CC68_EXT:
2298  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299  decodedcontroller.controller_number = 68;
2300  break;
2301  case _lev_ctrl_CC69_EXT:
2302  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303  decodedcontroller.controller_number = 69;
2304  break;
2305  case _lev_ctrl_CC70_EXT:
2306  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307  decodedcontroller.controller_number = 70;
2308  break;
2309  case _lev_ctrl_CC71_EXT:
2310  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311  decodedcontroller.controller_number = 71;
2312  break;
2313  case _lev_ctrl_CC72_EXT:
2314  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315  decodedcontroller.controller_number = 72;
2316  break;
2317  case _lev_ctrl_CC73_EXT:
2318  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319  decodedcontroller.controller_number = 73;
2320  break;
2321  case _lev_ctrl_CC74_EXT:
2322  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323  decodedcontroller.controller_number = 74;
2324  break;
2325  case _lev_ctrl_CC75_EXT:
2326  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327  decodedcontroller.controller_number = 75;
2328  break;
2329  case _lev_ctrl_CC76_EXT:
2330  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331  decodedcontroller.controller_number = 76;
2332  break;
2333  case _lev_ctrl_CC77_EXT:
2334  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335  decodedcontroller.controller_number = 77;
2336  break;
2337  case _lev_ctrl_CC78_EXT:
2338  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339  decodedcontroller.controller_number = 78;
2340  break;
2341  case _lev_ctrl_CC79_EXT:
2342  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343  decodedcontroller.controller_number = 79;
2344  break;
2345  case _lev_ctrl_CC84_EXT:
2346  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347  decodedcontroller.controller_number = 84;
2348  break;
2349  case _lev_ctrl_CC85_EXT:
2350  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351  decodedcontroller.controller_number = 85;
2352  break;
2353  case _lev_ctrl_CC86_EXT:
2354  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355  decodedcontroller.controller_number = 86;
2356  break;
2357  case _lev_ctrl_CC87_EXT:
2358  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359  decodedcontroller.controller_number = 87;
2360  break;
2361  case _lev_ctrl_CC89_EXT:
2362  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363  decodedcontroller.controller_number = 89;
2364  break;
2365  case _lev_ctrl_CC90_EXT:
2366  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367  decodedcontroller.controller_number = 90;
2368  break;
2369  case _lev_ctrl_CC96_EXT:
2370  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371  decodedcontroller.controller_number = 96;
2372  break;
2373  case _lev_ctrl_CC97_EXT:
2374  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375  decodedcontroller.controller_number = 97;
2376  break;
2377  case _lev_ctrl_CC102_EXT:
2378  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379  decodedcontroller.controller_number = 102;
2380  break;
2381  case _lev_ctrl_CC103_EXT:
2382  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383  decodedcontroller.controller_number = 103;
2384  break;
2385  case _lev_ctrl_CC104_EXT:
2386  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387  decodedcontroller.controller_number = 104;
2388  break;
2389  case _lev_ctrl_CC105_EXT:
2390  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391  decodedcontroller.controller_number = 105;
2392  break;
2393  case _lev_ctrl_CC106_EXT:
2394  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395  decodedcontroller.controller_number = 106;
2396  break;
2397  case _lev_ctrl_CC107_EXT:
2398  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399  decodedcontroller.controller_number = 107;
2400  break;
2401  case _lev_ctrl_CC108_EXT:
2402  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403  decodedcontroller.controller_number = 108;
2404  break;
2405  case _lev_ctrl_CC109_EXT:
2406  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407  decodedcontroller.controller_number = 109;
2408  break;
2409  case _lev_ctrl_CC110_EXT:
2410  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411  decodedcontroller.controller_number = 110;
2412  break;
2413  case _lev_ctrl_CC111_EXT:
2414  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415  decodedcontroller.controller_number = 111;
2416  break;
2417  case _lev_ctrl_CC112_EXT:
2418  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419  decodedcontroller.controller_number = 112;
2420  break;
2421  case _lev_ctrl_CC113_EXT:
2422  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423  decodedcontroller.controller_number = 113;
2424  break;
2425  case _lev_ctrl_CC114_EXT:
2426  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427  decodedcontroller.controller_number = 114;
2428  break;
2429  case _lev_ctrl_CC115_EXT:
2430  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431  decodedcontroller.controller_number = 115;
2432  break;
2433  case _lev_ctrl_CC116_EXT:
2434  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435  decodedcontroller.controller_number = 116;
2436  break;
2437  case _lev_ctrl_CC117_EXT:
2438  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439  decodedcontroller.controller_number = 117;
2440  break;
2441  case _lev_ctrl_CC118_EXT:
2442  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443  decodedcontroller.controller_number = 118;
2444  break;
2445  case _lev_ctrl_CC119_EXT:
2446  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447  decodedcontroller.controller_number = 119;
2448  break;
2449 
2450  // unknown controller type
2451  default:
2452  throw gig::Exception("Unknown leverage controller type.");
2453  }
2454  return decodedcontroller;
2455  }
2456 
2457 // see above (diagnostic push not supported prior GCC 4.6)
2458 //#pragma GCC diagnostic pop
2459 
2460  DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2461  _lev_ctrl_t encodedcontroller;
2462  switch (DecodedController.type) {
2463  // special controller
2465  encodedcontroller = _lev_ctrl_none;
2466  break;
2468  encodedcontroller = _lev_ctrl_velocity;
2469  break;
2471  encodedcontroller = _lev_ctrl_channelaftertouch;
2472  break;
2473 
2474  // ordinary MIDI control change controller
2476  switch (DecodedController.controller_number) {
2477  case 1:
2478  encodedcontroller = _lev_ctrl_modwheel;
2479  break;
2480  case 2:
2481  encodedcontroller = _lev_ctrl_breath;
2482  break;
2483  case 4:
2484  encodedcontroller = _lev_ctrl_foot;
2485  break;
2486  case 12:
2487  encodedcontroller = _lev_ctrl_effect1;
2488  break;
2489  case 13:
2490  encodedcontroller = _lev_ctrl_effect2;
2491  break;
2492  case 16:
2493  encodedcontroller = _lev_ctrl_genpurpose1;
2494  break;
2495  case 17:
2496  encodedcontroller = _lev_ctrl_genpurpose2;
2497  break;
2498  case 18:
2499  encodedcontroller = _lev_ctrl_genpurpose3;
2500  break;
2501  case 19:
2502  encodedcontroller = _lev_ctrl_genpurpose4;
2503  break;
2504  case 5:
2505  encodedcontroller = _lev_ctrl_portamentotime;
2506  break;
2507  case 64:
2508  encodedcontroller = _lev_ctrl_sustainpedal;
2509  break;
2510  case 65:
2511  encodedcontroller = _lev_ctrl_portamento;
2512  break;
2513  case 66:
2514  encodedcontroller = _lev_ctrl_sostenutopedal;
2515  break;
2516  case 67:
2517  encodedcontroller = _lev_ctrl_softpedal;
2518  break;
2519  case 80:
2520  encodedcontroller = _lev_ctrl_genpurpose5;
2521  break;
2522  case 81:
2523  encodedcontroller = _lev_ctrl_genpurpose6;
2524  break;
2525  case 82:
2526  encodedcontroller = _lev_ctrl_genpurpose7;
2527  break;
2528  case 83:
2529  encodedcontroller = _lev_ctrl_genpurpose8;
2530  break;
2531  case 91:
2532  encodedcontroller = _lev_ctrl_effect1depth;
2533  break;
2534  case 92:
2535  encodedcontroller = _lev_ctrl_effect2depth;
2536  break;
2537  case 93:
2538  encodedcontroller = _lev_ctrl_effect3depth;
2539  break;
2540  case 94:
2541  encodedcontroller = _lev_ctrl_effect4depth;
2542  break;
2543  case 95:
2544  encodedcontroller = _lev_ctrl_effect5depth;
2545  break;
2546 
2547  // format extension (these controllers are so far only
2548  // supported by LinuxSampler & gigedit) they will *NOT*
2549  // work with Gigasampler/GigaStudio !
2550  case 3:
2551  encodedcontroller = _lev_ctrl_CC3_EXT;
2552  break;
2553  case 6:
2554  encodedcontroller = _lev_ctrl_CC6_EXT;
2555  break;
2556  case 7:
2557  encodedcontroller = _lev_ctrl_CC7_EXT;
2558  break;
2559  case 8:
2560  encodedcontroller = _lev_ctrl_CC8_EXT;
2561  break;
2562  case 9:
2563  encodedcontroller = _lev_ctrl_CC9_EXT;
2564  break;
2565  case 10:
2566  encodedcontroller = _lev_ctrl_CC10_EXT;
2567  break;
2568  case 11:
2569  encodedcontroller = _lev_ctrl_CC11_EXT;
2570  break;
2571  case 14:
2572  encodedcontroller = _lev_ctrl_CC14_EXT;
2573  break;
2574  case 15:
2575  encodedcontroller = _lev_ctrl_CC15_EXT;
2576  break;
2577  case 20:
2578  encodedcontroller = _lev_ctrl_CC20_EXT;
2579  break;
2580  case 21:
2581  encodedcontroller = _lev_ctrl_CC21_EXT;
2582  break;
2583  case 22:
2584  encodedcontroller = _lev_ctrl_CC22_EXT;
2585  break;
2586  case 23:
2587  encodedcontroller = _lev_ctrl_CC23_EXT;
2588  break;
2589  case 24:
2590  encodedcontroller = _lev_ctrl_CC24_EXT;
2591  break;
2592  case 25:
2593  encodedcontroller = _lev_ctrl_CC25_EXT;
2594  break;
2595  case 26:
2596  encodedcontroller = _lev_ctrl_CC26_EXT;
2597  break;
2598  case 27:
2599  encodedcontroller = _lev_ctrl_CC27_EXT;
2600  break;
2601  case 28:
2602  encodedcontroller = _lev_ctrl_CC28_EXT;
2603  break;
2604  case 29:
2605  encodedcontroller = _lev_ctrl_CC29_EXT;
2606  break;
2607  case 30:
2608  encodedcontroller = _lev_ctrl_CC30_EXT;
2609  break;
2610  case 31:
2611  encodedcontroller = _lev_ctrl_CC31_EXT;
2612  break;
2613  case 68:
2614  encodedcontroller = _lev_ctrl_CC68_EXT;
2615  break;
2616  case 69:
2617  encodedcontroller = _lev_ctrl_CC69_EXT;
2618  break;
2619  case 70:
2620  encodedcontroller = _lev_ctrl_CC70_EXT;
2621  break;
2622  case 71:
2623  encodedcontroller = _lev_ctrl_CC71_EXT;
2624  break;
2625  case 72:
2626  encodedcontroller = _lev_ctrl_CC72_EXT;
2627  break;
2628  case 73:
2629  encodedcontroller = _lev_ctrl_CC73_EXT;
2630  break;
2631  case 74:
2632  encodedcontroller = _lev_ctrl_CC74_EXT;
2633  break;
2634  case 75:
2635  encodedcontroller = _lev_ctrl_CC75_EXT;
2636  break;
2637  case 76:
2638  encodedcontroller = _lev_ctrl_CC76_EXT;
2639  break;
2640  case 77:
2641  encodedcontroller = _lev_ctrl_CC77_EXT;
2642  break;
2643  case 78:
2644  encodedcontroller = _lev_ctrl_CC78_EXT;
2645  break;
2646  case 79:
2647  encodedcontroller = _lev_ctrl_CC79_EXT;
2648  break;
2649  case 84:
2650  encodedcontroller = _lev_ctrl_CC84_EXT;
2651  break;
2652  case 85:
2653  encodedcontroller = _lev_ctrl_CC85_EXT;
2654  break;
2655  case 86:
2656  encodedcontroller = _lev_ctrl_CC86_EXT;
2657  break;
2658  case 87:
2659  encodedcontroller = _lev_ctrl_CC87_EXT;
2660  break;
2661  case 89:
2662  encodedcontroller = _lev_ctrl_CC89_EXT;
2663  break;
2664  case 90:
2665  encodedcontroller = _lev_ctrl_CC90_EXT;
2666  break;
2667  case 96:
2668  encodedcontroller = _lev_ctrl_CC96_EXT;
2669  break;
2670  case 97:
2671  encodedcontroller = _lev_ctrl_CC97_EXT;
2672  break;
2673  case 102:
2674  encodedcontroller = _lev_ctrl_CC102_EXT;
2675  break;
2676  case 103:
2677  encodedcontroller = _lev_ctrl_CC103_EXT;
2678  break;
2679  case 104:
2680  encodedcontroller = _lev_ctrl_CC104_EXT;
2681  break;
2682  case 105:
2683  encodedcontroller = _lev_ctrl_CC105_EXT;
2684  break;
2685  case 106:
2686  encodedcontroller = _lev_ctrl_CC106_EXT;
2687  break;
2688  case 107:
2689  encodedcontroller = _lev_ctrl_CC107_EXT;
2690  break;
2691  case 108:
2692  encodedcontroller = _lev_ctrl_CC108_EXT;
2693  break;
2694  case 109:
2695  encodedcontroller = _lev_ctrl_CC109_EXT;
2696  break;
2697  case 110:
2698  encodedcontroller = _lev_ctrl_CC110_EXT;
2699  break;
2700  case 111:
2701  encodedcontroller = _lev_ctrl_CC111_EXT;
2702  break;
2703  case 112:
2704  encodedcontroller = _lev_ctrl_CC112_EXT;
2705  break;
2706  case 113:
2707  encodedcontroller = _lev_ctrl_CC113_EXT;
2708  break;
2709  case 114:
2710  encodedcontroller = _lev_ctrl_CC114_EXT;
2711  break;
2712  case 115:
2713  encodedcontroller = _lev_ctrl_CC115_EXT;
2714  break;
2715  case 116:
2716  encodedcontroller = _lev_ctrl_CC116_EXT;
2717  break;
2718  case 117:
2719  encodedcontroller = _lev_ctrl_CC117_EXT;
2720  break;
2721  case 118:
2722  encodedcontroller = _lev_ctrl_CC118_EXT;
2723  break;
2724  case 119:
2725  encodedcontroller = _lev_ctrl_CC119_EXT;
2726  break;
2727 
2728  default:
2729  throw gig::Exception("leverage controller number is not supported by the gig format");
2730  }
2731  break;
2732  default:
2733  throw gig::Exception("Unknown leverage controller type.");
2734  }
2735  return encodedcontroller;
2736  }
2737 
2739  Instances--;
2740  if (!Instances) {
2741  // delete the velocity->volume tables
2742  VelocityTableMap::iterator iter;
2743  for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2744  double* pTable = iter->second;
2745  if (pTable) delete[] pTable;
2746  }
2747  pVelocityTables->clear();
2748  delete pVelocityTables;
2749  pVelocityTables = NULL;
2750  }
2751  if (VelocityTable) delete[] VelocityTable;
2752  }
2753 
2765  double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2766  return pVelocityAttenuationTable[MIDIKeyVelocity];
2767  }
2768 
2769  double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2770  return pVelocityReleaseTable[MIDIKeyVelocity];
2771  }
2772 
2773  double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2774  return pVelocityCutoffTable[MIDIKeyVelocity];
2775  }
2776 
2782  pVelocityAttenuationTable =
2783  GetVelocityTable(
2785  );
2786  VelocityResponseCurve = curve;
2787  }
2788 
2794  pVelocityAttenuationTable =
2795  GetVelocityTable(
2797  );
2798  VelocityResponseDepth = depth;
2799  }
2800 
2806  pVelocityAttenuationTable =
2807  GetVelocityTable(
2809  );
2810  VelocityResponseCurveScaling = scaling;
2811  }
2812 
2818  pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2820  }
2821 
2827  pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2829  }
2830 
2836  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2837  VCFCutoffController = controller;
2838  }
2839 
2845  pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2846  VCFVelocityCurve = curve;
2847  }
2848 
2854  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2855  VCFVelocityDynamicRange = range;
2856  }
2857 
2863  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2864  VCFVelocityScale = scaling;
2865  }
2866 
2867  double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2868 
2869  // line-segment approximations of the 15 velocity curves
2870 
2871  // linear
2872  const int lin0[] = { 1, 1, 127, 127 };
2873  const int lin1[] = { 1, 21, 127, 127 };
2874  const int lin2[] = { 1, 45, 127, 127 };
2875  const int lin3[] = { 1, 74, 127, 127 };
2876  const int lin4[] = { 1, 127, 127, 127 };
2877 
2878  // non-linear
2879  const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2880  const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2881  127, 127 };
2882  const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2883  127, 127 };
2884  const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2885  127, 127 };
2886  const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2887 
2888  // special
2889  const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2890  113, 127, 127, 127 };
2891  const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2892  118, 127, 127, 127 };
2893  const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2894  85, 90, 91, 127, 127, 127 };
2895  const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2896  117, 127, 127, 127 };
2897  const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2898  127, 127 };
2899 
2900  // this is only used by the VCF velocity curve
2901  const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2902  91, 127, 127, 127 };
2903 
2904  const int* const curves[] = { non0, non1, non2, non3, non4,
2905  lin0, lin1, lin2, lin3, lin4,
2906  spe0, spe1, spe2, spe3, spe4, spe5 };
2907 
2908  double* const table = new double[128];
2909 
2910  const int* curve = curves[curveType * 5 + depth];
2911  const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2912 
2913  table[0] = 0;
2914  for (int x = 1 ; x < 128 ; x++) {
2915 
2916  if (x > curve[2]) curve += 2;
2917  double y = curve[1] + (x - curve[0]) *
2918  (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2919  y = y / 127;
2920 
2921  // Scale up for s > 20, down for s < 20. When
2922  // down-scaling, the curve still ends at 1.0.
2923  if (s < 20 && y >= 0.5)
2924  y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2925  else
2926  y = y * (s / 20.0);
2927  if (y > 1) y = 1;
2928 
2929  table[x] = y;
2930  }
2931  return table;
2932  }
2933 
2934 
2935 // *************** Region ***************
2936 // *
2937 
2938  Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2939  // Initialization
2940  Dimensions = 0;
2941  for (int i = 0; i < 256; i++) {
2942  pDimensionRegions[i] = NULL;
2943  }
2944  Layers = 1;
2945  File* file = (File*) GetParent()->GetParent();
2946  int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2947 
2948  // Actual Loading
2949 
2950  if (!file->GetAutoLoad()) return;
2951 
2952  LoadDimensionRegions(rgnList);
2953 
2954  RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2955  if (_3lnk) {
2956  DimensionRegions = _3lnk->ReadUint32();
2957  for (int i = 0; i < dimensionBits; i++) {
2958  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2959  uint8_t bits = _3lnk->ReadUint8();
2960  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2961  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2962  uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2963  if (dimension == dimension_none) { // inactive dimension
2965  pDimensionDefinitions[i].bits = 0;
2969  }
2970  else { // active dimension
2971  pDimensionDefinitions[i].dimension = dimension;
2972  pDimensionDefinitions[i].bits = bits;
2973  pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2974  pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2975  pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
2976  Dimensions++;
2977 
2978  // if this is a layer dimension, remember the amount of layers
2979  if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2980  }
2981  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2982  }
2983  for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2984 
2985  // if there's a velocity dimension and custom velocity zone splits are used,
2986  // update the VelocityTables in the dimension regions
2988 
2989  // jump to start of the wave pool indices (if not already there)
2990  if (file->pVersion && file->pVersion->major == 3)
2991  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2992  else
2993  _3lnk->SetPos(44);
2994 
2995  // load sample references (if auto loading is enabled)
2996  if (file->GetAutoLoad()) {
2997  for (uint i = 0; i < DimensionRegions; i++) {
2998  uint32_t wavepoolindex = _3lnk->ReadUint32();
2999  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3000  }
3001  GetSample(); // load global region sample reference
3002  }
3003  } else {
3004  DimensionRegions = 0;
3005  for (int i = 0 ; i < 8 ; i++) {
3007  pDimensionDefinitions[i].bits = 0;
3009  }
3010  }
3011 
3012  // make sure there is at least one dimension region
3013  if (!DimensionRegions) {
3014  RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3015  if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3016  RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3017  pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3018  DimensionRegions = 1;
3019  }
3020  }
3021 
3032  // in the gig format we don't care about the Region's sample reference
3033  // but we still have to provide some existing one to not corrupt the
3034  // file, so to avoid the latter we simply always assign the sample of
3035  // the first dimension region of this region
3037 
3038  // first update base class's chunks
3040 
3041  // update dimension region's chunks
3042  for (int i = 0; i < DimensionRegions; i++) {
3044  }
3045 
3046  File* pFile = (File*) GetParent()->GetParent();
3047  bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3048  const int iMaxDimensions = version3 ? 8 : 5;
3049  const int iMaxDimensionRegions = version3 ? 256 : 32;
3050 
3051  // make sure '3lnk' chunk exists
3053  if (!_3lnk) {
3054  const int _3lnkChunkSize = version3 ? 1092 : 172;
3055  _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3056  memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3057 
3058  // move 3prg to last position
3060  }
3061 
3062  // update dimension definitions in '3lnk' chunk
3063  uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3064  store32(&pData[0], DimensionRegions);
3065  int shift = 0;
3066  for (int i = 0; i < iMaxDimensions; i++) {
3067  pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3068  pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3069  pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3070  pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3071  pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3072  // next 3 bytes unknown, always zero?
3073 
3074  shift += pDimensionDefinitions[i].bits;
3075  }
3076 
3077  // update wave pool table in '3lnk' chunk
3078  const int iWavePoolOffset = version3 ? 68 : 44;
3079  for (uint i = 0; i < iMaxDimensionRegions; i++) {
3080  int iWaveIndex = -1;
3081  if (i < DimensionRegions) {
3082  if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3083  File::SampleList::iterator iter = pFile->pSamples->begin();
3084  File::SampleList::iterator end = pFile->pSamples->end();
3085  for (int index = 0; iter != end; ++iter, ++index) {
3086  if (*iter == pDimensionRegions[i]->pSample) {
3087  iWaveIndex = index;
3088  break;
3089  }
3090  }
3091  }
3092  store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3093  }
3094  }
3095 
3097  RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3098  if (_3prg) {
3099  int dimensionRegionNr = 0;
3100  RIFF::List* _3ewl = _3prg->GetFirstSubList();
3101  while (_3ewl) {
3102  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3103  pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3104  dimensionRegionNr++;
3105  }
3106  _3ewl = _3prg->GetNextSubList();
3107  }
3108  if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3109  }
3110  }
3111 
3112  void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3113  // update KeyRange struct and make sure regions are in correct order
3114  DLS::Region::SetKeyRange(Low, High);
3115  // update Region key table for fast lookup
3116  ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3117  }
3118 
3120  // get velocity dimension's index
3121  int veldim = -1;
3122  for (int i = 0 ; i < Dimensions ; i++) {
3123  if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3124  veldim = i;
3125  break;
3126  }
3127  }
3128  if (veldim == -1) return;
3129 
3130  int step = 1;
3131  for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3132  int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3133  int end = step * pDimensionDefinitions[veldim].zones;
3134 
3135  // loop through all dimension regions for all dimensions except the velocity dimension
3136  int dim[8] = { 0 };
3137  for (int i = 0 ; i < DimensionRegions ; i++) {
3138 
3139  if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3140  pDimensionRegions[i]->VelocityUpperLimit) {
3141  // create the velocity table
3142  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3143  if (!table) {
3144  table = new uint8_t[128];
3145  pDimensionRegions[i]->VelocityTable = table;
3146  }
3147  int tableidx = 0;
3148  int velocityZone = 0;
3149  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3150  for (int k = i ; k < end ; k += step) {
3152  for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3153  velocityZone++;
3154  }
3155  } else { // gig2
3156  for (int k = i ; k < end ; k += step) {
3158  for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3159  velocityZone++;
3160  }
3161  }
3162  } else {
3163  if (pDimensionRegions[i]->VelocityTable) {
3164  delete[] pDimensionRegions[i]->VelocityTable;
3166  }
3167  }
3168 
3169  int j;
3170  int shift = 0;
3171  for (j = 0 ; j < Dimensions ; j++) {
3172  if (j == veldim) i += skipveldim; // skip velocity dimension
3173  else {
3174  dim[j]++;
3175  if (dim[j] < pDimensionDefinitions[j].zones) break;
3176  else {
3177  // skip unused dimension regions
3178  dim[j] = 0;
3179  i += ((1 << pDimensionDefinitions[j].bits) -
3180  pDimensionDefinitions[j].zones) << shift;
3181  }
3182  }
3183  shift += pDimensionDefinitions[j].bits;
3184  }
3185  if (j == Dimensions) break;
3186  }
3187  }
3188 
3205  // some initial sanity checks of the given dimension definition
3206  if (pDimDef->zones < 2)
3207  throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3208  if (pDimDef->bits < 1)
3209  throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3210  if (pDimDef->dimension == dimension_samplechannel) {
3211  if (pDimDef->zones != 2)
3212  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3213  if (pDimDef->bits != 1)
3214  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3215  }
3216 
3217  // check if max. amount of dimensions reached
3218  File* file = (File*) GetParent()->GetParent();
3219  const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3220  if (Dimensions >= iMaxDimensions)
3221  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3222  // check if max. amount of dimension bits reached
3223  int iCurrentBits = 0;
3224  for (int i = 0; i < Dimensions; i++)
3225  iCurrentBits += pDimensionDefinitions[i].bits;
3226  if (iCurrentBits >= iMaxDimensions)
3227  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3228  const int iNewBits = iCurrentBits + pDimDef->bits;
3229  if (iNewBits > iMaxDimensions)
3230  throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3231  // check if there's already a dimensions of the same type
3232  for (int i = 0; i < Dimensions; i++)
3233  if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3234  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3235 
3236  // pos is where the new dimension should be placed, normally
3237  // last in list, except for the samplechannel dimension which
3238  // has to be first in list
3239  int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3240  int bitpos = 0;
3241  for (int i = 0 ; i < pos ; i++)
3242  bitpos += pDimensionDefinitions[i].bits;
3243 
3244  // make room for the new dimension
3245  for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3246  for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3247  for (int j = Dimensions ; j > pos ; j--) {
3250  }
3251  }
3252 
3253  // assign definition of new dimension
3254  pDimensionDefinitions[pos] = *pDimDef;
3255 
3256  // auto correct certain dimension definition fields (where possible)
3258  __resolveSplitType(pDimensionDefinitions[pos].dimension);
3260  __resolveZoneSize(pDimensionDefinitions[pos]);
3261 
3262  // create new dimension region(s) for this new dimension, and make
3263  // sure that the dimension regions are placed correctly in both the
3264  // RIFF list and the pDimensionRegions array
3265  RIFF::Chunk* moveTo = NULL;
3267  for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3268  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3269  pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3270  }
3271  for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3272  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3273  RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3274  if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3275  // create a new dimension region and copy all parameter values from
3276  // an existing dimension region
3277  pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3278  new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3279 
3280  DimensionRegions++;
3281  }
3282  }
3283  moveTo = pDimensionRegions[i]->pParentList;
3284  }
3285 
3286  // initialize the upper limits for this dimension
3287  int mask = (1 << bitpos) - 1;
3288  for (int z = 0 ; z < pDimDef->zones ; z++) {
3289  uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3290  for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3291  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3292  (z << bitpos) |
3293  (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3294  }
3295  }
3296 
3297  Dimensions++;
3298 
3299  // if this is a layer dimension, update 'Layers' attribute
3300  if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3301 
3303  }
3304 
3317  // get dimension's index
3318  int iDimensionNr = -1;
3319  for (int i = 0; i < Dimensions; i++) {
3320  if (&pDimensionDefinitions[i] == pDimDef) {
3321  iDimensionNr = i;
3322  break;
3323  }
3324  }
3325  if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3326 
3327  // get amount of bits below the dimension to delete
3328  int iLowerBits = 0;
3329  for (int i = 0; i < iDimensionNr; i++)
3330  iLowerBits += pDimensionDefinitions[i].bits;
3331 
3332  // get amount ot bits above the dimension to delete
3333  int iUpperBits = 0;
3334  for (int i = iDimensionNr + 1; i < Dimensions; i++)
3335  iUpperBits += pDimensionDefinitions[i].bits;
3336 
3338 
3339  // delete dimension regions which belong to the given dimension
3340  // (that is where the dimension's bit > 0)
3341  for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3342  for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3343  for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3344  int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3345  iObsoleteBit << iLowerBits |
3346  iLowerBit;
3347 
3348  _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3349  delete pDimensionRegions[iToDelete];
3350  pDimensionRegions[iToDelete] = NULL;
3351  DimensionRegions--;
3352  }
3353  }
3354  }
3355 
3356  // defrag pDimensionRegions array
3357  // (that is remove the NULL spaces within the pDimensionRegions array)
3358  for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3359  if (!pDimensionRegions[iTo]) {
3360  if (iFrom <= iTo) iFrom = iTo + 1;
3361  while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3362  if (iFrom < 256 && pDimensionRegions[iFrom]) {
3363  pDimensionRegions[iTo] = pDimensionRegions[iFrom];
3364  pDimensionRegions[iFrom] = NULL;
3365  }
3366  }
3367  }
3368 
3369  // remove the this dimension from the upper limits arrays
3370  for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3371  DimensionRegion* d = pDimensionRegions[j];
3372  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3373  d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3374  }
3375  d->DimensionUpperLimits[Dimensions - 1] = 127;
3376  }
3377 
3378  // 'remove' dimension definition
3379  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3381  }
3383  pDimensionDefinitions[Dimensions - 1].bits = 0;
3384  pDimensionDefinitions[Dimensions - 1].zones = 0;
3385 
3386  Dimensions--;
3387 
3388  // if this was a layer dimension, update 'Layers' attribute
3389  if (pDimDef->dimension == dimension_layer) Layers = 1;
3390  }
3391 
3407  dimension_def_t* oldDef = GetDimensionDefinition(type);
3408  if (!oldDef)
3409  throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3410  if (oldDef->zones <= 2)
3411  throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3412  if (zone < 0 || zone >= oldDef->zones)
3413  throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3414 
3415  const int newZoneSize = oldDef->zones - 1;
3416 
3417  // create a temporary Region which just acts as a temporary copy
3418  // container and will be deleted at the end of this function and will
3419  // also not be visible through the API during this process
3420  gig::Region* tempRgn = NULL;
3421  {
3422  // adding these temporary chunks is probably not even necessary
3423  Instrument* instr = static_cast<Instrument*>(GetParent());
3424  RIFF::List* pCkInstrument = instr->pCkInstrument;
3425  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3426  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3427  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3428  tempRgn = new Region(instr, rgn);
3429  }
3430 
3431  // copy this region's dimensions (with already the dimension split size
3432  // requested by the arguments of this method call) to the temporary
3433  // region, and don't use Region::CopyAssign() here for this task, since
3434  // it would also alter fast lookup helper variables here and there
3435  dimension_def_t newDef;
3436  for (int i = 0; i < Dimensions; ++i) {
3437  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3438  // is this the dimension requested by the method arguments? ...
3439  if (def.dimension == type) { // ... if yes, decrement zone amount by one
3440  def.zones = newZoneSize;
3441  if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3442  newDef = def;
3443  }
3444  tempRgn->AddDimension(&def);
3445  }
3446 
3447  // find the dimension index in the tempRegion which is the dimension
3448  // type passed to this method (paranoidly expecting different order)
3449  int tempReducedDimensionIndex = -1;
3450  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3451  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3452  tempReducedDimensionIndex = d;
3453  break;
3454  }
3455  }
3456 
3457  // copy dimension regions from this region to the temporary region
3458  for (int iDst = 0; iDst < 256; ++iDst) {
3459  DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3460  if (!dstDimRgn) continue;
3461  std::map<dimension_t,int> dimCase;
3462  bool isValidZone = true;
3463  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3464  const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3465  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3466  (iDst >> baseBits) & ((1 << dstBits) - 1);
3467  baseBits += dstBits;
3468  // there are also DimensionRegion objects of unused zones, skip them
3469  if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3470  isValidZone = false;
3471  break;
3472  }
3473  }
3474  if (!isValidZone) continue;
3475  // a bit paranoid: cope with the chance that the dimensions would
3476  // have different order in source and destination regions
3477  const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3478  if (dimCase[type] >= zone) dimCase[type]++;
3479  DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3480  dstDimRgn->CopyAssign(srcDimRgn);
3481  // if this is the upper most zone of the dimension passed to this
3482  // method, then correct (raise) its upper limit to 127
3483  if (newDef.split_type == split_type_normal && isLastZone)
3484  dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3485  }
3486 
3487  // now tempRegion's dimensions and DimensionRegions basically reflect
3488  // what we wanted to get for this actual Region here, so we now just
3489  // delete and recreate the dimension in question with the new amount
3490  // zones and then copy back from tempRegion
3491  DeleteDimension(oldDef);
3492  AddDimension(&newDef);
3493  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3494  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3495  if (!srcDimRgn) continue;
3496  std::map<dimension_t,int> dimCase;
3497  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3498  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3499  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3500  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3501  baseBits += srcBits;
3502  }
3503  // a bit paranoid: cope with the chance that the dimensions would
3504  // have different order in source and destination regions
3505  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3506  if (!dstDimRgn) continue;
3507  dstDimRgn->CopyAssign(srcDimRgn);
3508  }
3509 
3510  // delete temporary region
3511  delete tempRgn;
3512 
3514  }
3515 
3531  dimension_def_t* oldDef = GetDimensionDefinition(type);
3532  if (!oldDef)
3533  throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3534  if (zone < 0 || zone >= oldDef->zones)
3535  throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3536 
3537  const int newZoneSize = oldDef->zones + 1;
3538 
3539  // create a temporary Region which just acts as a temporary copy
3540  // container and will be deleted at the end of this function and will
3541  // also not be visible through the API during this process
3542  gig::Region* tempRgn = NULL;
3543  {
3544  // adding these temporary chunks is probably not even necessary
3545  Instrument* instr = static_cast<Instrument*>(GetParent());
3546  RIFF::List* pCkInstrument = instr->pCkInstrument;
3547  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3548  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3549  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3550  tempRgn = new Region(instr, rgn);
3551  }
3552 
3553  // copy this region's dimensions (with already the dimension split size
3554  // requested by the arguments of this method call) to the temporary
3555  // region, and don't use Region::CopyAssign() here for this task, since
3556  // it would also alter fast lookup helper variables here and there
3557  dimension_def_t newDef;
3558  for (int i = 0; i < Dimensions; ++i) {
3559  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3560  // is this the dimension requested by the method arguments? ...
3561  if (def.dimension == type) { // ... if yes, increment zone amount by one
3562  def.zones = newZoneSize;
3563  if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3564  newDef = def;
3565  }
3566  tempRgn->AddDimension(&def);
3567  }
3568 
3569  // find the dimension index in the tempRegion which is the dimension
3570  // type passed to this method (paranoidly expecting different order)
3571  int tempIncreasedDimensionIndex = -1;
3572  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3573  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3574  tempIncreasedDimensionIndex = d;
3575  break;
3576  }
3577  }
3578 
3579  // copy dimension regions from this region to the temporary region
3580  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3581  DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3582  if (!srcDimRgn) continue;
3583  std::map<dimension_t,int> dimCase;
3584  bool isValidZone = true;
3585  for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3586  const int srcBits = pDimensionDefinitions[d].bits;
3587  dimCase[pDimensionDefinitions[d].dimension] =
3588  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3589  // there are also DimensionRegion objects for unused zones, skip them
3590  if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3591  isValidZone = false;
3592  break;
3593  }
3594  baseBits += srcBits;
3595  }
3596  if (!isValidZone) continue;
3597  // a bit paranoid: cope with the chance that the dimensions would
3598  // have different order in source and destination regions
3599  if (dimCase[type] > zone) dimCase[type]++;
3600  DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3601  dstDimRgn->CopyAssign(srcDimRgn);
3602  // if this is the requested zone to be splitted, then also copy
3603  // the source DimensionRegion to the newly created target zone
3604  // and set the old zones upper limit lower
3605  if (dimCase[type] == zone) {
3606  // lower old zones upper limit
3607  if (newDef.split_type == split_type_normal) {
3608  const int high =
3609  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3610  int low = 0;
3611  if (zone > 0) {
3612  std::map<dimension_t,int> lowerCase = dimCase;
3613  lowerCase[type]--;
3614  DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3615  low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3616  }
3617  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3618  }
3619  // fill the newly created zone of the divided zone as well
3620  dimCase[type]++;
3621  dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3622  dstDimRgn->CopyAssign(srcDimRgn);
3623  }
3624  }
3625 
3626  // now tempRegion's dimensions and DimensionRegions basically reflect
3627  // what we wanted to get for this actual Region here, so we now just
3628  // delete and recreate the dimension in question with the new amount
3629  // zones and then copy back from tempRegion
3630  DeleteDimension(oldDef);
3631  AddDimension(&newDef);
3632  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3633  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3634  if (!srcDimRgn) continue;
3635  std::map<dimension_t,int> dimCase;
3636  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3637  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3638  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3639  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3640  baseBits += srcBits;
3641  }
3642  // a bit paranoid: cope with the chance that the dimensions would
3643  // have different order in source and destination regions
3644  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3645  if (!dstDimRgn) continue;
3646  dstDimRgn->CopyAssign(srcDimRgn);
3647  }
3648 
3649  // delete temporary region
3650  delete tempRgn;
3651 
3653  }
3654 
3670  if (oldType == newType) return;
3671  dimension_def_t* def = GetDimensionDefinition(oldType);
3672  if (!def)
3673  throw gig::Exception("No dimension with provided old dimension type exists on this region");
3674  if (newType == dimension_samplechannel && def->zones != 2)
3675  throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3676  if (GetDimensionDefinition(newType))
3677  throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3678  def->dimension = newType;
3679  def->split_type = __resolveSplitType(newType);
3680  }
3681 
3682  DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3683  uint8_t bits[8] = {};
3684  for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3685  it != DimCase.end(); ++it)
3686  {
3687  for (int d = 0; d < Dimensions; ++d) {
3688  if (pDimensionDefinitions[d].dimension == it->first) {
3689  bits[d] = it->second;
3690  goto nextDimCaseSlice;
3691  }
3692  }
3693  assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3694  nextDimCaseSlice:
3695  ; // noop
3696  }
3697  return GetDimensionRegionByBit(bits);
3698  }
3699 
3710  for (int i = 0; i < Dimensions; ++i)
3711  if (pDimensionDefinitions[i].dimension == type)
3712  return &pDimensionDefinitions[i];
3713  return NULL;
3714  }
3715 
3717  for (int i = 0; i < 256; i++) {
3718  if (pDimensionRegions[i]) delete pDimensionRegions[i];
3719  }
3720  }
3721 
3741  uint8_t bits;
3742  int veldim = -1;
3743  int velbitpos;
3744  int bitpos = 0;
3745  int dimregidx = 0;
3746  for (uint i = 0; i < Dimensions; i++) {
3747  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3748  // the velocity dimension must be handled after the other dimensions
3749  veldim = i;
3750  velbitpos = bitpos;
3751  } else {
3752  switch (pDimensionDefinitions[i].split_type) {
3753  case split_type_normal:
3754  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3755  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3756  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3757  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3758  }
3759  } else {
3760  // gig2: evenly sized zones
3761  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3762  }
3763  break;
3764  case split_type_bit: // the value is already the sought dimension bit number
3765  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3766  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3767  break;
3768  }
3769  dimregidx |= bits << bitpos;
3770  }
3771  bitpos += pDimensionDefinitions[i].bits;
3772  }
3773  DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3774  if (!dimreg) return NULL;
3775  if (veldim != -1) {
3776  // (dimreg is now the dimension region for the lowest velocity)
3777  if (dimreg->VelocityTable) // custom defined zone ranges
3778  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3779  else // normal split type
3780  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3781 
3782  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3783  dimregidx |= (bits & limiter_mask) << velbitpos;
3784  dimreg = pDimensionRegions[dimregidx & 255];
3785  }
3786  return dimreg;
3787  }
3788 
3789  int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3790  uint8_t bits;
3791  int veldim = -1;
3792  int velbitpos;
3793  int bitpos = 0;
3794  int dimregidx = 0;
3795  for (uint i = 0; i < Dimensions; i++) {
3796  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3797  // the velocity dimension must be handled after the other dimensions
3798  veldim = i;
3799  velbitpos = bitpos;
3800  } else {
3801  switch (pDimensionDefinitions[i].split_type) {
3802  case split_type_normal:
3803  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3804  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3805  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3806  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3807  }
3808  } else {
3809  // gig2: evenly sized zones
3810  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3811  }
3812  break;
3813  case split_type_bit: // the value is already the sought dimension bit number
3814  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3815  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3816  break;
3817  }
3818  dimregidx |= bits << bitpos;
3819  }
3820  bitpos += pDimensionDefinitions[i].bits;
3821  }
3822  dimregidx &= 255;
3823  DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3824  if (!dimreg) return -1;
3825  if (veldim != -1) {
3826  // (dimreg is now the dimension region for the lowest velocity)
3827  if (dimreg->VelocityTable) // custom defined zone ranges
3828  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3829  else // normal split type
3830  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3831 
3832  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3833  dimregidx |= (bits & limiter_mask) << velbitpos;
3834  dimregidx &= 255;
3835  }
3836  return dimregidx;
3837  }
3838 
3850  return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3851  << pDimensionDefinitions[5].bits | DimBits[5])
3852  << pDimensionDefinitions[4].bits | DimBits[4])
3853  << pDimensionDefinitions[3].bits | DimBits[3])
3854  << pDimensionDefinitions[2].bits | DimBits[2])
3855  << pDimensionDefinitions[1].bits | DimBits[1])
3856  << pDimensionDefinitions[0].bits | DimBits[0]];
3857  }
3858 
3869  if (pSample) return static_cast<gig::Sample*>(pSample);
3870  else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3871  }
3872 
3873  Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3874  if ((int32_t)WavePoolTableIndex == -1) return NULL;
3875  File* file = (File*) GetParent()->GetParent();
3876  if (!file->pWavePoolTable) return NULL;
3877  unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3878  unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3879  Sample* sample = file->GetFirstSample(pProgress);
3880  while (sample) {
3881  if (sample->ulWavePoolOffset == soughtoffset &&
3882  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3883  sample = file->GetNextSample();
3884  }
3885  return NULL;
3886  }
3887 
3897  void Region::CopyAssign(const Region* orig) {
3898  CopyAssign(orig, NULL);
3899  }
3900 
3908  void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3909  // handle base classes
3911 
3912  if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3913  pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3914  }
3915 
3916  // handle own member variables
3917  for (int i = Dimensions - 1; i >= 0; --i) {
3919  }
3920  Layers = 0; // just to be sure
3921  for (int i = 0; i < orig->Dimensions; i++) {
3922  // we need to copy the dim definition here, to avoid the compiler
3923  // complaining about const-ness issue
3924  dimension_def_t def = orig->pDimensionDefinitions[i];
3925  AddDimension(&def);
3926  }
3927  for (int i = 0; i < 256; i++) {
3928  if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3930  orig->pDimensionRegions[i],
3931  mSamples
3932  );
3933  }
3934  }
3935  Layers = orig->Layers;
3936  }
3937 
3938 
3939 // *************** MidiRule ***************
3940 // *
3941 
3943  _3ewg->SetPos(36);
3944  Triggers = _3ewg->ReadUint8();
3945  _3ewg->SetPos(40);
3946  ControllerNumber = _3ewg->ReadUint8();
3947  _3ewg->SetPos(46);
3948  for (int i = 0 ; i < Triggers ; i++) {
3949  pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3950  pTriggers[i].Descending = _3ewg->ReadUint8();
3951  pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3952  pTriggers[i].Key = _3ewg->ReadUint8();
3953  pTriggers[i].NoteOff = _3ewg->ReadUint8();
3954  pTriggers[i].Velocity = _3ewg->ReadUint8();
3955  pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3956  _3ewg->ReadUint8();
3957  }
3958  }
3959 
3961  ControllerNumber(0),
3962  Triggers(0) {
3963  }
3964 
3965  void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3966  pData[32] = 4;
3967  pData[33] = 16;
3968  pData[36] = Triggers;
3969  pData[40] = ControllerNumber;
3970  for (int i = 0 ; i < Triggers ; i++) {
3971  pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3972  pData[47 + i * 8] = pTriggers[i].Descending;
3973  pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3974  pData[49 + i * 8] = pTriggers[i].Key;
3975  pData[50 + i * 8] = pTriggers[i].NoteOff;
3976  pData[51 + i * 8] = pTriggers[i].Velocity;
3977  pData[52 + i * 8] = pTriggers[i].OverridePedal;
3978  }
3979  }
3980 
3982  _3ewg->SetPos(36);
3983  LegatoSamples = _3ewg->ReadUint8(); // always 12
3984  _3ewg->SetPos(40);
3985  BypassUseController = _3ewg->ReadUint8();
3986  BypassKey = _3ewg->ReadUint8();
3987  BypassController = _3ewg->ReadUint8();
3988  ThresholdTime = _3ewg->ReadUint16();
3989  _3ewg->ReadInt16();
3990  ReleaseTime = _3ewg->ReadUint16();
3991  _3ewg->ReadInt16();
3992  KeyRange.low = _3ewg->ReadUint8();
3993  KeyRange.high = _3ewg->ReadUint8();
3994  _3ewg->SetPos(64);
3995  ReleaseTriggerKey = _3ewg->ReadUint8();
3996  AltSustain1Key = _3ewg->ReadUint8();
3997  AltSustain2Key = _3ewg->ReadUint8();
3998  }
3999 
4001  LegatoSamples(12),
4002  BypassUseController(false),
4003  BypassKey(0),
4004  BypassController(1),
4005  ThresholdTime(20),
4006  ReleaseTime(20),
4007  ReleaseTriggerKey(0),
4008  AltSustain1Key(0),
4009  AltSustain2Key(0)
4010  {
4011  KeyRange.low = KeyRange.high = 0;
4012  }
4013 
4014  void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4015  pData[32] = 0;
4016  pData[33] = 16;
4017  pData[36] = LegatoSamples;
4018  pData[40] = BypassUseController;
4019  pData[41] = BypassKey;
4020  pData[42] = BypassController;
4021  store16(&pData[43], ThresholdTime);
4022  store16(&pData[47], ReleaseTime);
4023  pData[51] = KeyRange.low;
4024  pData[52] = KeyRange.high;
4025  pData[64] = ReleaseTriggerKey;
4026  pData[65] = AltSustain1Key;
4027  pData[66] = AltSustain2Key;
4028  }
4029 
4031  _3ewg->SetPos(36);
4032  Articulations = _3ewg->ReadUint8();
4033  int flags = _3ewg->ReadUint8();
4034  Polyphonic = flags & 8;
4035  Chained = flags & 4;
4036  Selector = (flags & 2) ? selector_controller :
4037  (flags & 1) ? selector_key_switch : selector_none;
4038  Patterns = _3ewg->ReadUint8();
4039  _3ewg->ReadUint8(); // chosen row
4040  _3ewg->ReadUint8(); // unknown
4041  _3ewg->ReadUint8(); // unknown
4042  _3ewg->ReadUint8(); // unknown
4043  KeySwitchRange.low = _3ewg->ReadUint8();
4044  KeySwitchRange.high = _3ewg->ReadUint8();
4045  Controller = _3ewg->ReadUint8();
4046  PlayRange.low = _3ewg->ReadUint8();
4047  PlayRange.high = _3ewg->ReadUint8();
4048 
4049  int n = std::min(int(Articulations), 32);
4050  for (int i = 0 ; i < n ; i++) {
4051  _3ewg->ReadString(pArticulations[i], 32);
4052  }
4053  _3ewg->SetPos(1072);
4054  n = std::min(int(Patterns), 32);
4055  for (int i = 0 ; i < n ; i++) {
4056  _3ewg->ReadString(pPatterns[i].Name, 16);
4057  pPatterns[i].Size = _3ewg->ReadUint8();
4058  _3ewg->Read(&pPatterns[i][0], 1, 32);
4059  }
4060  }
4061 
4063  Articulations(0),
4064  Patterns(0),
4065  Selector(selector_none),
4066  Controller(0),
4067  Polyphonic(false),
4068  Chained(false)
4069  {
4070  PlayRange.low = PlayRange.high = 0;
4072  }
4073 
4074  void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4075  pData[32] = 3;
4076  pData[33] = 16;
4077  pData[36] = Articulations;
4078  pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4079  (Selector == selector_controller ? 2 :
4080  (Selector == selector_key_switch ? 1 : 0));
4081  pData[38] = Patterns;
4082 
4083  pData[43] = KeySwitchRange.low;
4084  pData[44] = KeySwitchRange.high;
4085  pData[45] = Controller;
4086  pData[46] = PlayRange.low;
4087  pData[47] = PlayRange.high;
4088 
4089  char* str = reinterpret_cast<char*>(pData);
4090  int pos = 48;
4091  int n = std::min(int(Articulations), 32);
4092  for (int i = 0 ; i < n ; i++, pos += 32) {
4093  strncpy(&str[pos], pArticulations[i].c_str(), 32);
4094  }
4095 
4096  pos = 1072;
4097  n = std::min(int(Patterns), 32);
4098  for (int i = 0 ; i < n ; i++, pos += 49) {
4099  strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4100  pData[pos + 16] = pPatterns[i].Size;
4101  memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4102  }
4103  }
4104 
4105 // *************** Script ***************
4106 // *
4107 
4109  pGroup = group;
4110  pChunk = ckScri;
4111  if (ckScri) { // object is loaded from file ...
4112  // read header
4113  uint32_t headerSize = ckScri->ReadUint32();
4114  Compression = (Compression_t) ckScri->ReadUint32();
4115  Encoding = (Encoding_t) ckScri->ReadUint32();
4116  Language = (Language_t) ckScri->ReadUint32();
4117  Bypass = (Language_t) ckScri->ReadUint32() & 1;
4118  crc = ckScri->ReadUint32();
4119  uint32_t nameSize = ckScri->ReadUint32();
4120  Name.resize(nameSize, ' ');
4121  for (int i = 0; i < nameSize; ++i)
4122  Name[i] = ckScri->ReadUint8();
4123  // to handle potential future extensions of the header
4124  ckScri->SetPos(sizeof(int32_t) + headerSize);
4125  // read actual script data
4126  uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4127  data.resize(scriptSize);
4128  for (int i = 0; i < scriptSize; ++i)
4129  data[i] = ckScri->ReadUint8();
4130  } else { // this is a new script object, so just initialize it as such ...
4134  Bypass = false;
4135  crc = 0;
4136  Name = "Unnamed Script";
4137  }
4138  }
4139 
4141  }
4142 
4147  String s;
4148  s.resize(data.size(), ' ');
4149  memcpy(&s[0], &data[0], data.size());
4150  return s;
4151  }
4152 
4159  void Script::SetScriptAsText(const String& text) {
4160  data.resize(text.size());
4161  memcpy(&data[0], &text[0], text.size());
4162  }
4163 
4165  // recalculate CRC32 check sum
4166  __resetCRC(crc);
4167  __calculateCRC(&data[0], data.size(), crc);
4168  __encodeCRC(crc);
4169  // make sure chunk exists and has the required size
4170  const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4171  if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4172  else pChunk->Resize(chunkSize);
4173  // fill the chunk data to be written to disk
4174  uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4175  int pos = 0;
4176  store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4177  pos += sizeof(int32_t);
4178  store32(&pData[pos], Compression);
4179  pos += sizeof(int32_t);
4180  store32(&pData[pos], Encoding);
4181  pos += sizeof(int32_t);
4182  store32(&pData[pos], Language);
4183  pos += sizeof(int32_t);
4184  store32(&pData[pos], Bypass ? 1 : 0);
4185  pos += sizeof(int32_t);
4186  store32(&pData[pos], crc);
4187  pos += sizeof(int32_t);
4188  store32(&pData[pos], Name.size());
4189  pos += sizeof(int32_t);
4190  for (int i = 0; i < Name.size(); ++i, ++pos)
4191  pData[pos] = Name[i];
4192  for (int i = 0; i < data.size(); ++i, ++pos)
4193  pData[pos] = data[i];
4194  }
4195 
4203  if (this->pGroup = pGroup) return;
4204  if (pChunk)
4205  pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4206  this->pGroup = pGroup;
4207  }
4208 
4216  return pGroup;
4217  }
4218 
4220  File* pFile = pGroup->pFile;
4221  for (int i = 0; pFile->GetInstrument(i); ++i) {
4222  Instrument* instr = pFile->GetInstrument(i);
4223  instr->RemoveScript(this);
4224  }
4225  }
4226 
4227 // *************** ScriptGroup ***************
4228 // *
4229 
4231  pFile = file;
4232  pList = lstRTIS;
4233  pScripts = NULL;
4234  if (lstRTIS) {
4235  RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4236  ::LoadString(ckName, Name);
4237  } else {
4238  Name = "Default Group";
4239  }
4240  }
4241 
4243  if (pScripts) {
4244  std::list<Script*>::iterator iter = pScripts->begin();
4245  std::list<Script*>::iterator end = pScripts->end();
4246  while (iter != end) {
4247  delete *iter;
4248  ++iter;
4249  }
4250  delete pScripts;
4251  }
4252  }
4253 
4255  if (pScripts) {
4256  if (!pList)
4258 
4259  // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4260  ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4261 
4262  for (std::list<Script*>::iterator it = pScripts->begin();
4263  it != pScripts->end(); ++it)
4264  {
4265  (*it)->UpdateChunks();
4266  }
4267  }
4268  }
4269 
4278  if (!pScripts) LoadScripts();
4279  std::list<Script*>::iterator it = pScripts->begin();
4280  for (uint i = 0; it != pScripts->end(); ++i, ++it)
4281  if (i == index) return *it;
4282  return NULL;
4283  }
4284 
4297  if (!pScripts) LoadScripts();
4298  Script* pScript = new Script(this, NULL);
4299  pScripts->push_back(pScript);
4300  return pScript;
4301  }
4302 
4314  if (!pScripts) LoadScripts();
4315  std::list<Script*>::iterator iter =
4316  find(pScripts->begin(), pScripts->end(), pScript);
4317  if (iter == pScripts->end())
4318  throw gig::Exception("Could not delete script, could not find given script");
4319  pScripts->erase(iter);
4320  pScript->RemoveAllScriptReferences();
4321  if (pScript->pChunk)
4322  pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4323  delete pScript;
4324  }
4325 
4327  if (pScripts) return;
4328  pScripts = new std::list<Script*>;
4329  if (!pList) return;
4330 
4331  for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4332  ck = pList->GetNextSubChunk())
4333  {
4334  if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4335  pScripts->push_back(new Script(this, ck));
4336  }
4337  }
4338  }
4339 
4340 // *************** Instrument ***************
4341 // *
4342 
4343  Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4344  static const DLS::Info::string_length_t fixedStringLengths[] = {
4345  { CHUNK_ID_INAM, 64 },
4346  { CHUNK_ID_ISFT, 12 },
4347  { 0, 0 }
4348  };
4349  pInfo->SetFixedStringLengths(fixedStringLengths);
4350 
4351  // Initialization
4352  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4353  EffectSend = 0;
4354  Attenuation = 0;
4355  FineTune = 0;
4356  PitchbendRange = 0;
4357  PianoReleaseMode = false;
4358  DimensionKeyRange.low = 0;
4359  DimensionKeyRange.high = 0;
4360  pMidiRules = new MidiRule*[3];
4361  pMidiRules[0] = NULL;
4362  pScriptRefs = NULL;
4363 
4364  // Loading
4365  RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
4366  if (lart) {
4367  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4368  if (_3ewg) {
4369  EffectSend = _3ewg->ReadUint16();
4370  Attenuation = _3ewg->ReadInt32();
4371  FineTune = _3ewg->ReadInt16();
4372  PitchbendRange = _3ewg->ReadInt16();
4373  uint8_t dimkeystart = _3ewg->ReadUint8();
4374  PianoReleaseMode = dimkeystart & 0x01;
4375  DimensionKeyRange.low = dimkeystart >> 1;
4376  DimensionKeyRange.high = _3ewg->ReadUint8();
4377 
4378  if (_3ewg->GetSize() > 32) {
4379  // read MIDI rules
4380  int i = 0;
4381  _3ewg->SetPos(32);
4382  uint8_t id1 = _3ewg->ReadUint8();
4383  uint8_t id2 = _3ewg->ReadUint8();
4384 
4385  if (id2 == 16) {
4386  if (id1 == 4) {
4387  pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4388  } else if (id1 == 0) {
4389  pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4390  } else if (id1 == 3) {
4391  pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4392  } else {
4393  pMidiRules[i++] = new MidiRuleUnknown;
4394  }
4395  }
4396  else if (id1 != 0 || id2 != 0) {
4397  pMidiRules[i++] = new MidiRuleUnknown;
4398  }
4399  //TODO: all the other types of rules
4400 
4401  pMidiRules[i] = NULL;
4402  }
4403  }
4404  }
4405 
4406  if (pFile->GetAutoLoad()) {
4407  if (!pRegions) pRegions = new RegionList;
4408  RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4409  if (lrgn) {
4410  RIFF::List* rgn = lrgn->GetFirstSubList();
4411  while (rgn) {
4412  if (rgn->GetListType() == LIST_TYPE_RGN) {
4413  __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4414  pRegions->push_back(new Region(this, rgn));
4415  }
4416  rgn = lrgn->GetNextSubList();
4417  }
4418  // Creating Region Key Table for fast lookup
4420  }
4421  }
4422 
4423  // own gig format extensions
4424  RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4425  if (lst3LS) {
4426  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4427  if (ckSCSL) {
4428  int headerSize = ckSCSL->ReadUint32();
4429  int slotCount = ckSCSL->ReadUint32();
4430  if (slotCount) {
4431  int slotSize = ckSCSL->ReadUint32();
4432  ckSCSL->SetPos(headerSize); // in case of future header extensions
4433  int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4434  for (int i = 0; i < slotCount; ++i) {
4435  _ScriptPooolEntry e;
4436  e.fileOffset = ckSCSL->ReadUint32();
4437  e.bypass = ckSCSL->ReadUint32() & 1;
4438  if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4439  scriptPoolFileOffsets.push_back(e);
4440  }
4441  }
4442  }
4443  }
4444 
4445  __notify_progress(pProgress, 1.0f); // notify done
4446  }
4447 
4449  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4450  RegionList::iterator iter = pRegions->begin();
4451  RegionList::iterator end = pRegions->end();
4452  for (; iter != end; ++iter) {
4453  gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4454  for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
4455  RegionKeyTable[iKey] = pRegion;
4456  }
4457  }
4458  }
4459 
4461  for (int i = 0 ; pMidiRules[i] ; i++) {
4462  delete pMidiRules[i];
4463  }
4464  delete[] pMidiRules;
4465  if (pScriptRefs) delete pScriptRefs;
4466  }
4467 
4478  // first update base classes' chunks
4480 
4481  // update Regions' chunks
4482  {
4483  RegionList::iterator iter = pRegions->begin();
4484  RegionList::iterator end = pRegions->end();
4485  for (; iter != end; ++iter)
4486  (*iter)->UpdateChunks();
4487  }
4488 
4489  // make sure 'lart' RIFF list chunk exists
4491  if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4492  // make sure '3ewg' RIFF chunk exists
4493  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4494  if (!_3ewg) {
4495  File* pFile = (File*) GetParent();
4496 
4497  // 3ewg is bigger in gig3, as it includes the iMIDI rules
4498  int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4499  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4500  memset(_3ewg->LoadChunkData(), 0, size);
4501  }
4502  // update '3ewg' RIFF chunk
4503  uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4504  store16(&pData[0], EffectSend);
4505  store32(&pData[2], Attenuation);
4506  store16(&pData[6], FineTune);
4507  store16(&pData[8], PitchbendRange);
4508  const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4509  DimensionKeyRange.low << 1;
4510  pData[10] = dimkeystart;
4511  pData[11] = DimensionKeyRange.high;
4512 
4513  if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4514  pData[32] = 0;
4515  pData[33] = 0;
4516  } else {
4517  for (int i = 0 ; pMidiRules[i] ; i++) {
4518  pMidiRules[i]->UpdateChunks(pData);
4519  }
4520  }
4521 
4522  // own gig format extensions
4523  if (ScriptSlotCount()) {
4524  // make sure we have converted the original loaded script file
4525  // offsets into valid Script object pointers
4526  LoadScripts();
4527 
4529  if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4530  const int slotCount = pScriptRefs->size();
4531  const int headerSize = 3 * sizeof(uint32_t);
4532  const int slotSize = 2 * sizeof(uint32_t);
4533  const int totalChunkSize = headerSize + slotCount * slotSize;
4534  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4535  if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4536  else ckSCSL->Resize(totalChunkSize);
4537  uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4538  int pos = 0;
4539  store32(&pData[pos], headerSize);
4540  pos += sizeof(uint32_t);
4541  store32(&pData[pos], slotCount);
4542  pos += sizeof(uint32_t);
4543  store32(&pData[pos], slotSize);
4544  pos += sizeof(uint32_t);
4545  for (int i = 0; i < slotCount; ++i) {
4546  // arbitrary value, the actual file offset will be updated in
4547  // UpdateScriptFileOffsets() after the file has been resized
4548  int bogusFileOffset = 0;
4549  store32(&pData[pos], bogusFileOffset);
4550  pos += sizeof(uint32_t);
4551  store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4552  pos += sizeof(uint32_t);
4553  }
4554  } else {
4555  // no script slots, so get rid of any LS custom RIFF chunks (if any)
4557  if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4558  }
4559  }
4560 
4562  // own gig format extensions
4563  if (pScriptRefs) {
4565  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4566  const int slotCount = pScriptRefs->size();
4567  const int headerSize = 3 * sizeof(uint32_t);
4568  ckSCSL->SetPos(headerSize);
4569  for (int i = 0; i < slotCount; ++i) {
4570  uint32_t fileOffset =
4571  (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4572  (*pScriptRefs)[i].script->pChunk->GetPos() -
4574  ckSCSL->WriteUint32(&fileOffset);
4575  // jump over flags entry (containing the bypass flag)
4576  ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4577  }
4578  }
4579  }
4580 
4588  Region* Instrument::GetRegion(unsigned int Key) {
4589  if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4590  return RegionKeyTable[Key];
4591 
4592  /*for (int i = 0; i < Regions; i++) {
4593  if (Key <= pRegions[i]->KeyRange.high &&
4594  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
4595  }
4596  return NULL;*/
4597  }
4598 
4607  if (!pRegions) return NULL;
4608  RegionsIterator = pRegions->begin();
4609  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4610  }
4611 
4621  if (!pRegions) return NULL;
4622  RegionsIterator++;
4623  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4624  }
4625 
4627  // create new Region object (and its RIFF chunks)
4629  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4630  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4631  Region* pNewRegion = new Region(this, rgn);
4632  pRegions->push_back(pNewRegion);
4633  Regions = pRegions->size();
4634  // update Region key table for fast lookup
4636  // done
4637  return pNewRegion;
4638  }
4639 
4641  if (!pRegions) return;
4643  // update Region key table for fast lookup
4645  }
4646 
4658  return pMidiRules[i];
4659  }
4660 
4667  delete pMidiRules[0];
4669  pMidiRules[0] = r;
4670  pMidiRules[1] = 0;
4671  return r;
4672  }
4673 
4680  delete pMidiRules[0];
4681  MidiRuleLegato* r = new MidiRuleLegato;
4682  pMidiRules[0] = r;
4683  pMidiRules[1] = 0;
4684  return r;
4685  }
4686 
4693  delete pMidiRules[0];
4695  pMidiRules[0] = r;
4696  pMidiRules[1] = 0;
4697  return r;
4698  }
4699 
4706  delete pMidiRules[i];
4707  pMidiRules[i] = 0;
4708  }
4709 
4711  if (pScriptRefs) return;
4712  pScriptRefs = new std::vector<_ScriptPooolRef>;
4713  if (scriptPoolFileOffsets.empty()) return;
4714  File* pFile = (File*) GetParent();
4715  for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4716  uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4717  for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4718  ScriptGroup* group = pFile->GetScriptGroup(i);
4719  for (uint s = 0; group->GetScript(s); ++s) {
4720  Script* script = group->GetScript(s);
4721  if (script->pChunk) {
4722  uint32_t offset = script->pChunk->GetFilePos() -
4723  script->pChunk->GetPos() -
4725  if (offset == soughtOffset)
4726  {
4727  _ScriptPooolRef ref;
4728  ref.script = script;
4729  ref.bypass = scriptPoolFileOffsets[k].bypass;
4730  pScriptRefs->push_back(ref);
4731  break;
4732  }
4733  }
4734  }
4735  }
4736  }
4737  // we don't need that anymore
4738  scriptPoolFileOffsets.clear();
4739  }
4740 
4754  LoadScripts();
4755  if (index >= pScriptRefs->size()) return NULL;
4756  return pScriptRefs->at(index).script;
4757  }
4758 
4794  void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4795  LoadScripts();
4796  _ScriptPooolRef ref = { pScript, bypass };
4797  pScriptRefs->push_back(ref);
4798  }
4799 
4814  void Instrument::SwapScriptSlots(uint index1, uint index2) {
4815  LoadScripts();
4816  if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4817  return;
4818  _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4819  (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4820  (*pScriptRefs)[index2] = tmp;
4821  }
4822 
4829  void Instrument::RemoveScriptSlot(uint index) {
4830  LoadScripts();
4831  if (index >= pScriptRefs->size()) return;
4832  pScriptRefs->erase( pScriptRefs->begin() + index );
4833  }
4834 
4848  LoadScripts();
4849  for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4850  if ((*pScriptRefs)[i].script == pScript) {
4851  pScriptRefs->erase( pScriptRefs->begin() + i );
4852  }
4853  }
4854  }
4855 
4871  return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4872  }
4873 
4891  if (index >= ScriptSlotCount()) return false;
4892  return pScriptRefs ? pScriptRefs->at(index).bypass
4893  : scriptPoolFileOffsets.at(index).bypass;
4894 
4895  }
4896 
4910  void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4911  if (index >= ScriptSlotCount()) return;
4912  if (pScriptRefs)
4913  pScriptRefs->at(index).bypass = bBypass;
4914  else
4915  scriptPoolFileOffsets.at(index).bypass = bBypass;
4916  }
4917 
4928  CopyAssign(orig, NULL);
4929  }
4930 
4939  void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4940  // handle base class
4941  // (without copying DLS region stuff)
4943 
4944  // handle own member variables
4945  Attenuation = orig->Attenuation;
4946  EffectSend = orig->EffectSend;
4947  FineTune = orig->FineTune;
4951  scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
4952  pScriptRefs = orig->pScriptRefs;
4953 
4954  // free old midi rules
4955  for (int i = 0 ; pMidiRules[i] ; i++) {
4956  delete pMidiRules[i];
4957  }
4958  //TODO: MIDI rule copying
4959  pMidiRules[0] = NULL;
4960 
4961  // delete all old regions
4962  while (Regions) DeleteRegion(GetFirstRegion());
4963  // create new regions and copy them from original
4964  {
4965  RegionList::const_iterator it = orig->pRegions->begin();
4966  for (int i = 0; i < orig->Regions; ++i, ++it) {
4967  Region* dstRgn = AddRegion();
4968  //NOTE: Region does semi-deep copy !
4969  dstRgn->CopyAssign(
4970  static_cast<gig::Region*>(*it),
4971  mSamples
4972  );
4973  }
4974  }
4975 
4977  }
4978 
4979 
4980 // *************** Group ***************
4981 // *
4982 
4989  Group::Group(File* file, RIFF::Chunk* ck3gnm) {
4990  pFile = file;
4991  pNameChunk = ck3gnm;
4992  ::LoadString(pNameChunk, Name);
4993  }
4994 
4996  // remove the chunk associated with this group (if any)
4997  if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4998  }
4999 
5009  // make sure <3gri> and <3gnl> list chunks exist
5010  RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5011  if (!_3gri) {
5012  _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5013  pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5014  }
5015  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5016  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5017 
5018  if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5019  // v3 has a fixed list of 128 strings, find a free one
5020  for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5021  if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5022  pNameChunk = ck;
5023  break;
5024  }
5025  }
5026  }
5027 
5028  // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5029  ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5030  }
5031 
5044  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5045  for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5046  if (pSample->GetGroup() == this) return pSample;
5047  }
5048  return NULL;
5049  }
5050 
5062  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5063  for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5064  if (pSample->GetGroup() == this) return pSample;
5065  }
5066  return NULL;
5067  }
5068 
5072  void Group::AddSample(Sample* pSample) {
5073  pSample->pGroup = this;
5074  }
5075 
5083  // get "that" other group first
5084  Group* pOtherGroup = NULL;
5085  for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5086  if (pOtherGroup != this) break;
5087  }
5088  if (!pOtherGroup) throw Exception(
5089  "Could not move samples to another group, since there is no "
5090  "other Group. This is a bug, report it!"
5091  );
5092  // now move all samples of this group to the other group
5093  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5094  pOtherGroup->AddSample(pSample);
5095  }
5096  }
5097 
5098 
5099 
5100 // *************** File ***************
5101 // *
5102 
5105  0, 2, 19980628 & 0xffff, 19980628 >> 16
5106  };
5107 
5110  0, 3, 20030331 & 0xffff, 20030331 >> 16
5111  };
5112 
5113  static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5114  { CHUNK_ID_IARL, 256 },
5115  { CHUNK_ID_IART, 128 },
5116  { CHUNK_ID_ICMS, 128 },
5117  { CHUNK_ID_ICMT, 1024 },
5118  { CHUNK_ID_ICOP, 128 },
5119  { CHUNK_ID_ICRD, 128 },
5120  { CHUNK_ID_IENG, 128 },
5121  { CHUNK_ID_IGNR, 128 },
5122  { CHUNK_ID_IKEY, 128 },
5123  { CHUNK_ID_IMED, 128 },
5124  { CHUNK_ID_INAM, 128 },
5125  { CHUNK_ID_IPRD, 128 },
5126  { CHUNK_ID_ISBJ, 128 },
5127  { CHUNK_ID_ISFT, 128 },
5128  { CHUNK_ID_ISRC, 128 },
5129  { CHUNK_ID_ISRF, 128 },
5130  { CHUNK_ID_ITCH, 128 },
5131  { 0, 0 }
5132  };
5133 
5134  File::File() : DLS::File() {
5135  bAutoLoad = true;
5136  *pVersion = VERSION_3;
5137  pGroups = NULL;
5138  pScriptGroups = NULL;
5139  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5140  pInfo->ArchivalLocation = String(256, ' ');
5141 
5142  // add some mandatory chunks to get the file chunks in right
5143  // order (INFO chunk will be moved to first position later)
5147 
5148  GenerateDLSID();
5149  }
5150 
5151  File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5152  bAutoLoad = true;
5153  pGroups = NULL;
5154  pScriptGroups = NULL;
5155  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5156  }
5157 
5159  if (pGroups) {
5160  std::list<Group*>::iterator iter = pGroups->begin();
5161  std::list<Group*>::iterator end = pGroups->end();
5162  while (iter != end) {
5163  delete *iter;
5164  ++iter;
5165  }
5166  delete pGroups;
5167  }
5168  if (pScriptGroups) {
5169  std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5170  std::list<ScriptGroup*>::iterator end = pScriptGroups->end();
5171  while (iter != end) {
5172  delete *iter;
5173  ++iter;
5174  }
5175  delete pScriptGroups;
5176  }
5177  }
5178 
5180  if (!pSamples) LoadSamples(pProgress);
5181  if (!pSamples) return NULL;
5182  SamplesIterator = pSamples->begin();
5183  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5184  }
5185 
5187  if (!pSamples) return NULL;
5188  SamplesIterator++;
5189  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5190  }
5191 
5197  Sample* File::GetSample(uint index) {
5198  if (!pSamples) LoadSamples();
5199  if (!pSamples) return NULL;
5200  DLS::File::SampleList::iterator it = pSamples->begin();
5201  for (int i = 0; i < index; ++i) {
5202  ++it;
5203  if (it == pSamples->end()) return NULL;
5204  }
5205  if (it == pSamples->end()) return NULL;
5206  return static_cast<gig::Sample*>( *it );
5207  }
5208 
5217  if (!pSamples) LoadSamples();
5220  // create new Sample object and its respective 'wave' list chunk
5221  RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5222  Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5223 
5224  // add mandatory chunks to get the chunks in right order
5225  wave->AddSubChunk(CHUNK_ID_FMT, 16);
5226  wave->AddSubList(LIST_TYPE_INFO);
5227 
5228  pSamples->push_back(pSample);
5229  return pSample;
5230  }
5231 
5241  void File::DeleteSample(Sample* pSample) {
5242  if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5243  SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5244  if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5245  if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5246  pSamples->erase(iter);
5247  delete pSample;
5248 
5249  SampleList::iterator tmp = SamplesIterator;
5250  // remove all references to the sample
5251  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5252  instrument = GetNextInstrument()) {
5253  for (Region* region = instrument->GetFirstRegion() ; region ;
5254  region = instrument->GetNextRegion()) {
5255 
5256  if (region->GetSample() == pSample) region->SetSample(NULL);
5257 
5258  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5259  gig::DimensionRegion *d = region->pDimensionRegions[i];
5260  if (d->pSample == pSample) d->pSample = NULL;
5261  }
5262  }
5263  }
5264  SamplesIterator = tmp; // restore iterator
5265  }
5266 
5268  LoadSamples(NULL);
5269  }
5270 
5271  void File::LoadSamples(progress_t* pProgress) {
5272  // Groups must be loaded before samples, because samples will try
5273  // to resolve the group they belong to
5274  if (!pGroups) LoadGroups();
5275 
5276  if (!pSamples) pSamples = new SampleList;
5277 
5278  RIFF::File* file = pRIFF;
5279 
5280  // just for progress calculation
5281  int iSampleIndex = 0;
5282  int iTotalSamples = WavePoolCount;
5283 
5284  // check if samples should be loaded from extension files
5285  int lastFileNo = 0;
5286  for (int i = 0 ; i < WavePoolCount ; i++) {
5287  if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5288  }
5289  String name(pRIFF->GetFileName());
5290  int nameLen = name.length();
5291  char suffix[6];
5292  if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5293 
5294  for (int fileNo = 0 ; ; ) {
5295  RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5296  if (wvpl) {
5297  unsigned long wvplFileOffset = wvpl->GetFilePos();
5298  RIFF::List* wave = wvpl->GetFirstSubList();
5299  while (wave) {
5300  if (wave->GetListType() == LIST_TYPE_WAVE) {
5301  // notify current progress
5302  const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5303  __notify_progress(pProgress, subprogress);
5304 
5305  unsigned long waveFileOffset = wave->GetFilePos();
5306  pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5307 
5308  iSampleIndex++;
5309  }
5310  wave = wvpl->GetNextSubList();
5311  }
5312 
5313  if (fileNo == lastFileNo) break;
5314 
5315  // open extension file (*.gx01, *.gx02, ...)
5316  fileNo++;
5317  sprintf(suffix, ".gx%02d", fileNo);
5318  name.replace(nameLen, 5, suffix);
5319  file = new RIFF::File(name);
5320  ExtensionFiles.push_back(file);
5321  } else break;
5322  }
5323 
5324  __notify_progress(pProgress, 1.0); // notify done
5325  }
5326 
5328  if (!pInstruments) LoadInstruments();
5329  if (!pInstruments) return NULL;
5330  InstrumentsIterator = pInstruments->begin();
5331  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5332  }
5333 
5335  if (!pInstruments) return NULL;
5337  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5338  }
5339 
5347  Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
5348  if (!pInstruments) {
5349  // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
5350 
5351  // sample loading subtask
5352  progress_t subprogress;
5353  __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5354  __notify_progress(&subprogress, 0.0f);
5355  if (GetAutoLoad())
5356  GetFirstSample(&subprogress); // now force all samples to be loaded
5357  __notify_progress(&subprogress, 1.0f);
5358 
5359  // instrument loading subtask
5360  if (pProgress && pProgress->callback) {
5361  subprogress.__range_min = subprogress.__range_max;
5362  subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
5363  }
5364  __notify_progress(&subprogress, 0.0f);
5365  LoadInstruments(&subprogress);
5366  __notify_progress(&subprogress, 1.0f);
5367  }
5368  if (!pInstruments) return NULL;
5369  InstrumentsIterator = pInstruments->begin();
5370  for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5371  if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5373  }
5374  return NULL;
5375  }
5376 
5385  if (!pInstruments) LoadInstruments();
5387  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5388  RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5389 
5390  // add mandatory chunks to get the chunks in right order
5391  lstInstr->AddSubList(LIST_TYPE_INFO);
5392  lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5393 
5394  Instrument* pInstrument = new Instrument(this, lstInstr);
5395  pInstrument->GenerateDLSID();
5396 
5397  lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5398 
5399  // this string is needed for the gig to be loadable in GSt:
5400  pInstrument->pInfo->Software = "Endless Wave";
5401 
5402  pInstruments->push_back(pInstrument);
5403  return pInstrument;
5404  }
5405 
5422  Instrument* instr = AddInstrument();
5423  instr->CopyAssign(orig);
5424  return instr;
5425  }
5426 
5438  void File::AddContentOf(File* pFile) {
5439  static int iCallCount = -1;
5440  iCallCount++;
5441  std::map<Group*,Group*> mGroups;
5442  std::map<Sample*,Sample*> mSamples;
5443 
5444  // clone sample groups
5445  for (int i = 0; pFile->GetGroup(i); ++i) {
5446  Group* g = AddGroup();
5447  g->Name =
5448  "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5449  mGroups[pFile->GetGroup(i)] = g;
5450  }
5451 
5452  // clone samples (not waveform data here yet)
5453  for (int i = 0; pFile->GetSample(i); ++i) {
5454  Sample* s = AddSample();
5455  s->CopyAssignMeta(pFile->GetSample(i));
5456  mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5457  mSamples[pFile->GetSample(i)] = s;
5458  }
5459 
5460  //BUG: For some reason this method only works with this additional
5461  // Save() call in between here.
5462  //
5463  // Important: The correct one of the 2 Save() methods has to be called
5464  // here, depending on whether the file is completely new or has been
5465  // saved to disk already, otherwise it will result in data corruption.
5466  if (pRIFF->IsNew())
5467  Save(GetFileName());
5468  else
5469  Save();
5470 
5471  // clone instruments
5472  // (passing the crosslink table here for the cloned samples)
5473  for (int i = 0; pFile->GetInstrument(i); ++i) {
5474  Instrument* instr = AddInstrument();
5475  instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5476  }
5477 
5478  // Mandatory: file needs to be saved to disk at this point, so this
5479  // file has the correct size and data layout for writing the samples'
5480  // waveform data to disk.
5481  Save();
5482 
5483  // clone samples' waveform data
5484  // (using direct read & write disk streaming)
5485  for (int i = 0; pFile->GetSample(i); ++i) {
5486  mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5487  }
5488  }
5489 
5498  void File::DeleteInstrument(Instrument* pInstrument) {
5499  if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5500  InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5501  if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5502  pInstruments->erase(iter);
5503  delete pInstrument;
5504  }
5505 
5507  LoadInstruments(NULL);
5508  }
5509 
5512  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5513  if (lstInstruments) {
5514  int iInstrumentIndex = 0;
5515  RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
5516  while (lstInstr) {
5517  if (lstInstr->GetListType() == LIST_TYPE_INS) {
5518  // notify current progress
5519  const float localProgress = (float) iInstrumentIndex / (float) Instruments;
5520  __notify_progress(pProgress, localProgress);
5521 
5522  // divide local progress into subprogress for loading current Instrument
5523  progress_t subprogress;
5524  __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5525 
5526  pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5527 
5528  iInstrumentIndex++;
5529  }
5530  lstInstr = lstInstruments->GetNextSubList();
5531  }
5532  __notify_progress(pProgress, 1.0); // notify done
5533  }
5534  }
5535 
5539  void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5541  if (!_3crc) return;
5542 
5543  // get the index of the sample
5544  int iWaveIndex = -1;
5545  File::SampleList::iterator iter = pSamples->begin();
5546  File::SampleList::iterator end = pSamples->end();
5547  for (int index = 0; iter != end; ++iter, ++index) {
5548  if (*iter == pSample) {
5549  iWaveIndex = index;
5550  break;
5551  }
5552  }
5553  if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5554 
5555  // write the CRC-32 checksum to disk
5556  _3crc->SetPos(iWaveIndex * 8);
5557  uint32_t tmp = 1;
5558  _3crc->WriteUint32(&tmp); // unknown, always 1?
5559  _3crc->WriteUint32(&crc);
5560  }
5561 
5563  if (!pGroups) LoadGroups();
5564  // there must always be at least one group
5565  GroupsIterator = pGroups->begin();
5566  return *GroupsIterator;
5567  }
5568 
5570  if (!pGroups) return NULL;
5571  ++GroupsIterator;
5572  return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5573  }
5574 
5581  Group* File::GetGroup(uint index) {
5582  if (!pGroups) LoadGroups();
5583  GroupsIterator = pGroups->begin();
5584  for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5585  if (i == index) return *GroupsIterator;
5586  ++GroupsIterator;
5587  }
5588  return NULL;
5589  }
5590 
5602  if (!pGroups) LoadGroups();
5603  GroupsIterator = pGroups->begin();
5604  for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5605  if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5606  return NULL;
5607  }
5608 
5610  if (!pGroups) LoadGroups();
5611  // there must always be at least one group
5613  Group* pGroup = new Group(this, NULL);
5614  pGroups->push_back(pGroup);
5615  return pGroup;
5616  }
5617 
5627  void File::DeleteGroup(Group* pGroup) {
5628  if (!pGroups) LoadGroups();
5629  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5630  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5631  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5632  // delete all members of this group
5633  for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5634  DeleteSample(pSample);
5635  }
5636  // now delete this group object
5637  pGroups->erase(iter);
5638  delete pGroup;
5639  }
5640 
5652  if (!pGroups) LoadGroups();
5653  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5654  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5655  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5656  // move all members of this group to another group
5657  pGroup->MoveAll();
5658  pGroups->erase(iter);
5659  delete pGroup;
5660  }
5661 
5663  if (!pGroups) pGroups = new std::list<Group*>;
5664  // try to read defined groups from file
5666  if (lst3gri) {
5667  RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5668  if (lst3gnl) {
5669  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5670  while (ck) {
5671  if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5672  if (pVersion && pVersion->major == 3 &&
5673  strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5674 
5675  pGroups->push_back(new Group(this, ck));
5676  }
5677  ck = lst3gnl->GetNextSubChunk();
5678  }
5679  }
5680  }
5681  // if there were no group(s), create at least the mandatory default group
5682  if (!pGroups->size()) {
5683  Group* pGroup = new Group(this, NULL);
5684  pGroup->Name = "Default Group";
5685  pGroups->push_back(pGroup);
5686  }
5687  }
5688 
5697  if (!pScriptGroups) LoadScriptGroups();
5698  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5699  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5700  if (i == index) return *it;
5701  return NULL;
5702  }
5703 
5713  if (!pScriptGroups) LoadScriptGroups();
5714  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5715  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5716  if ((*it)->Name == name) return *it;
5717  return NULL;
5718  }
5719 
5729  if (!pScriptGroups) LoadScriptGroups();
5730  ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5731  pScriptGroups->push_back(pScriptGroup);
5732  return pScriptGroup;
5733  }
5734 
5747  void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5748  if (!pScriptGroups) LoadScriptGroups();
5749  std::list<ScriptGroup*>::iterator iter =
5750  find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5751  if (iter == pScriptGroups->end())
5752  throw gig::Exception("Could not delete script group, could not find given script group");
5753  pScriptGroups->erase(iter);
5754  for (int i = 0; pScriptGroup->GetScript(i); ++i)
5755  pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5756  if (pScriptGroup->pList)
5757  pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5758  delete pScriptGroup;
5759  }
5760 
5762  if (pScriptGroups) return;
5763  pScriptGroups = new std::list<ScriptGroup*>;
5765  if (lstLS) {
5766  for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5767  lst = lstLS->GetNextSubList())
5768  {
5769  if (lst->GetListType() == LIST_TYPE_RTIS) {
5770  pScriptGroups->push_back(new ScriptGroup(this, lst));
5771  }
5772  }
5773  }
5774  }
5775 
5787  bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5788 
5790 
5791  // update own gig format extension chunks
5792  // (not part of the GigaStudio 4 format)
5793  //
5794  // This must be performed before writing the chunks for instruments,
5795  // because the instruments' script slots will write the file offsets
5796  // of the respective instrument script chunk as reference.
5797  if (pScriptGroups) {
5799  if (pScriptGroups->empty()) {
5800  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5801  } else {
5802  if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5803 
5804  // Update instrument script (group) chunks.
5805 
5806  for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5807  it != pScriptGroups->end(); ++it)
5808  {
5809  (*it)->UpdateChunks();
5810  }
5811  }
5812  }
5813 
5814  // first update base class's chunks
5816 
5817  if (newFile) {
5818  // INFO was added by Resource::UpdateChunks - make sure it
5819  // is placed first in file
5821  RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5822  if (first != info) {
5823  pRIFF->MoveSubChunk(info, first);
5824  }
5825  }
5826 
5827  // update group's chunks
5828  if (pGroups) {
5829  // make sure '3gri' and '3gnl' list chunks exist
5830  // (before updating the Group chunks)
5832  if (!_3gri) {
5833  _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5835  }
5836  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5837  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5838 
5839  // v3: make sure the file has 128 3gnm chunks
5840  // (before updating the Group chunks)
5841  if (pVersion && pVersion->major == 3) {
5842  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5843  for (int i = 0 ; i < 128 ; i++) {
5844  if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5845  if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5846  }
5847  }
5848 
5849  std::list<Group*>::iterator iter = pGroups->begin();
5850  std::list<Group*>::iterator end = pGroups->end();
5851  for (; iter != end; ++iter) {
5852  (*iter)->UpdateChunks();
5853  }
5854  }
5855 
5856  // update einf chunk
5857 
5858  // The einf chunk contains statistics about the gig file, such
5859  // as the number of regions and samples used by each
5860  // instrument. It is divided in equally sized parts, where the
5861  // first part contains information about the whole gig file,
5862  // and the rest of the parts map to each instrument in the
5863  // file.
5864  //
5865  // At the end of each part there is a bit map of each sample
5866  // in the file, where a set bit means that the sample is used
5867  // by the file/instrument.
5868  //
5869  // Note that there are several fields with unknown use. These
5870  // are set to zero.
5871 
5872  int sublen = pSamples->size() / 8 + 49;
5873  int einfSize = (Instruments + 1) * sublen;
5874 
5876  if (einf) {
5877  if (einf->GetSize() != einfSize) {
5878  einf->Resize(einfSize);
5879  memset(einf->LoadChunkData(), 0, einfSize);
5880  }
5881  } else if (newFile) {
5882  einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5883  }
5884  if (einf) {
5885  uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5886 
5887  std::map<gig::Sample*,int> sampleMap;
5888  int sampleIdx = 0;
5889  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5890  sampleMap[pSample] = sampleIdx++;
5891  }
5892 
5893  int totnbusedsamples = 0;
5894  int totnbusedchannels = 0;
5895  int totnbregions = 0;
5896  int totnbdimregions = 0;
5897  int totnbloops = 0;
5898  int instrumentIdx = 0;
5899 
5900  memset(&pData[48], 0, sublen - 48);
5901 
5902  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5903  instrument = GetNextInstrument()) {
5904  int nbusedsamples = 0;
5905  int nbusedchannels = 0;
5906  int nbdimregions = 0;
5907  int nbloops = 0;
5908 
5909  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5910 
5911  for (Region* region = instrument->GetFirstRegion() ; region ;
5912  region = instrument->GetNextRegion()) {
5913  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5914  gig::DimensionRegion *d = region->pDimensionRegions[i];
5915  if (d->pSample) {
5916  int sampleIdx = sampleMap[d->pSample];
5917  int byte = 48 + sampleIdx / 8;
5918  int bit = 1 << (sampleIdx & 7);
5919  if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5920  pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5921  nbusedsamples++;
5922  nbusedchannels += d->pSample->Channels;
5923 
5924  if ((pData[byte] & bit) == 0) {
5925  pData[byte] |= bit;
5926  totnbusedsamples++;
5927  totnbusedchannels += d->pSample->Channels;
5928  }
5929  }
5930  }
5931  if (d->SampleLoops) nbloops++;
5932  }
5933  nbdimregions += region->DimensionRegions;
5934  }
5935  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5936  // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5937  store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5938  store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5939  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5940  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5941  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5942  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5943  // next 8 bytes unknown
5944  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5945  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5946  // next 4 bytes unknown
5947 
5948  totnbregions += instrument->Regions;
5949  totnbdimregions += nbdimregions;
5950  totnbloops += nbloops;
5951  instrumentIdx++;
5952  }
5953  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5954  // store32(&pData[0], sublen);
5955  store32(&pData[4], totnbusedchannels);
5956  store32(&pData[8], totnbusedsamples);
5957  store32(&pData[12], Instruments);
5958  store32(&pData[16], totnbregions);
5959  store32(&pData[20], totnbdimregions);
5960  store32(&pData[24], totnbloops);
5961  // next 8 bytes unknown
5962  // next 4 bytes unknown, not always 0
5963  store32(&pData[40], pSamples->size());
5964  // next 4 bytes unknown
5965  }
5966 
5967  // update 3crc chunk
5968 
5969  // The 3crc chunk contains CRC-32 checksums for the
5970  // samples. The actual checksum values will be filled in
5971  // later, by Sample::Write.
5972 
5974  if (_3crc) {
5975  _3crc->Resize(pSamples->size() * 8);
5976  } else if (newFile) {
5977  _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5978  _3crc->LoadChunkData();
5979 
5980  // the order of einf and 3crc is not the same in v2 and v3
5981  if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5982  }
5983  }
5984 
5987 
5988  for (Instrument* instrument = GetFirstInstrument(); instrument;
5989  instrument = GetNextInstrument())
5990  {
5991  instrument->UpdateScriptFileOffsets();
5992  }
5993  }
5994 
6010  void File::SetAutoLoad(bool b) {
6011  bAutoLoad = b;
6012  }
6013 
6019  return bAutoLoad;
6020  }
6021 
6022 
6023 
6024 // *************** Exception ***************
6025 // *
6026 
6027  Exception::Exception(String Message) : DLS::Exception(Message) {
6028  }
6029 
6031  std::cout << "gig::Exception: " << Message << std::endl;
6032  }
6033 
6034 
6035 // *************** functions ***************
6036 // *
6037 
6044  return PACKAGE;
6045  }
6046 
6052  return VERSION;
6053  }
6054 
6055 } // namespace gig
range_t KeySwitchRange
Key range for key switch selector.
Definition: gig.h:831
bool LFO2FlipPhase
Inverts phase of the filter cutoff LFO wave.
Definition: gig.h:397
void UpdateRegionKeyTable()
Definition: gig.cpp:4448
void SetScriptAsText(const String &text)
Replaces the current script with the new script source code text given by text.
Definition: gig.cpp:4159
void AddContentOf(File *pFile)
Add content of another existing file.
Definition: gig.cpp:5438
#define CHUNK_ID_3GIX
Definition: gig.h:55
void MoveAll()
Move all members of this group to another group (preferably the 1st one except this).
Definition: gig.cpp:5082
#define LIST_TYPE_3GNL
Definition: gig.h:52
unsigned long WriteUint32(uint32_t *pData, unsigned long WordCount=1)
Writes WordCount number of 32 Bit unsigned integer words from the buffer pointed by pData to the chun...
Definition: RIFF.cpp:628
dim_bypass_ctrl_t DimensionBypass
If defined, the MIDI controller can switch on/off the dimension in realtime.
Definition: gig.h:431
~Instrument()
Destructor.
Definition: gig.cpp:4460
Encapsulates articulation information of a dimension region.
Definition: gig.h:356
void LoadScripts()
Definition: gig.cpp:4710
range_t DimensionKeyRange
0-127 (where 0 means C1 and 127 means G9)
Definition: gig.h:949
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:371
#define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x)
Definition: gig.cpp:49
uint8_t VCFVelocityScale
(0-127) Amount velocity controls VCF cutoff frequency (only if no other VCF cutoff controller is defi...
Definition: gig.h:414
void SetDimensionType(dimension_t oldType, dimension_t newType)
Change type of an existing dimension.
Definition: gig.cpp:3669
unsigned long FrameOffset
Current offset (sample points) in current sample frame (for decompression only).
Definition: gig.h:657
bool reverse
If playback direction is currently backwards (in case there is a pingpong or reverse loop defined)...
Definition: gig.h:310
uint8_t AltSustain2Key
Key triggering a second set of alternate sustain samples.
Definition: gig.h:794
uint32_t Regions
Reflects the number of Region defintions this Instrument has.
Definition: DLS.h:465
Region * GetRegion(unsigned int Key)
Returns the appropriate Region for a triggered note.
Definition: gig.cpp:4588
void AddSample(Sample *pSample)
Move Sample given by pSample from another Group to this Group.
Definition: gig.cpp:5072
String GetScriptAsText()
Returns the current script (i.e.
Definition: gig.cpp:4146
virtual void UpdateChunks()
Apply dimension region settings to the respective RIFF chunks.
Definition: gig.cpp:1756
MidiRuleAlternator * AddMidiRuleAlternator()
Adds the alternator MIDI rule to the instrument.
Definition: gig.cpp:4692
virtual void UpdateChunks()
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition: DLS.cpp:1294
Sample * AddSample()
Add a new sample.
Definition: gig.cpp:5216
bool VCFEnabled
If filter should be used.
Definition: gig.h:408
no SMPTE offset
Definition: gig.h:100
void AddDimension(dimension_def_t *pDimDef)
Einstein would have dreamed of it - create a new dimension.
Definition: gig.cpp:3204
stream_whence_t
File stream position dependent to these relations.
Definition: RIFF.h:158
void LoadScripts()
Definition: gig.cpp:4326
uint32_t FineTune
Specifies the fraction of a semitone up from the specified MIDI unity note field. A value of 0x800000...
Definition: gig.h:617
unsigned long Read(void *pData, unsigned long WordCount, unsigned long WordSize)
Reads WordCount number of data words with given WordSize and copies it into a buffer pointed by pData...
Definition: RIFF.cpp:280
uint8_t BypassKey
Key to be used to bypass the sustain note.
Definition: gig.h:787
uint16_t LFO1ControlDepth
Controller depth influencing sample amplitude LFO pitch (0 - 1200 cents).
Definition: gig.h:376
Chunk * GetFirstSubChunk()
Returns the first subchunk within the list.
Definition: RIFF.cpp:1046
lfo1_ctrl_t
Defines how LFO1 is controlled by.
Definition: gig.h:141
Group of Gigasampler objects.
Definition: gig.h:1017
uint32_t LoopType
Defines how the waveform samples will be looped (appropriate loop types for the gig format are define...
Definition: DLS.h:231
uint8_t VCFVelocityDynamicRange
0x04 = lowest, 0x00 = highest .
Definition: gig.h:415
String Name
Stores the name of this Group.
Definition: gig.h:1019
DimensionRegion * GetDimensionRegionByBit(const uint8_t DimBits[8])
Returns the appropriate DimensionRegion for the given dimension bit numbers (zone index)...
Definition: gig.cpp:3849
Special dimension for triggering samples on releasing a key.
Definition: gig.h:228
uint16_t PitchbendRange
Number of semitones pitchbend controller can pitch (default is 2).
Definition: gig.h:947
virtual void UpdateChunks()
Apply all the gig file&#39;s current instruments, samples, groups and settings to the respective RIFF chu...
Definition: gig.cpp:5786
double EG1Release
Release time of the sample amplitude EG (0.000 - 60.000s).
Definition: gig.h:367
#define CHUNK_ID_SMPL
Definition: RIFF.h:106
unsigned long ReadAndLoop(void *pBuffer, unsigned long SampleCount, playback_state_t *pPlaybackState, DimensionRegion *pDimRgn, buffer_t *pExternalDecompressionBuffer=NULL)
Reads SampleCount number of sample points from the position stored in pPlaybackState into the buffer ...
Definition: gig.cpp:926
virtual ~File()
Definition: gig.cpp:5158
#define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)
Definition: gig.cpp:47
uint8_t Triggers
Number of triggers.
Definition: gig.h:764
#define LIST_TYPE_WAVE
Definition: DLS.h:67
uint ScriptSlotCount() const
Instrument&#39;s amount of script slots.
Definition: gig.cpp:4870
#define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)
Definition: gig.cpp:52
virtual void UpdateChunks()
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition: gig.cpp:4477
#define CHUNK_ID_ISBJ
Definition: DLS.h:81
uint32_t GetChunkID()
Chunk ID in unsigned integer representation.
Definition: RIFF.h:187
vcf_type_t VCFType
Defines the general filter characteristic (lowpass, highpass, bandpass, etc.).
Definition: gig.h:409
Script * AddScript()
Add new instrument script.
Definition: gig.cpp:4296
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:1065
void __ensureMandatoryChunksExist()
Checks if all (for DLS) mandatory chunks exist, if not they will be created.
Definition: DLS.cpp:1783
uint32_t LoopSize
Caution: Use the respective fields in the DimensionRegion instead of this one! (Intended purpose: Len...
Definition: gig.h:625
void(* callback)(progress_t *)
Callback function pointer which has to be assigned to a function for progress notification.
Definition: gig.h:327
Instrument * AddInstrument()
Add a new instrument definition.
Definition: gig.cpp:5384
virtual void LoadScriptGroups()
Definition: gig.cpp:5761
Script * GetScript(uint index)
Get instrument script.
Definition: gig.cpp:4277
loop_type_t LoopType
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition: gig.h:622
lfo1_ctrl_t LFO1Controller
MIDI Controller which controls sample amplitude LFO.
Definition: gig.h:377
Group * AddGroup()
Definition: gig.cpp:5609
#define CHUNK_ID_ISRF
Definition: DLS.h:83
#define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)
Definition: gig.cpp:45
#define LIST_TYPE_LART
Definition: DLS.h:71
Only internally controlled.
Definition: gig.h:133
Sample * GetFirstSample()
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: DLS.cpp:1493
uint8_t low
Low value of range.
Definition: gig.h:75
uint16_t SampleStartOffset
Number of samples the sample start should be moved (0 - 2000).
Definition: gig.h:440
MIDI rule for triggering notes by control change events.
Definition: gig.h:761
void UpdateChunks()
Definition: gig.cpp:4254
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:1161
NKSP stands for &quot;Is Not KSP&quot; (default).
Definition: gig.h:872
#define CHUNK_ID_PTBL
Definition: DLS.h:92
uint8_t Key
Key to trigger.
Definition: gig.h:769
unsigned long WorstCaseFrameSize
For compressed samples only: size (in bytes) of the largest possible sample frame.
Definition: gig.h:661
#define LIST_TYPE_WVPL
Definition: DLS.h:65
String GetFileName()
Definition: RIFF.cpp:1596
RIFF::List * pCkRegion
Definition: DLS.h:446
void AddScriptSlot(Script *pScript, bool bypass=false)
Add new instrument script slot (gig format extension).
Definition: gig.cpp:4794
bool EG1Hold
If true, Decay1 stage should be postponed until the sample reached the sample loop start...
Definition: gig.h:368
range_t PlayRange
Key range of the playable keys in the instrument.
Definition: gig.h:809
uint16_t ThresholdTime
Maximum time (ms) between two notes that should be played legato.
Definition: gig.h:789
RIFF::Chunk * pCk3gix
Definition: gig.h:665
unsigned long GetSize() const
Returns sample size.
Definition: DLS.cpp:848
dimension values are already the sought bit number
Definition: gig.h:265
uint8_t VelocityResponseCurveScaling
0 - 127 (usually you don&#39;t have to interpret this parameter, use GetVelocityAttenuation() instead)...
Definition: gig.h:424
bool Descending
If the change in CC value should be downwards.
Definition: gig.h:767
double GetVelocityCutoff(uint8_t MIDIKeyVelocity)
Definition: gig.cpp:2773
unsigned long Size
Size of the actual data in the buffer in bytes.
Definition: gig.h:82
Instrument * GetFirstInstrument()
Returns a pointer to the first Instrument object of the file, NULL otherwise.
Definition: gig.cpp:5327
unsigned long SetPos(unsigned long 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:199
#define CHUNK_ID_ICMT
Definition: RIFF.h:98
void ReadString(String &s, int size)
Reads a null-padded string of size characters and copies it into the string s.
Definition: RIFF.cpp:607
#define CHUNK_ID_ISFT
Definition: RIFF.h:104
Region * RegionKeyTable[128]
fast lookup for the corresponding Region of a MIDI key
Definition: gig.h:978
uint8_t ReleaseTriggerKey
Key triggering release samples.
Definition: gig.h:792
Sample(File *pFile, RIFF::List *waveList, unsigned long WavePoolOffset, unsigned long fileNo=0)
Constructor.
Definition: gig.cpp:370
#define CHUNK_ID_3EWA
Definition: gig.h:56
void UpdateChunks()
Definition: gig.cpp:4164
uint32_t * pWavePoolTable
Definition: DLS.h:529
For MIDI tools like legato and repetition mode.
Definition: gig.h:232
bool VCFKeyboardTracking
If true: VCF cutoff frequence will be dependend to the note key position relative to the defined brea...
Definition: gig.h:419
#define CHUNK_ID_IMED
Definition: DLS.h:80
uint32_t WavePoolTableIndex
Definition: DLS.h:447
uint8_t Velocity
Velocity of the note to trigger. 255 means that velocity should depend on the speed of the controller...
Definition: gig.h:771
void CopyAssignWave(const Sample *orig)
Should be called after CopyAssignMeta() and File::Save() sequence.
Definition: gig.cpp:508
Defines a controller that has a certain contrained influence on a particular synthesis parameter (use...
Definition: gig.h:182
#define CHUNK_ID_IPRD
Definition: RIFF.h:103
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:397
uint8_t Controller
CC number for controller selector.
Definition: gig.h:832
void SetVCFVelocityScale(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2862
RIFF::List * pCkInstrument
Definition: DLS.h:480
Defines Region information of an Instrument.
Definition: gig.h:717
#define GIG_EXP_ENCODE(x)
Definition: gig.cpp:42
uint32_t SamplerOptions
Definition: DLS.h:381
void UpdateVelocityTable()
Definition: gig.cpp:3119
unsigned long SamplesPerFrame
For compressed samples only: number of samples in a full sample frame.
Definition: gig.h:662
uint32_t LoopPlayCount
Number of times the loop should be played (a value of 0 = infinite).
Definition: gig.h:627
uint8_t ReleaseTriggerDecay
0 - 8
Definition: gig.h:427
lfo3_ctrl_t LFO3Controller
MIDI Controller which controls the sample pitch LFO.
Definition: gig.h:405
static unsigned int Instances
Number of instances of class Sample.
Definition: gig.h:654
bool Chained
If all patterns should be chained together.
Definition: gig.h:835
uint32_t MIDIUnityNote
Specifies the musical note at which the sample will be played at it&#39;s original sample rate...
Definition: gig.h:616
uint8_t ControllerNumber
MIDI controller number.
Definition: gig.h:763
#define GIG_PITCH_TRACK_EXTRACT(x)
Definition: gig.cpp:43
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
Definition: RIFF.cpp:1021
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
Definition: RIFF.cpp:1273
uint8_t ChannelOffset
Audio output where the audio signal of the dimension region should be routed to (0 - 9)...
Definition: gig.h:437
void Resize(int iNewSize)
Resize sample.
Definition: gig.cpp:827
Defines Sample Loop Points.
Definition: DLS.h:229
uint8_t VCFResonance
Firm internal filter resonance weight.
Definition: gig.h:416
Standard 8 bit US ASCII character encoding (default).
Definition: gig.h:866
bool VCFResonanceDynamic
If true: Increases the resonance Q according to changes of controllers that actually control the VCF ...
Definition: gig.h:417
Language_t Language
Programming language and dialect the script is written in.
Definition: gig.h:878
void DeleteMidiRule(int i)
Deletes a MIDI rule from the instrument.
Definition: gig.cpp:4705
unsigned int Dimensions
Number of defined dimensions, do not alter!
Definition: gig.h:719
Only controlled by external modulation wheel.
Definition: gig.h:125
#define GIG_VCF_RESONANCE_CTRL_ENCODE(x)
Definition: gig.cpp:46
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:4074
#define CHUNK_ID_SCSL
Definition: gig.h:65
vcf_cutoff_ctrl_t VCFCutoffController
Specifies which external controller has influence on the filter cutoff frequency. ...
Definition: gig.h:410
#define CHUNK_HEADER_SIZE
Definition: RIFF.h:110
virtual void SetGain(int32_t gain)
Definition: DLS.cpp:578
MidiRuleCtrlTrigger * AddMidiRuleCtrlTrigger()
Adds the &quot;controller trigger&quot; MIDI rule to the instrument.
Definition: gig.cpp:4666
unsigned long RemainingBytes()
Returns the number of bytes left to read in the chunk body.
Definition: RIFF.cpp:231
void LoadString(RIFF::Chunk *ck, std::string &s, int strLength)
Definition: SF.cpp:60
double EG1Decay1
Decay time of the sample amplitude EG (0.000 - 60.000s).
Definition: gig.h:363
List * GetFirstSubList()
Returns the first sublist within the list (that is a subchunk with chunk ID &quot;LIST&quot;).
Definition: RIFF.cpp:1080
float __range_min
Only for internal usage, do not modify!
Definition: gig.h:330
DimensionRegion * GetDimensionRegionByValue(const uint DimValues[8])
Use this method in your audio engine to get the appropriate dimension region with it&#39;s articulation d...
Definition: gig.cpp:3740
void UpdateScriptFileOffsets()
Definition: gig.cpp:4561
virtual void UpdateChunks()
Apply Region settings and all its DimensionRegions to the respective RIFF chunks. ...
Definition: gig.cpp:3031
lfo2_ctrl_t LFO2Controller
MIDI Controlle which controls the filter cutoff LFO.
Definition: gig.h:396
Compression_t Compression
Whether the script was/should be compressed, and if so, which compression algorithm shall be used...
Definition: gig.h:876
RIFF::List * pParentList
Definition: DLS.h:379
void LoadDimensionRegions(RIFF::List *rgn)
Definition: gig.cpp:3096
Different samples triggered each time a note is played, any key advances the counter.
Definition: gig.h:233
bool Dithered
For 24-bit compressed samples only: if dithering was used during compression with bit reduction...
Definition: gig.h:630
Region * GetFirstRegion()
Returns the first Region of the instrument.
Definition: gig.cpp:4606
String libraryVersion()
Returns version of this C++ library.
Definition: gig.cpp:6051
#define CHUNK_ID_IKEY
Definition: DLS.h:79
uint8_t VelocityUpperLimit
Defines the upper velocity value limit of a velocity split (only if an user defined limit was set...
Definition: gig.h:358
uint8_t ReleaseVelocityResponseDepth
Dynamic range of release velocity affecting envelope time (0 - 4).
Definition: gig.h:426
RIFF::List * pParentList
Definition: DLS.h:295
void RemoveAllScriptReferences()
Definition: gig.cpp:4219
std::list< Sample * > SampleList
Definition: DLS.h:518
Will be thrown whenever a gig specific error occurs while trying to access a Gigasampler File...
Definition: gig.h:1114
buffer_t LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount)
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition: gig.cpp:716
virtual void UpdateChunks()
Apply all the DLS file&#39;s current instruments, samples and settings to the respective RIFF chunks...
Definition: DLS.cpp:1676
Group * GetGroup() const
Returns pointer to the Group this Sample belongs to.
Definition: gig.cpp:1367
InstrumentList::iterator InstrumentsIterator
Definition: DLS.h:526
Instrument(File *pFile, RIFF::List *insList, progress_t *pProgress=NULL)
Definition: gig.cpp:4343
Used for indicating the progress of a certain task.
Definition: gig.h:326
void GenerateDLSID()
Generates a new DLSID for the resource.
Definition: DLS.cpp:487
uint8_t in_end
End position of fade in.
Definition: gig.h:301
void SetVCFCutoffController(vcf_cutoff_ctrl_t controller)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2835
unsigned long WorstCaseMaxSamples(buffer_t *pDecompressionBuffer)
Definition: gig.h:690
static const DLS::version_t VERSION_2
Reflects Gigasampler file format version 2.0 (1998-06-28).
Definition: gig.h:1038
Sample * pSample
Points to the Sample which is assigned to the dimension region.
Definition: gig.h:359
uint FrameSize
Reflects the size (in bytes) of one single sample point (only if known sample data format is used...
Definition: DLS.h:403
buffer_t LoadSampleData()
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition: gig.cpp:667
uint16_t ReleaseTime
Release time.
Definition: gig.h:790
uint32_t LoopStart
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition: gig.h:623
Group * GetNextGroup()
Returns a pointer to the next Group object of the file, NULL otherwise.
Definition: gig.cpp:5569
Loop forward (normal)
Definition: gig.h:93
unsigned long ReadUint32(uint32_t *pData, unsigned long WordCount=1)
Reads WordCount number of 32 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition: RIFF.cpp:590
void SetVCFVelocityCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2844
#define CHUNK_ID_IENG
Definition: RIFF.h:101
double EG2Decay1
Decay time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:383
#define LIST_TYPE_3PRG
Definition: gig.h:49
uint8_t EG1ControllerAttackInfluence
Amount EG1 Controller has influence on the EG1 Attack time (0 - 3, where 0 means off).
Definition: gig.h:371
unsigned long GetPos()
Position within the chunk data body.
Definition: RIFF.h:192
#define INITIAL_SAMPLE_BUFFER_SIZE
Initial size of the sample buffer which is used for decompression of compressed sample wave streams -...
Definition: gig.cpp:38
unsigned long position
Current position within the sample.
Definition: gig.h:309
String pArticulations[32]
Names of the articulations.
Definition: gig.h:807
crossfade_t Crossfade
Definition: gig.h:429
Compression_t
Definition: gig.h:868
void SetAutoLoad(bool b)
Enable / disable automatic loading.
Definition: gig.cpp:6010
MidiRule * GetMidiRule(int i)
Returns a MIDI rule of the instrument.
Definition: gig.cpp:4657
smpte_format_t SMPTEFormat
Specifies the Society of Motion Pictures and Television E time format used in the following SMPTEOffs...
Definition: gig.h:618
uint16_t low
Low value of range.
Definition: DLS.h:205
double SampleAttenuation
Sample volume (calculated from DLS::Sampler::Gain)
Definition: gig.h:441
File()
Definition: gig.cpp:5134
lfo3_ctrl_t
Defines how LFO3 is controlled by.
Definition: gig.h:123
bool b64BitWavePoolOffsets
Definition: DLS.h:531
RIFF List Chunk.
Definition: RIFF.h:280
#define CHUNK_ID_WSMP
Definition: DLS.h:93
ScriptGroup * GetGroup() const
Returns the script group this script currently belongs to.
Definition: gig.cpp:4215
double EG1Decay2
Only if EG1InfiniteSustain == false: 2nd decay stage time of the sample amplitude EG (0...
Definition: gig.h:364
bool PianoReleaseMode
Definition: gig.h:948
RIFF::Chunk * pCkData
Definition: DLS.h:416
#define CHUNK_ID_VERS
Definition: DLS.h:85
#define LIST_TYPE_3EWL
Definition: gig.h:50
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:292
void RemoveScript(Script *pScript)
Remove reference to given Script (gig format extension).
Definition: gig.cpp:4847
RegionList * pRegions
Definition: DLS.h:481
uint8_t BypassController
Controller to be used to bypass the sustain note.
Definition: gig.h:788
attenuation_ctrl_t AttenuationController
MIDI Controller which has influence on the volume level of the sample (or entire sample group)...
Definition: gig.h:434
float __range_max
Only for internal usage, do not modify!
Definition: gig.h:331
static buffer_t InternalDecompressionBuffer
Buffer used for decompression as well as for truncation of 24 Bit -&gt; 16 Bit samples.
Definition: gig.h:655
static void DestroyDecompressionBuffer(buffer_t &DecompressionBuffer)
Free decompression buffer, previously created with CreateDecompressionBuffer().
Definition: gig.cpp:1350
Pointer address and size of a buffer.
Definition: gig.h:80
virtual void LoadSamples()
Definition: gig.cpp:5267
friend class ScriptGroup
Definition: gig.h:1098
uint8_t in_start
Start position of fade in.
Definition: gig.h:300
uint8_t Patterns
Number of alternator patterns.
Definition: gig.h:811
unsigned long Read(void *pBuffer, unsigned long SampleCount, buffer_t *pExternalDecompressionBuffer=NULL)
Reads SampleCount number of sample points from the current position into the buffer pointed by pBuffe...
Definition: gig.cpp:1101
dimension_t dimension
Specifies which source (usually a MIDI controller) is associated with the dimension.
Definition: gig.h:270
bool Bypass
Global bypass: if enabled, this script shall not be executed by the sampler for any instrument...
Definition: gig.h:879
range_t KeyRange
Key range for legato notes.
Definition: gig.h:791
friend class Sample
Definition: gig.h:1096
unsigned long SamplesInLastFrame
For compressed samples only: length of the last sample frame.
Definition: gig.h:660
bool EG2ControllerInvert
Invert values coming from defined EG2 controller.
Definition: gig.h:389
uint8_t Articulations
Number of articulations in the instrument.
Definition: gig.h:806
friend class Region
Definition: gig.h:987
Group * GetFirstGroup()
Returns a pointer to the first Group object of the file, NULL otherwise.
Definition: gig.cpp:5562
Group * GetGroup(uint index)
Returns the group with the given index.
Definition: gig.cpp:5581
uint8_t VelSensitivity
How sensitive the velocity should be to the speed of the controller change.
Definition: gig.h:768
#define LIST_TYPE_3GRI
Definition: gig.h:51
String Name
Arbitrary name of the script, which may be displayed i.e. in an instrument editor.
Definition: gig.h:875
uint32_t DimensionRegions
Total number of DimensionRegions this Region contains, do not alter!
Definition: gig.h:721
Instrument * AddDuplicateInstrument(const Instrument *orig)
Add a duplicate of an existing instrument.
Definition: gig.cpp:5421
std::string String
Definition: gig.h:71
bool MSDecode
Gigastudio flag: defines if Mid Side Recordings should be decoded.
Definition: gig.h:439
Key Velocity (this is the only dimension in gig2 where the ranges can exactly be defined).
Definition: gig.h:226
bool EG1InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released...
Definition: gig.h:365
bool Compressed
If the sample wave is compressed (probably just interesting for instrument and sample editors...
Definition: gig.h:628
void ReleaseSampleData()
Frees the cached sample from RAM if loaded with LoadSampleData() previously.
Definition: gig.cpp:790
uint32_t SampleLoops
Reflects the number of sample loops.
Definition: DLS.h:370
More poles than normal lowpass.
Definition: gig.h:280
Resource * pParent
Definition: DLS.h:355
uint16_t LFO2InternalDepth
Firm pitch of the filter cutoff LFO (0 - 1200 cents).
Definition: gig.h:394
void Resize(int iNewSize)
Resize sample.
Definition: DLS.cpp:881
SampleList * pSamples
Definition: DLS.h:523
#define CHUNK_ID_FMT
Definition: DLS.h:87
void DeleteDimensionZone(dimension_t type, int zone)
Delete one split zone of a dimension (decrement zone amount).
Definition: gig.cpp:3406
uint16_t LFO1InternalDepth
Firm pitch of the sample amplitude LFO (0 - 1200 cents).
Definition: gig.h:375
#define CHUNK_ID_3CRC
Definition: gig.h:62
The difference between none and none2 is unknown.
Definition: gig.h:152
virtual void LoadInstruments()
Definition: gig.cpp:5506
float zone_size
Intended for internal usage: reflects the size of each zone (128/zones) for normal split types only...
Definition: gig.h:274
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition: gig.cpp:5985
String Message
Definition: RIFF.h:385
bool PitchTrack
If true: sample will be pitched according to the key position (this will be disabled for drums for ex...
Definition: gig.h:430
double GetVelocityRelease(uint8_t MIDIKeyVelocity)
Definition: gig.cpp:2769
#define CHUNK_ID_LSNM
Definition: gig.h:64
unsigned long Write(void *pBuffer, unsigned long SampleCount)
Write sample wave data.
Definition: gig.cpp:1290
unsigned long ReadInt32(int32_t *pData, unsigned long WordCount=1)
Reads WordCount number of 32 Bit signed integer words and copies it into the buffer pointed by pData...
Definition: RIFF.cpp:553
Encoding_t
Definition: gig.h:865
bool BypassUseController
If a controller should be used to bypass the sustain note.
Definition: gig.h:786
virtual void UpdateChunks()
Apply Region settings to the respective RIFF chunks.
Definition: DLS.cpp:1099
unsigned int Layers
Amount of defined layers (1 - 32). A value of 1 actually means no layering, a value &gt; 1 means there i...
Definition: gig.h:723
void * pStart
Points to the beginning of the buffer.
Definition: gig.h:81
bool EG2InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released...
Definition: gig.h:385
Region * AddRegion()
Definition: gig.cpp:4626
unsigned long SamplePos
For compressed samples only: stores the current position (in sample points).
Definition: gig.h:659
Group * pGroup
pointer to the Group this sample belongs to (always not-NULL)
Definition: gig.h:656
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition: RIFF.cpp:1002
Script(ScriptGroup *group, RIFF::Chunk *ckScri)
Definition: gig.cpp:4108
struct gig::MidiRuleAlternator::pattern_t pPatterns[32]
A pattern is a sequence of articulation numbers.
#define LIST_TYPE_3LS
Definition: gig.h:53
#define LIST_TYPE_INS
Definition: DLS.h:69
Chunk * GetNextSubChunk()
Returns the next subchunk within the list.
Definition: RIFF.cpp:1062
MidiRuleLegato * AddMidiRuleLegato()
Adds the legato MIDI rule to the instrument.
Definition: gig.cpp:4679
std::list< Instrument * > InstrumentList
Definition: DLS.h:519
uint8_t EG2ControllerAttackInfluence
Amount EG2 Controller has influence on the EG2 Attack time (0 - 3, where 0 means off).
Definition: gig.h:390
Exception(String Message)
Definition: gig.cpp:6027
bool SelfMask
If true: high velocity notes will stop low velocity notes at the same note, with that you can save vo...
Definition: gig.h:433
#define CHUNK_ID_ICRD
Definition: RIFF.h:100
#define LIST_TYPE_RTIS
Definition: gig.h:54
int16_t LFO3ControlDepth
Controller depth of the sample pitch LFO (-1200 - +1200 cents).
Definition: gig.h:404
RIFF::Chunk * pCkSmpl
Definition: gig.h:666
#define GET_PARAMS(params)
void RemoveScriptSlot(uint index)
Remove script slot.
Definition: gig.cpp:4829
double EG3Attack
Attack time of the sample pitch EG (0.000 - 10.000s).
Definition: gig.h:400
void DeleteDimension(dimension_def_t *pDimDef)
Delete an existing dimension.
Definition: gig.cpp:3316
#define CHUNK_ID_DLID
Definition: DLS.h:86
Instrument * GetNextInstrument()
Returns a pointer to the next Instrument object of the file, NULL otherwise.
Definition: gig.cpp:5334
unsigned long SamplesTotal
Reflects total number of sample points (only if known sample data format is used, 0 otherwise)...
Definition: DLS.h:402
uint8_t LegatoSamples
Number of legato samples per key in each direction (always 12)
Definition: gig.h:785
uint8_t out_end
End postition of fade out.
Definition: gig.h:303
void DeleteGroupOnly(Group *pGroup)
Delete a group.
Definition: gig.cpp:5651
double EG2Attack
Attack time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:382
uint16_t BitDepth
Size of each sample per channel (only if known sample data format is used, 0 otherwise).
Definition: DLS.h:401
bool InvertAttenuationController
Inverts the values coming from the defined Attenuation Controller.
Definition: gig.h:435
double LFO1Frequency
Frequency of the sample amplitude LFO (0.10 - 10.00 Hz).
Definition: gig.h:374
Ordinary RIFF Chunk.
Definition: RIFF.h:183
uint32_t GetListType()
Returns unsigned integer representation of the list&#39;s ID.
Definition: RIFF.h:284
DimensionRegion(Region *pParent, RIFF::List *_3ewl)
Definition: gig.cpp:1390
uint32_t LoopID
Specifies the unique ID that corresponds to one of the defined cue points in the cue point list (only...
Definition: gig.h:621
uint16_t EffectSend
Definition: gig.h:945
#define CHUNK_ID_ICMS
Definition: DLS.h:77
virtual void UpdateChunks()
Update chunks with current group settings.
Definition: gig.cpp:5008
bool LFO1FlipPhase
Inverts phase of the sample amplitude LFO wave.
Definition: gig.h:378
uint8_t AltSustain1Key
Key triggering alternate sustain samples.
Definition: gig.h:793
void DeleteSample(Sample *pSample)
Delete a sample.
Definition: gig.cpp:5241
unsigned long GetFilePos()
Current, actual offset in file.
Definition: RIFF.h:193
int16_t FineTune
in cents
Definition: gig.h:946
Region(Instrument *pInstrument, RIFF::List *rgnList)
Definition: gig.cpp:2938
static buffer_t CreateDecompressionBuffer(unsigned long MaxReadSize)
Allocates a decompression buffer for streaming (compressed) samples with Sample::Read().
Definition: gig.cpp:1333
#define LIST_TYPE_RGN
Definition: DLS.h:73
bool LFO3Sync
If set to true only one LFO should be used for all voices.
Definition: gig.h:406
#define CHUNK_ID_INAM
Definition: RIFF.h:102
bool IsScriptSlotBypassed(uint index)
Whether script execution shall be skipped.
Definition: gig.cpp:4890
double LFO3Frequency
Frequency of the sample pitch LFO (0.10 - 10.00 Hz).
Definition: gig.h:402
static const DLS::version_t VERSION_3
Reflects Gigasampler file format version 3.0 (2003-03-31).
Definition: gig.h:1039
uint32_t LoopLength
Length of the looping area (in sample points).
Definition: DLS.h:233
void DeleteRegion(Region *pRegion)
Definition: gig.cpp:4640
#define CHUNK_ID_ITCH
Definition: DLS.h:84
#define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)
Definition: gig.cpp:50
virtual ~ScriptGroup()
Definition: gig.cpp:4242
ScriptGroup * AddScriptGroup()
Add new instrument script group.
Definition: gig.cpp:5728
#define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)
Definition: gig.cpp:51
#define CHUNK_ID_EINF
Definition: gig.h:61
DimensionRegion * pDimensionRegions[256]
Pointer array to the 32 (gig2) or 256 (gig3) possible dimension regions (reflects NULL for dimension ...
Definition: gig.h:722
#define CHUNK_ID_3EWG
Definition: gig.h:58
uint32_t Product
Specifies the MIDI model ID defined by the manufacturer corresponding to the Manufacturer field...
Definition: gig.h:614
bool LFO1Sync
If set to true only one LFO should be used for all voices.
Definition: gig.h:379
unsigned long ReadInt16(int16_t *pData, unsigned long WordCount=1)
Reads WordCount number of 16 Bit signed integer words and copies it into the buffer pointed by pData...
Definition: RIFF.cpp:479
split_type_t
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition: gig.h:263
Alternating loop (forward/backward, also known as Ping Pong)
Definition: gig.h:94
ScriptGroup * GetScriptGroup(uint index)
Get instrument script group (by index).
Definition: gig.cpp:5696
unsigned long loop_cycles_left
How many times the loop has still to be passed, this value will be decremented with each loop cycle...
Definition: gig.h:311
~Sample()
Destructor.
Definition: gig.cpp:1371
void SetSampleChecksum(Sample *pSample, uint32_t crc)
Updates the 3crc chunk with the checksum of a sample.
Definition: gig.cpp:5539
Sample * GetNextSample()
Returns the next Sample of the Group.
Definition: gig.cpp:5061
uint8_t EG2ControllerReleaseInfluence
Amount EG2 Controller has influence on the EG2 Release time (0 - 3, where 0 means off)...
Definition: gig.h:392
unsigned long Write(void *pData, unsigned long WordCount, unsigned long WordSize)
Writes WordCount number of data words with given WordSize from the buffer pointed by pData...
Definition: RIFF.cpp:338
SampleList::iterator SamplesIterator
Definition: DLS.h:524
List * GetParent()
Returns pointer to the chunk&#39;s parent list chunk.
Definition: RIFF.h:189
uint16_t EG2PreAttack
Preattack value of the filter cutoff EG (0 - 1000 permille).
Definition: gig.h:381
Chunk * AddSubChunk(uint32_t uiChunkID, uint uiBodySize)
Creates a new sub chunk.
Definition: RIFF.cpp:1182
uint32_t Loops
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: Numb...
Definition: gig.h:620
bool LFO2Sync
If set to true only one LFO should be used for all voices.
Definition: gig.h:398
uint32_t SMPTEOffset
The SMPTE Offset value specifies the time offset to be used for the synchronization / calibration to ...
Definition: gig.h:619
unsigned long FileNo
File number (&gt; 0 when sample is stored in an extension file, 0 when it&#39;s in the gig) ...
Definition: gig.h:664
void SplitDimensionZone(dimension_t type, int zone)
Divide split zone of a dimension in two (increment zone amount).
Definition: gig.cpp:3530
Sample * GetFirstSample(progress_t *pProgress=NULL)
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: gig.cpp:5179
bool EG1ControllerInvert
Invert values coming from defined EG1 controller.
Definition: gig.h:370
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:3965
friend class Group
Definition: gig.h:1097
Ordinary MIDI control change controller, see field &#39;controller_number&#39;.
Definition: gig.h:187
vcf_type_t
Defines which frequencies are filtered by the VCF.
Definition: gig.h:278
version_t * pVersion
Points to a version_t structure if the file provided a version number else is set to NULL...
Definition: DLS.h:497
void DeleteInstrument(Instrument *pInstrument)
Delete an instrument.
Definition: gig.cpp:5498
uint16_t LFO2ControlDepth
Controller depth influencing filter cutoff LFO pitch (0 - 1200).
Definition: gig.h:395
uint32_t LoopStart
The start value specifies the offset (in sample points) in the waveform data of the first sample poin...
Definition: DLS.h:232
uint16_t major
Definition: DLS.h:111
RegionList::iterator RegionsIterator
Definition: DLS.h:482
String Name
Name of this script group. For example to be displayed in an instrument editor.
Definition: gig.h:912
int GetDimensionRegionIndexByValue(const uint DimValues[8])
Definition: gig.cpp:3789
Loop backward (reverse)
Definition: gig.h:95
int16_t EG3Depth
Depth of the sample pitch EG (-1200 - +1200).
Definition: gig.h:401
bool GetAutoLoad()
Returns whether automatic loading is enabled.
Definition: gig.cpp:6018
uint8_t VCFKeyboardTrackingBreakpoint
See VCFKeyboardTracking (0 - 127).
Definition: gig.h:420
eg2_ctrl_t EG2Controller
MIDI Controller which has influence on filter cutoff EG parameters (attack, decay, release).
Definition: gig.h:388
#define CHUNK_ID_INSH
Definition: DLS.h:89
For layering of up to 8 instruments (and eventually crossfading of 2 or 4 layers).
Definition: gig.h:225
void * LoadChunkData()
Load chunk body into RAM.
Definition: RIFF.cpp:753
bool VCFCutoffControllerInvert
Inverts values coming from the defined cutoff controller.
Definition: gig.h:411
Different samples triggered each time a note is played, random order.
Definition: gig.h:231
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: gig.cpp:3897
#define LIST_TYPE_LRGN
Definition: DLS.h:70
void * custom
This pointer can be used for arbitrary data.
Definition: gig.h:329
#define CHUNK_ID_IGNR
Definition: DLS.h:78
void SwapScriptSlots(uint index1, uint index2)
Flip two script slots with each other (gig format extension).
Definition: gig.cpp:4814
double EG2Release
Release time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:387
uint8_t EG1ControllerReleaseInfluence
Amount EG1 Controller has influence on the EG1 Release time (0 - 3, where 0 means off)...
Definition: gig.h:373
#define CHUNK_ID_IART
Definition: DLS.h:76
float factor
Reflects current progress as value between 0.0 and 1.0.
Definition: gig.h:328
uint8_t EG2ControllerDecayInfluence
Amount EG2 Controller has influence on the EG2 Decay time (0 - 3, where 0 means off).
Definition: gig.h:391
~Region()
Destructor.
Definition: gig.cpp:3716
unsigned long GetPos() const
Returns the current position in the sample (in sample points).
Definition: gig.cpp:887
bool Polyphonic
If alternator should step forward only when all notes are off.
Definition: gig.h:834
Abstract base class for all MIDI rules.
Definition: gig.h:752
void SetVelocityResponseCurveScaling(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2805
#define CHUNK_ID_3LNK
Definition: gig.h:57
dimension_t
Defines the type of dimension, that is how the dimension zones (and thus how the dimension regions ar...
Definition: gig.h:222
ScriptGroup(File *file, RIFF::List *lstRTIS)
Definition: gig.cpp:4230
gig::buffer_t buffer_t
Definition: Korg.h:79
uint32_t LoopEnd
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition: gig.h:624
curve_type_t ReleaseVelocityResponseCurve
Defines a transformation curve to the incoming release veloctiy values affecting envelope times...
Definition: gig.h:425
Different samples triggered each time a note is played, dimension regions selected in sequence...
Definition: gig.h:230
dimension_def_t pDimensionDefinitions[8]
Defines the five (gig2) or eight (gig3) possible dimensions (the dimension&#39;s controller and number of...
Definition: gig.h:720
#define CHUNK_ID_COLH
Definition: DLS.h:94
uint8_t zones
Number of zones the dimension has.
Definition: gig.h:272
unsigned long GetSize() const
Chunk size in bytes (without header, thus the chunk data body)
Definition: RIFF.h:190
Effect 5 Depth (MIDI Controller 95)
Definition: gig.h:119
#define GIG_EXP_DECODE(x)
(so far) every exponential paramater in the gig format has a basis of 1.000000008813822 ...
Definition: gig.cpp:41
uint8_t AttenuationControllerThreshold
0-127
Definition: gig.h:436
#define CHUNK_ID_ICOP
Definition: RIFF.h:99
RIFF::File * pRIFF
Definition: DLS.h:521
buffer_t GetCache()
Returns current cached sample points.
Definition: gig.cpp:775
void SetVCFVelocityDynamicRange(uint8_t range)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2853
vcf_cutoff_ctrl_t
Defines how the filter cutoff frequency is controlled by.
Definition: gig.h:150
No controller defined.
Definition: gig.h:184
Encapsulates sample waves used for playback.
Definition: gig.h:611
virtual void SetGain(int32_t gain)
Updates the respective member variable and updates SampleAttenuation which depends on this value...
Definition: gig.cpp:1744
RIFF File.
Definition: RIFF.h:328
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
Definition: RIFF.cpp:1253
Group(File *file, RIFF::Chunk *ck3gnm)
Constructor.
Definition: gig.cpp:4989
InstrumentList * pInstruments
Definition: DLS.h:525
virtual void UpdateChunks()
Apply sample and its settings to the respective RIFF chunks.
Definition: DLS.cpp:957
unsigned long GuessSize(unsigned long samples)
Definition: gig.h:673
dimension value between 0-127
Definition: gig.h:264
int16_t LFO3InternalDepth
Firm depth of the sample pitch LFO (-1200 - +1200 cents).
Definition: gig.h:403
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:1925
String Software
&lt;ISFT-ck&gt;. Identifies the name of the sofware package used to create the file.
Definition: DLS.h:317
String ArchivalLocation
&lt;IARL-ck&gt;. Indicates where the subject of the file is stored.
Definition: DLS.h:307
Sample * GetNextSample()
Returns a pointer to the next Sample object of the file, NULL otherwise.
Definition: gig.cpp:5186
unsigned long ulWavePoolOffset
Definition: DLS.h:418
virtual void Save()
Save changes to same file.
Definition: DLS.cpp:1758
virtual ~Script()
Definition: gig.cpp:4140
double EG2Decay2
Only if EG2InfiniteSustain == false: 2nd stage decay time of the filter cutoff EG (0...
Definition: gig.h:384
int32_t Attenuation
in dB
Definition: gig.h:944
Encapsulates sample waves used for playback.
Definition: DLS.h:394
type_t type
Controller type.
Definition: gig.h:190
uint controller_number
MIDI controller number if this controller is a control change controller, 0 otherwise.
Definition: gig.h:191
uint8_t * VelocityTable
For velocity dimensions with custom defined zone ranges only: used for fast converting from velocity ...
Definition: gig.h:473
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
Definition: RIFF.cpp:1205
uint32_t SamplesPerSecond
Sampling rate at which each channel should be played (defaults to 44100 if Sample was created with In...
Definition: DLS.h:398
curve_type_t VelocityResponseCurve
Defines a transformation curve to the incoming velocity values affecting amplitude (usually you don&#39;t...
Definition: gig.h:422
A MIDI rule not yet implemented by libgig.
Definition: gig.h:845
void PrintMessage()
Definition: gig.cpp:6030
uint16_t EG1Sustain
Sustain value of the sample amplitude EG (0 - 1000 permille).
Definition: gig.h:366
Sample * GetSample(uint index)
Returns Sample object of index.
Definition: gig.cpp:5197
uint32_t WavePoolCount
Definition: DLS.h:528
String GetFileName()
File name of this DLS file.
Definition: DLS.cpp:1657
Real-time instrument script (gig format extension).
Definition: gig.h:863
unsigned long NullExtensionSize
The buffer might be bigger than the actual data, if that&#39;s the case that unused space at the end of t...
Definition: gig.h:83
#define CHUNK_ID_3GNM
Definition: gig.h:60
void SetVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2793
RIFF::List * pWaveList
Definition: DLS.h:415
Sample * GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t *pProgress=NULL)
Definition: gig.cpp:3873
uint8_t DimensionUpperLimits[8]
gig3: defines the upper limit of the dimension values for this dimension region. In case you wondered...
Definition: gig.h:442
virtual void CopyAssign(const DimensionRegion *orig)
Make a (semi) deep copy of the DimensionRegion object given by orig and assign it to this object...
Definition: gig.cpp:1686
uint8_t TriggerPoint
The CC value to pass for the note to be triggered.
Definition: gig.h:766
uint8_t VelocityResponseDepth
Dynamic range of velocity affecting amplitude (0 - 4) (usually you don&#39;t have to interpret this param...
Definition: gig.h:423
uint32_t LoopFraction
The fractional value specifies a fraction of a sample at which to loop. This allows a loop to be fine...
Definition: gig.h:626
uint32_t TruncatedBits
For 24-bit compressed samples only: number of bits truncated during compression (0, 4 or 6)
Definition: gig.h:629
Instrument * GetInstrument(uint index, progress_t *pProgress=NULL)
Returns the instrument with the given index.
Definition: gig.cpp:5347
unsigned long ReadUint16(uint16_t *pData, unsigned long WordCount=1)
Reads WordCount number of 16 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition: RIFF.cpp:516
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:759
friend class Script
Definition: gig.h:922
#define LIST_TYPE_LINS
Definition: DLS.h:68
Resource * GetParent()
Definition: DLS.h:349
virtual void UpdateChunks(uint8_t *pData) const =0
#define CHUNK_ID_IARL
Definition: DLS.h:75
Group of instrument scripts (gig format extension).
Definition: gig.h:910
Language_t
Definition: gig.h:871
virtual void UpdateChunks()
Apply sample and its settings to the respective RIFF chunks.
Definition: gig.cpp:535
int8_t Pan
Panorama / Balance (-64..0..63 &lt;-&gt; left..middle..right)
Definition: gig.h:432
Only internally controlled.
Definition: gig.h:142
Parses Gigasampler files and provides abstract access to the data.
Definition: gig.h:1036
void DeleteRegion(Region *pRegion)
Definition: DLS.cpp:1279
void SetGroup(ScriptGroup *pGroup)
Move this script from its current ScriptGroup to another ScriptGroup given by pGroup.
Definition: gig.cpp:4202
lfo2_ctrl_t
Defines how LFO2 is controlled by.
Definition: gig.h:132
Dimension for keyswitching.
Definition: gig.h:229
Sample * pSample
Definition: DLS.h:448
#define LIST_TYPE_INFO
Definition: RIFF.h:97
MIDI rule for instruments with legato samples.
Definition: gig.h:783
virtual ~Group()
Definition: gig.cpp:4995
void SetReleaseVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2826
range_t KeyRange
Definition: DLS.h:430
#define CHUNK_ID_ISRC
Definition: DLS.h:82
Sample * GetFirstSample()
Returns the first Sample of this Group.
Definition: gig.cpp:5043
struct gig::MidiRuleCtrlTrigger::trigger_t pTriggers[32]
dimension_def_t * GetDimensionDefinition(dimension_t type)
Searches in the current Region for a dimension of the given dimension type and returns the precise co...
Definition: gig.cpp:3709
uint16_t EG2Sustain
Sustain value of the filter cutoff EG (0 - 1000 permille).
Definition: gig.h:386
uint32_t Instruments
Reflects the number of available Instrument objects.
Definition: DLS.h:498
Provides all neccessary information for the synthesis of a DLS Instrument.
Definition: DLS.h:458
Provides all neccessary information for the synthesis of an Instrument.
Definition: gig.h:931
void SetScriptSlotBypassed(uint index, bool bBypass)
Defines whether execution shall be skipped.
Definition: gig.cpp:4910
void DeleteGroup(Group *pGroup)
Delete a group and its samples.
Definition: gig.cpp:5627
bool SustainDefeat
If true: Sustain pedal will not hold a note.
Definition: gig.h:438
Encoding_t Encoding
Format the script&#39;s source code text is encoded with.
Definition: gig.h:877
buffer_t RAMCache
Buffers samples (already uncompressed) in RAM.
Definition: gig.h:663
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: gig.cpp:4927
bool NoteOff
If a note off should be triggered instead of a note on.
Definition: gig.h:770
String libraryName()
Returns the name of this C++ library.
Definition: gig.cpp:6043
int32_t Gain
Definition: DLS.h:367
virtual void LoadGroups()
Definition: gig.cpp:5662
Quadtuple version number (&quot;major.minor.release.build&quot;).
Definition: DLS.h:109
#define SKIP_ONE(x)
double LFO2Frequency
Frequency of the filter cutoff LFO (0.10 - 10.00 Hz).
Definition: gig.h:393
unsigned long GetNewSize()
New chunk size if it was modified with Resize().
Definition: RIFF.h:191
uint32_t SamplePeriod
Specifies the duration of time that passes during the playback of one sample in nanoseconds (normally...
Definition: gig.h:615
uint16_t EG1PreAttack
Preattack value of the sample amplitude EG (0 - 1000 permille).
Definition: gig.h:361
Script * GetScriptOfSlot(uint index)
Get instrument script (gig format extension).
Definition: gig.cpp:4753
Dimension not in use.
Definition: gig.h:223
unsigned long * FrameTable
For positioning within compressed samples only: stores the offset values for each frame...
Definition: gig.h:658
void CopyAssignCore(const Instrument *orig)
Definition: DLS.cpp:1341
curve_type_t
Defines the shape of a function graph.
Definition: gig.h:108
uint8_t bits
Number of &quot;bits&quot; (1 bit = 2 splits/zones, 2 bit = 4 splits/zones, 3 bit = 8 splits/zones,...).
Definition: gig.h:271
selector_t Selector
Method by which pattern is chosen.
Definition: gig.h:830
uint8_t out_start
Start position of fade out.
Definition: gig.h:302
uint8_t VCFCutoff
Max. cutoff frequency.
Definition: gig.h:412
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: gig.cpp:3112
unsigned long SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence=RIFF::stream_start)
Sets the position within the sample (in sample points, not in bytes).
Definition: gig.cpp:853
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
Definition: DLS.h:346
uint32_t Manufacturer
Specifies the MIDI Manufacturer&#39;s Association (MMA) Manufacturer code for the sampler intended to rec...
Definition: gig.h:613
uint8_t high
High value of range.
Definition: gig.h:76
virtual void UpdateChunks()
Apply all sample player options to the respective RIFF chunk.
Definition: DLS.cpp:586
bool OverridePedal
If a note off should be triggered even if the sustain pedal is down.
Definition: gig.h:772
MIDI rule to automatically cycle through specified sequences of different articulations.
Definition: gig.h:804
Reflects the current playback state for a sample.
Definition: gig.h:308
Region * GetParent() const
Definition: gig.cpp:2089
General dimension definition.
Definition: gig.h:269
int Size
Number of steps in the pattern.
Definition: gig.h:814
void CopyAssignMeta(const Sample *orig)
Make a (semi) deep copy of the Sample object given by orig (without the actual waveform data) and ass...
Definition: gig.cpp:472
eg1_ctrl_t EG1Controller
MIDI Controller which has influence on sample amplitude EG parameters (attack, decay, release).
Definition: gig.h:369
uint32_t * pWavePoolTableHi
Definition: DLS.h:530
split_type_t split_type
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition: gig.h:273
void DeleteScript(Script *pScript)
Delete an instrument script.
Definition: gig.cpp:4313
If used sample has more than one channel (thus is not mono).
Definition: gig.h:224
void Resize(int iNewSize)
Resize chunk.
Definition: RIFF.cpp:822
void SetReleaseVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2817
vcf_res_ctrl_t VCFResonanceController
Specifies which external controller has influence on the filter resonance Q.
Definition: gig.h:418
Is not compressed at all (default).
Definition: gig.h:869
curve_type_t VCFVelocityCurve
Defines a transformation curve for the incoming velocity values, affecting the VCF.
Definition: gig.h:413
#define GIG_PITCH_TRACK_ENCODE(x)
Definition: gig.cpp:44
uint8_t EG1ControllerDecayInfluence
Amount EG1 Controller has influence on the EG1 Decay time (0 - 3, where 0 means off).
Definition: gig.h:372
List * GetNextSubList()
Returns the next sublist (that is a subchunk with chunk ID &quot;LIST&quot;) within the list.
Definition: RIFF.cpp:1102
Defines Region information of an Instrument.
Definition: DLS.h:428
Effect 4 Depth (MIDI Controller 94)
Definition: gig.h:118
double GetVelocityAttenuation(uint8_t MIDIKeyVelocity)
Returns the correct amplitude factor for the given MIDIKeyVelocity.
Definition: gig.cpp:2765
std::list< RIFF::File * > ExtensionFiles
Definition: DLS.h:522
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:4014
Sample * GetSample()
Returns pointer address to the Sample referenced with this region.
Definition: gig.cpp:3868
void SetVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2781
#define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)
Definition: gig.cpp:48
double EG1Attack
Attack time of the sample amplitude EG (0.000 - 60.000s).
Definition: gig.h:362
void DeleteScriptGroup(ScriptGroup *pGroup)
Delete an instrument script group.
Definition: gig.cpp:5747
unsigned long ReadInt8(int8_t *pData, unsigned long WordCount=1)
Reads WordCount number of 8 Bit signed integer words and copies it into the buffer pointed by pData...
Definition: RIFF.cpp:405
unsigned long ReadUint8(uint8_t *pData, unsigned long WordCount=1)
Reads WordCount number of 8 Bit unsigned integer words and copies it into the buffer pointed by pData...
Definition: RIFF.cpp:442
std::list< Region * > RegionList
Definition: DLS.h:474
Region * GetNextRegion()
Returns the next Region of the instrument.
Definition: gig.cpp:4620
#define CHUNK_ID_SCRI
Definition: gig.h:63
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition: DLS.cpp:1774
#define COPY_ONE(x)
#define CHUNK_ID_EWAV
Definition: gig.h:59