libgig  4.0.0
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-2015 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 // *************** Internal functions for sample decompression ***************
57 // *
58 
59 namespace {
60 
61  inline int get12lo(const unsigned char* pSrc)
62  {
63  const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
64  return x & 0x800 ? x - 0x1000 : x;
65  }
66 
67  inline int get12hi(const unsigned char* pSrc)
68  {
69  const int x = pSrc[1] >> 4 | pSrc[2] << 4;
70  return x & 0x800 ? x - 0x1000 : x;
71  }
72 
73  inline int16_t get16(const unsigned char* pSrc)
74  {
75  return int16_t(pSrc[0] | pSrc[1] << 8);
76  }
77 
78  inline int get24(const unsigned char* pSrc)
79  {
80  const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
81  return x & 0x800000 ? x - 0x1000000 : x;
82  }
83 
84  inline void store24(unsigned char* pDst, int x)
85  {
86  pDst[0] = x;
87  pDst[1] = x >> 8;
88  pDst[2] = x >> 16;
89  }
90 
91  void Decompress16(int compressionmode, const unsigned char* params,
92  int srcStep, int dstStep,
93  const unsigned char* pSrc, int16_t* pDst,
94  unsigned long currentframeoffset,
95  unsigned long copysamples)
96  {
97  switch (compressionmode) {
98  case 0: // 16 bit uncompressed
99  pSrc += currentframeoffset * srcStep;
100  while (copysamples) {
101  *pDst = get16(pSrc);
102  pDst += dstStep;
103  pSrc += srcStep;
104  copysamples--;
105  }
106  break;
107 
108  case 1: // 16 bit compressed to 8 bit
109  int y = get16(params);
110  int dy = get16(params + 2);
111  while (currentframeoffset) {
112  dy -= int8_t(*pSrc);
113  y -= dy;
114  pSrc += srcStep;
115  currentframeoffset--;
116  }
117  while (copysamples) {
118  dy -= int8_t(*pSrc);
119  y -= dy;
120  *pDst = y;
121  pDst += dstStep;
122  pSrc += srcStep;
123  copysamples--;
124  }
125  break;
126  }
127  }
128 
129  void Decompress24(int compressionmode, const unsigned char* params,
130  int dstStep, const unsigned char* pSrc, uint8_t* pDst,
131  unsigned long currentframeoffset,
132  unsigned long copysamples, int truncatedBits)
133  {
134  int y, dy, ddy, dddy;
135 
136 #define GET_PARAMS(params) \
137  y = get24(params); \
138  dy = y - get24((params) + 3); \
139  ddy = get24((params) + 6); \
140  dddy = get24((params) + 9)
141 
142 #define SKIP_ONE(x) \
143  dddy -= (x); \
144  ddy -= dddy; \
145  dy = -dy - ddy; \
146  y += dy
147 
148 #define COPY_ONE(x) \
149  SKIP_ONE(x); \
150  store24(pDst, y << truncatedBits); \
151  pDst += dstStep
152 
153  switch (compressionmode) {
154  case 2: // 24 bit uncompressed
155  pSrc += currentframeoffset * 3;
156  while (copysamples) {
157  store24(pDst, get24(pSrc) << truncatedBits);
158  pDst += dstStep;
159  pSrc += 3;
160  copysamples--;
161  }
162  break;
163 
164  case 3: // 24 bit compressed to 16 bit
165  GET_PARAMS(params);
166  while (currentframeoffset) {
167  SKIP_ONE(get16(pSrc));
168  pSrc += 2;
169  currentframeoffset--;
170  }
171  while (copysamples) {
172  COPY_ONE(get16(pSrc));
173  pSrc += 2;
174  copysamples--;
175  }
176  break;
177 
178  case 4: // 24 bit compressed to 12 bit
179  GET_PARAMS(params);
180  while (currentframeoffset > 1) {
181  SKIP_ONE(get12lo(pSrc));
182  SKIP_ONE(get12hi(pSrc));
183  pSrc += 3;
184  currentframeoffset -= 2;
185  }
186  if (currentframeoffset) {
187  SKIP_ONE(get12lo(pSrc));
188  currentframeoffset--;
189  if (copysamples) {
190  COPY_ONE(get12hi(pSrc));
191  pSrc += 3;
192  copysamples--;
193  }
194  }
195  while (copysamples > 1) {
196  COPY_ONE(get12lo(pSrc));
197  COPY_ONE(get12hi(pSrc));
198  pSrc += 3;
199  copysamples -= 2;
200  }
201  if (copysamples) {
202  COPY_ONE(get12lo(pSrc));
203  }
204  break;
205 
206  case 5: // 24 bit compressed to 8 bit
207  GET_PARAMS(params);
208  while (currentframeoffset) {
209  SKIP_ONE(int8_t(*pSrc++));
210  currentframeoffset--;
211  }
212  while (copysamples) {
213  COPY_ONE(int8_t(*pSrc++));
214  copysamples--;
215  }
216  break;
217  }
218  }
219 
220  const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
221  const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
222  const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
223  const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
224 }
225 
226 
227 
228 // *************** Internal CRC-32 (Cyclic Redundancy Check) functions ***************
229 // *
230 
231  static uint32_t* __initCRCTable() {
232  static uint32_t res[256];
233 
234  for (int i = 0 ; i < 256 ; i++) {
235  uint32_t c = i;
236  for (int j = 0 ; j < 8 ; j++) {
237  c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
238  }
239  res[i] = c;
240  }
241  return res;
242  }
243 
244  static const uint32_t* __CRCTable = __initCRCTable();
245 
251  inline static void __resetCRC(uint32_t& crc) {
252  crc = 0xffffffff;
253  }
254 
274  static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
275  for (int i = 0 ; i < bufSize ; i++) {
276  crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
277  }
278  }
279 
285  inline static uint32_t __encodeCRC(const uint32_t& crc) {
286  return crc ^ 0xffffffff;
287  }
288 
289 
290 
291 // *************** Other Internal functions ***************
292 // *
293 
294  static split_type_t __resolveSplitType(dimension_t dimension) {
295  return (
296  dimension == dimension_layer ||
297  dimension == dimension_samplechannel ||
298  dimension == dimension_releasetrigger ||
299  dimension == dimension_keyboard ||
300  dimension == dimension_roundrobin ||
301  dimension == dimension_random ||
302  dimension == dimension_smartmidi ||
303  dimension == dimension_roundrobinkeyboard
305  }
306 
307  static int __resolveZoneSize(dimension_def_t& dimension_definition) {
308  return (dimension_definition.split_type == split_type_normal)
309  ? int(128.0 / dimension_definition.zones) : 0;
310  }
311 
312 
313 
314 // *************** Sample ***************
315 // *
316 
317  unsigned int Sample::Instances = 0;
319 
338  Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
339  static const DLS::Info::string_length_t fixedStringLengths[] = {
340  { CHUNK_ID_INAM, 64 },
341  { 0, 0 }
342  };
343  pInfo->SetFixedStringLengths(fixedStringLengths);
344  Instances++;
345  FileNo = fileNo;
346 
347  __resetCRC(crc);
348 
349  pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
350  if (pCk3gix) {
351  uint16_t iSampleGroup = pCk3gix->ReadInt16();
352  pGroup = pFile->GetGroup(iSampleGroup);
353  } else { // '3gix' chunk missing
354  // by default assigned to that mandatory "Default Group"
355  pGroup = pFile->GetGroup(0);
356  }
357 
358  pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
359  if (pCkSmpl) {
365  pCkSmpl->Read(&SMPTEFormat, 1, 4);
367  Loops = pCkSmpl->ReadInt32();
368  pCkSmpl->ReadInt32(); // manufByt
369  LoopID = pCkSmpl->ReadInt32();
370  pCkSmpl->Read(&LoopType, 1, 4);
375  } else { // 'smpl' chunk missing
376  // use default values
377  Manufacturer = 0;
378  Product = 0;
379  SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
380  MIDIUnityNote = 60;
381  FineTune = 0;
383  SMPTEOffset = 0;
384  Loops = 0;
385  LoopID = 0;
387  LoopStart = 0;
388  LoopEnd = 0;
389  LoopFraction = 0;
390  LoopPlayCount = 0;
391  }
392 
393  FrameTable = NULL;
394  SamplePos = 0;
395  RAMCache.Size = 0;
396  RAMCache.pStart = NULL;
398 
399  if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
400 
401  RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
402  Compressed = ewav;
403  Dithered = false;
404  TruncatedBits = 0;
405  if (Compressed) {
406  uint32_t version = ewav->ReadInt32();
407  if (version == 3 && BitDepth == 24) {
408  Dithered = ewav->ReadInt32();
409  ewav->SetPos(Channels == 2 ? 84 : 64);
410  TruncatedBits = ewav->ReadInt32();
411  }
412  ScanCompressedSample();
413  }
414 
415  // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
419  }
420  FrameOffset = 0; // just for streaming compressed samples
421 
422  LoopSize = LoopEnd - LoopStart + 1;
423  }
424 
440  void Sample::CopyAssignMeta(const Sample* orig) {
441  // handle base classes
443 
444  // handle actual own attributes of this class
445  Manufacturer = orig->Manufacturer;
446  Product = orig->Product;
447  SamplePeriod = orig->SamplePeriod;
449  FineTune = orig->FineTune;
450  SMPTEFormat = orig->SMPTEFormat;
451  SMPTEOffset = orig->SMPTEOffset;
452  Loops = orig->Loops;
453  LoopID = orig->LoopID;
454  LoopType = orig->LoopType;
455  LoopStart = orig->LoopStart;
456  LoopEnd = orig->LoopEnd;
457  LoopSize = orig->LoopSize;
458  LoopFraction = orig->LoopFraction;
460 
461  // schedule resizing this sample to the given sample's size
462  Resize(orig->GetSize());
463  }
464 
476  void Sample::CopyAssignWave(const Sample* orig) {
477  const int iReadAtOnce = 32*1024;
478  char* buf = new char[iReadAtOnce * orig->FrameSize];
479  Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
480  unsigned long restorePos = pOrig->GetPos();
481  pOrig->SetPos(0);
482  SetPos(0);
483  for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
484  n = pOrig->Read(buf, iReadAtOnce))
485  {
486  Write(buf, n);
487  }
488  pOrig->SetPos(restorePos);
489  delete [] buf;
490  }
491 
504  void Sample::UpdateChunks(progress_t* pProgress) {
505  // first update base class's chunks
506  DLS::Sample::UpdateChunks(pProgress);
507 
508  // make sure 'smpl' chunk exists
510  if (!pCkSmpl) {
512  memset(pCkSmpl->LoadChunkData(), 0, 60);
513  }
514  // update 'smpl' chunk
515  uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
516  SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
517  store32(&pData[0], Manufacturer);
518  store32(&pData[4], Product);
519  store32(&pData[8], SamplePeriod);
520  store32(&pData[12], MIDIUnityNote);
521  store32(&pData[16], FineTune);
522  store32(&pData[20], SMPTEFormat);
523  store32(&pData[24], SMPTEOffset);
524  store32(&pData[28], Loops);
525 
526  // we skip 'manufByt' for now (4 bytes)
527 
528  store32(&pData[36], LoopID);
529  store32(&pData[40], LoopType);
530  store32(&pData[44], LoopStart);
531  store32(&pData[48], LoopEnd);
532  store32(&pData[52], LoopFraction);
533  store32(&pData[56], LoopPlayCount);
534 
535  // make sure '3gix' chunk exists
538  // determine appropriate sample group index (to be stored in chunk)
539  uint16_t iSampleGroup = 0; // 0 refers to default sample group
540  File* pFile = static_cast<File*>(pParent);
541  if (pFile->pGroups) {
542  std::list<Group*>::iterator iter = pFile->pGroups->begin();
543  std::list<Group*>::iterator end = pFile->pGroups->end();
544  for (int i = 0; iter != end; i++, iter++) {
545  if (*iter == pGroup) {
546  iSampleGroup = i;
547  break; // found
548  }
549  }
550  }
551  // update '3gix' chunk
552  pData = (uint8_t*) pCk3gix->LoadChunkData();
553  store16(&pData[0], iSampleGroup);
554 
555  // if the library user toggled the "Compressed" attribute from true to
556  // false, then the EWAV chunk associated with compressed samples needs
557  // to be deleted
559  if (ewav && !Compressed) {
560  pWaveList->DeleteSubChunk(ewav);
561  }
562  }
563 
565  void Sample::ScanCompressedSample() {
566  //TODO: we have to add some more scans here (e.g. determine compression rate)
567  this->SamplesTotal = 0;
568  std::list<unsigned long> frameOffsets;
569 
570  SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
571  WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
572 
573  // Scanning
574  pCkData->SetPos(0);
575  if (Channels == 2) { // Stereo
576  for (int i = 0 ; ; i++) {
577  // for 24 bit samples every 8:th frame offset is
578  // stored, to save some memory
579  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
580 
581  const int mode_l = pCkData->ReadUint8();
582  const int mode_r = pCkData->ReadUint8();
583  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
584  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
585 
586  if (pCkData->RemainingBytes() <= frameSize) {
588  ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
589  (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
591  break;
592  }
594  pCkData->SetPos(frameSize, RIFF::stream_curpos);
595  }
596  }
597  else { // Mono
598  for (int i = 0 ; ; i++) {
599  if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
600 
601  const int mode = pCkData->ReadUint8();
602  if (mode > 5) throw gig::Exception("Unknown compression mode");
603  const unsigned long frameSize = bytesPerFrame[mode];
604 
605  if (pCkData->RemainingBytes() <= frameSize) {
607  ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
609  break;
610  }
612  pCkData->SetPos(frameSize, RIFF::stream_curpos);
613  }
614  }
615  pCkData->SetPos(0);
616 
617  // Build the frames table (which is used for fast resolving of a frame's chunk offset)
618  if (FrameTable) delete[] FrameTable;
619  FrameTable = new unsigned long[frameOffsets.size()];
620  std::list<unsigned long>::iterator end = frameOffsets.end();
621  std::list<unsigned long>::iterator iter = frameOffsets.begin();
622  for (int i = 0; iter != end; i++, iter++) {
623  FrameTable[i] = *iter;
624  }
625  }
626 
637  return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
638  }
639 
662  buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
663  return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
664  }
665 
686  return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
687  }
688 
721  buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
722  if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
723  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
724  unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
725  SetPos(0); // reset read position to begin of sample
726  RAMCache.pStart = new int8_t[allocationsize];
727  RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
728  RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
729  // fill the remaining buffer space with silence samples
730  memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
731  return GetCache();
732  }
733 
745  // return a copy of the buffer_t structure
746  buffer_t result;
747  result.Size = this->RAMCache.Size;
748  result.pStart = this->RAMCache.pStart;
750  return result;
751  }
752 
760  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
761  RAMCache.pStart = NULL;
762  RAMCache.Size = 0;
764  }
765 
796  void Sample::Resize(int iNewSize) {
797  if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
798  DLS::Sample::Resize(iNewSize);
799  }
800 
822  unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
823  if (Compressed) {
824  switch (Whence) {
825  case RIFF::stream_curpos:
826  this->SamplePos += SampleCount;
827  break;
828  case RIFF::stream_end:
829  this->SamplePos = this->SamplesTotal - 1 - SampleCount;
830  break;
832  this->SamplePos -= SampleCount;
833  break;
834  case RIFF::stream_start: default:
835  this->SamplePos = SampleCount;
836  break;
837  }
838  if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
839 
840  unsigned long frame = this->SamplePos / 2048; // to which frame to jump
841  this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
842  pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
843  return this->SamplePos;
844  }
845  else { // not compressed
846  unsigned long orderedBytes = SampleCount * this->FrameSize;
847  unsigned long result = pCkData->SetPos(orderedBytes, Whence);
848  return (result == orderedBytes) ? SampleCount
849  : result / this->FrameSize;
850  }
851  }
852 
856  unsigned long Sample::GetPos() const {
857  if (Compressed) return SamplePos;
858  else return pCkData->GetPos() / FrameSize;
859  }
860 
895  unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
896  DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
897  unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
898  uint8_t* pDst = (uint8_t*) pBuffer;
899 
900  SetPos(pPlaybackState->position); // recover position from the last time
901 
902  if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
903 
904  const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
905  const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
906 
907  if (GetPos() <= loopEnd) {
908  switch (loop.LoopType) {
909 
910  case loop_type_bidirectional: { //TODO: not tested yet!
911  do {
912  // if not endless loop check if max. number of loop cycles have been passed
913  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
914 
915  if (!pPlaybackState->reverse) { // forward playback
916  do {
917  samplestoloopend = loopEnd - GetPos();
918  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
919  samplestoread -= readsamples;
920  totalreadsamples += readsamples;
921  if (readsamples == samplestoloopend) {
922  pPlaybackState->reverse = true;
923  break;
924  }
925  } while (samplestoread && readsamples);
926  }
927  else { // backward playback
928 
929  // as we can only read forward from disk, we have to
930  // determine the end position within the loop first,
931  // read forward from that 'end' and finally after
932  // reading, swap all sample frames so it reflects
933  // backward playback
934 
935  unsigned long swapareastart = totalreadsamples;
936  unsigned long loopoffset = GetPos() - loop.LoopStart;
937  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
938  unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
939 
940  SetPos(reverseplaybackend);
941 
942  // read samples for backward playback
943  do {
944  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
945  samplestoreadinloop -= readsamples;
946  samplestoread -= readsamples;
947  totalreadsamples += readsamples;
948  } while (samplestoreadinloop && readsamples);
949 
950  SetPos(reverseplaybackend); // pretend we really read backwards
951 
952  if (reverseplaybackend == loop.LoopStart) {
953  pPlaybackState->loop_cycles_left--;
954  pPlaybackState->reverse = false;
955  }
956 
957  // reverse the sample frames for backward playback
958  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!
959  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
960  }
961  } while (samplestoread && readsamples);
962  break;
963  }
964 
965  case loop_type_backward: { // TODO: not tested yet!
966  // forward playback (not entered the loop yet)
967  if (!pPlaybackState->reverse) do {
968  samplestoloopend = loopEnd - GetPos();
969  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
970  samplestoread -= readsamples;
971  totalreadsamples += readsamples;
972  if (readsamples == samplestoloopend) {
973  pPlaybackState->reverse = true;
974  break;
975  }
976  } while (samplestoread && readsamples);
977 
978  if (!samplestoread) break;
979 
980  // as we can only read forward from disk, we have to
981  // determine the end position within the loop first,
982  // read forward from that 'end' and finally after
983  // reading, swap all sample frames so it reflects
984  // backward playback
985 
986  unsigned long swapareastart = totalreadsamples;
987  unsigned long loopoffset = GetPos() - loop.LoopStart;
988  unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
989  : samplestoread;
990  unsigned long reverseplaybackend = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
991 
992  SetPos(reverseplaybackend);
993 
994  // read samples for backward playback
995  do {
996  // if not endless loop check if max. number of loop cycles have been passed
997  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
998  samplestoloopend = loopEnd - GetPos();
999  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1000  samplestoreadinloop -= readsamples;
1001  samplestoread -= readsamples;
1002  totalreadsamples += readsamples;
1003  if (readsamples == samplestoloopend) {
1004  pPlaybackState->loop_cycles_left--;
1005  SetPos(loop.LoopStart);
1006  }
1007  } while (samplestoreadinloop && readsamples);
1008 
1009  SetPos(reverseplaybackend); // pretend we really read backwards
1010 
1011  // reverse the sample frames for backward playback
1012  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1013  break;
1014  }
1015 
1016  default: case loop_type_normal: {
1017  do {
1018  // if not endless loop check if max. number of loop cycles have been passed
1019  if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1020  samplestoloopend = loopEnd - GetPos();
1021  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1022  samplestoread -= readsamples;
1023  totalreadsamples += readsamples;
1024  if (readsamples == samplestoloopend) {
1025  pPlaybackState->loop_cycles_left--;
1026  SetPos(loop.LoopStart);
1027  }
1028  } while (samplestoread && readsamples);
1029  break;
1030  }
1031  }
1032  }
1033  }
1034 
1035  // read on without looping
1036  if (samplestoread) do {
1037  readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
1038  samplestoread -= readsamples;
1039  totalreadsamples += readsamples;
1040  } while (readsamples && samplestoread);
1041 
1042  // store current position
1043  pPlaybackState->position = GetPos();
1044 
1045  return totalreadsamples;
1046  }
1047 
1070  unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
1071  if (SampleCount == 0) return 0;
1072  if (!Compressed) {
1073  if (BitDepth == 24) {
1074  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1075  }
1076  else { // 16 bit
1077  // (pCkData->Read does endian correction)
1078  return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
1079  : pCkData->Read(pBuffer, SampleCount, 2);
1080  }
1081  }
1082  else {
1083  if (this->SamplePos >= this->SamplesTotal) return 0;
1084  //TODO: efficiency: maybe we should test for an average compression rate
1085  unsigned long assumedsize = GuessSize(SampleCount),
1086  remainingbytes = 0, // remaining bytes in the local buffer
1087  remainingsamples = SampleCount,
1088  copysamples, skipsamples,
1089  currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
1090  this->FrameOffset = 0;
1091 
1092  buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
1093 
1094  // if decompression buffer too small, then reduce amount of samples to read
1095  if (pDecompressionBuffer->Size < assumedsize) {
1096  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
1097  SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
1098  remainingsamples = SampleCount;
1099  assumedsize = GuessSize(SampleCount);
1100  }
1101 
1102  unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1103  int16_t* pDst = static_cast<int16_t*>(pBuffer);
1104  uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1105  remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1106 
1107  while (remainingsamples && remainingbytes) {
1108  unsigned long framesamples = SamplesPerFrame;
1109  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
1110 
1111  int mode_l = *pSrc++, mode_r = 0;
1112 
1113  if (Channels == 2) {
1114  mode_r = *pSrc++;
1115  framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
1116  rightChannelOffset = bytesPerFrameNoHdr[mode_l];
1117  nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
1118  if (remainingbytes < framebytes) { // last frame in sample
1119  framesamples = SamplesInLastFrame;
1120  if (mode_l == 4 && (framesamples & 1)) {
1121  rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
1122  }
1123  else {
1124  rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
1125  }
1126  }
1127  }
1128  else {
1129  framebytes = bytesPerFrame[mode_l] + 1;
1130  nextFrameOffset = bytesPerFrameNoHdr[mode_l];
1131  if (remainingbytes < framebytes) {
1132  framesamples = SamplesInLastFrame;
1133  }
1134  }
1135 
1136  // determine how many samples in this frame to skip and read
1137  if (currentframeoffset + remainingsamples >= framesamples) {
1138  if (currentframeoffset <= framesamples) {
1139  copysamples = framesamples - currentframeoffset;
1140  skipsamples = currentframeoffset;
1141  }
1142  else {
1143  copysamples = 0;
1144  skipsamples = framesamples;
1145  }
1146  }
1147  else {
1148  // This frame has enough data for pBuffer, but not
1149  // all of the frame is needed. Set file position
1150  // to start of this frame for next call to Read.
1151  copysamples = remainingsamples;
1152  skipsamples = currentframeoffset;
1153  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1154  this->FrameOffset = currentframeoffset + copysamples;
1155  }
1156  remainingsamples -= copysamples;
1157 
1158  if (remainingbytes > framebytes) {
1159  remainingbytes -= framebytes;
1160  if (remainingsamples == 0 &&
1161  currentframeoffset + copysamples == framesamples) {
1162  // This frame has enough data for pBuffer, and
1163  // all of the frame is needed. Set file
1164  // position to start of next frame for next
1165  // call to Read. FrameOffset is 0.
1166  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1167  }
1168  }
1169  else remainingbytes = 0;
1170 
1171  currentframeoffset -= skipsamples;
1172 
1173  if (copysamples == 0) {
1174  // skip this frame
1175  pSrc += framebytes - Channels;
1176  }
1177  else {
1178  const unsigned char* const param_l = pSrc;
1179  if (BitDepth == 24) {
1180  if (mode_l != 2) pSrc += 12;
1181 
1182  if (Channels == 2) { // Stereo
1183  const unsigned char* const param_r = pSrc;
1184  if (mode_r != 2) pSrc += 12;
1185 
1186  Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1187  skipsamples, copysamples, TruncatedBits);
1188  Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1189  skipsamples, copysamples, TruncatedBits);
1190  pDst24 += copysamples * 6;
1191  }
1192  else { // Mono
1193  Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1194  skipsamples, copysamples, TruncatedBits);
1195  pDst24 += copysamples * 3;
1196  }
1197  }
1198  else { // 16 bit
1199  if (mode_l) pSrc += 4;
1200 
1201  int step;
1202  if (Channels == 2) { // Stereo
1203  const unsigned char* const param_r = pSrc;
1204  if (mode_r) pSrc += 4;
1205 
1206  step = (2 - mode_l) + (2 - mode_r);
1207  Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1208  Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1209  skipsamples, copysamples);
1210  pDst += copysamples << 1;
1211  }
1212  else { // Mono
1213  step = 2 - mode_l;
1214  Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1215  pDst += copysamples;
1216  }
1217  }
1218  pSrc += nextFrameOffset;
1219  }
1220 
1221  // reload from disk to local buffer if needed
1222  if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1223  assumedsize = GuessSize(remainingsamples);
1224  pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1225  if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1226  remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1227  pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1228  }
1229  } // while
1230 
1231  this->SamplePos += (SampleCount - remainingsamples);
1232  if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1233  return (SampleCount - remainingsamples);
1234  }
1235  }
1236 
1259  unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1260  if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1261 
1262  // if this is the first write in this sample, reset the
1263  // checksum calculator
1264  if (pCkData->GetPos() == 0) {
1265  __resetCRC(crc);
1266  }
1267  if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1268  unsigned long res;
1269  if (BitDepth == 24) {
1270  res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1271  } else { // 16 bit
1272  res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1273  : pCkData->Write(pBuffer, SampleCount, 2);
1274  }
1275  __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1276 
1277  // if this is the last write, update the checksum chunk in the
1278  // file
1279  if (pCkData->GetPos() == pCkData->GetSize()) {
1280  File* pFile = static_cast<File*>(GetParent());
1281  pFile->SetSampleChecksum(this, __encodeCRC(crc));
1282  }
1283  return res;
1284  }
1285 
1302  buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1303  buffer_t result;
1304  const double worstCaseHeaderOverhead =
1305  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1306  result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1307  result.pStart = new int8_t[result.Size];
1308  result.NullExtensionSize = 0;
1309  return result;
1310  }
1311 
1319  void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1320  if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1321  delete[] (int8_t*) DecompressionBuffer.pStart;
1322  DecompressionBuffer.pStart = NULL;
1323  DecompressionBuffer.Size = 0;
1324  DecompressionBuffer.NullExtensionSize = 0;
1325  }
1326  }
1327 
1337  return pGroup;
1338  }
1339 
1341  Instances--;
1343  delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1346  }
1347  if (FrameTable) delete[] FrameTable;
1348  if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1349  }
1350 
1351 
1352 
1353 // *************** DimensionRegion ***************
1354 // *
1355 
1356  uint DimensionRegion::Instances = 0;
1357  DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1358 
1360  Instances++;
1361 
1362  pSample = NULL;
1363  pRegion = pParent;
1364 
1365  if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1366  else memset(&Crossfade, 0, 4);
1367 
1368  if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1369 
1370  RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1371  if (_3ewa) { // if '3ewa' chunk exists
1372  _3ewa->ReadInt32(); // unknown, always == chunk size ?
1373  LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1374  EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1375  _3ewa->ReadInt16(); // unknown
1376  LFO1InternalDepth = _3ewa->ReadUint16();
1377  _3ewa->ReadInt16(); // unknown
1378  LFO3InternalDepth = _3ewa->ReadInt16();
1379  _3ewa->ReadInt16(); // unknown
1380  LFO1ControlDepth = _3ewa->ReadUint16();
1381  _3ewa->ReadInt16(); // unknown
1382  LFO3ControlDepth = _3ewa->ReadInt16();
1383  EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1384  EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1385  _3ewa->ReadInt16(); // unknown
1386  EG1Sustain = _3ewa->ReadUint16();
1387  EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1388  EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1389  uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1390  EG1ControllerInvert = eg1ctrloptions & 0x01;
1394  EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1395  uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1396  EG2ControllerInvert = eg2ctrloptions & 0x01;
1400  LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1401  EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1402  EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1403  _3ewa->ReadInt16(); // unknown
1404  EG2Sustain = _3ewa->ReadUint16();
1405  EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1406  _3ewa->ReadInt16(); // unknown
1407  LFO2ControlDepth = _3ewa->ReadUint16();
1408  LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1409  _3ewa->ReadInt16(); // unknown
1410  LFO2InternalDepth = _3ewa->ReadUint16();
1411  int32_t eg1decay2 = _3ewa->ReadInt32();
1412  EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1413  EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1414  _3ewa->ReadInt16(); // unknown
1415  EG1PreAttack = _3ewa->ReadUint16();
1416  int32_t eg2decay2 = _3ewa->ReadInt32();
1417  EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1418  EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1419  _3ewa->ReadInt16(); // unknown
1420  EG2PreAttack = _3ewa->ReadUint16();
1421  uint8_t velocityresponse = _3ewa->ReadUint8();
1422  if (velocityresponse < 5) {
1424  VelocityResponseDepth = velocityresponse;
1425  } else if (velocityresponse < 10) {
1427  VelocityResponseDepth = velocityresponse - 5;
1428  } else if (velocityresponse < 15) {
1430  VelocityResponseDepth = velocityresponse - 10;
1431  } else {
1434  }
1435  uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1436  if (releasevelocityresponse < 5) {
1438  ReleaseVelocityResponseDepth = releasevelocityresponse;
1439  } else if (releasevelocityresponse < 10) {
1441  ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1442  } else if (releasevelocityresponse < 15) {
1444  ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1445  } else {
1448  }
1451  _3ewa->ReadInt32(); // unknown
1452  SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1453  _3ewa->ReadInt16(); // unknown
1454  uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1455  PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1456  if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1457  else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1459  uint8_t pan = _3ewa->ReadUint8();
1460  Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1461  SelfMask = _3ewa->ReadInt8() & 0x01;
1462  _3ewa->ReadInt8(); // unknown
1463  uint8_t lfo3ctrl = _3ewa->ReadUint8();
1464  LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1465  LFO3Sync = lfo3ctrl & 0x20; // bit 5
1466  InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1467  AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1468  uint8_t lfo2ctrl = _3ewa->ReadUint8();
1469  LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1470  LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1471  LFO2Sync = lfo2ctrl & 0x20; // bit 5
1472  bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1473  uint8_t lfo1ctrl = _3ewa->ReadUint8();
1474  LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1475  LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1476  LFO1Sync = lfo1ctrl & 0x40; // bit 6
1477  VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1479  uint16_t eg3depth = _3ewa->ReadUint16();
1480  EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1481  : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1482  _3ewa->ReadInt16(); // unknown
1483  ChannelOffset = _3ewa->ReadUint8() / 4;
1484  uint8_t regoptions = _3ewa->ReadUint8();
1485  MSDecode = regoptions & 0x01; // bit 0
1486  SustainDefeat = regoptions & 0x02; // bit 1
1487  _3ewa->ReadInt16(); // unknown
1488  VelocityUpperLimit = _3ewa->ReadInt8();
1489  _3ewa->ReadInt8(); // unknown
1490  _3ewa->ReadInt16(); // unknown
1491  ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1492  _3ewa->ReadInt8(); // unknown
1493  _3ewa->ReadInt8(); // unknown
1494  EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1495  uint8_t vcfcutoff = _3ewa->ReadUint8();
1496  VCFEnabled = vcfcutoff & 0x80; // bit 7
1497  VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1498  VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1499  uint8_t vcfvelscale = _3ewa->ReadUint8();
1500  VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1501  VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1502  _3ewa->ReadInt8(); // unknown
1503  uint8_t vcfresonance = _3ewa->ReadUint8();
1504  VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1505  VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1506  uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1507  VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1508  VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1509  uint8_t vcfvelocity = _3ewa->ReadUint8();
1510  VCFVelocityDynamicRange = vcfvelocity % 5;
1511  VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1512  VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1513  if (VCFType == vcf_type_lowpass) {
1514  if (lfo3ctrl & 0x40) // bit 6
1516  }
1517  if (_3ewa->RemainingBytes() >= 8) {
1518  _3ewa->Read(DimensionUpperLimits, 1, 8);
1519  } else {
1520  memset(DimensionUpperLimits, 0, 8);
1521  }
1522  } else { // '3ewa' chunk does not exist yet
1523  // use default values
1524  LFO3Frequency = 1.0;
1525  EG3Attack = 0.0;
1526  LFO1InternalDepth = 0;
1527  LFO3InternalDepth = 0;
1528  LFO1ControlDepth = 0;
1529  LFO3ControlDepth = 0;
1530  EG1Attack = 0.0;
1531  EG1Decay1 = 0.005;
1532  EG1Sustain = 1000;
1533  EG1Release = 0.3;
1536  EG1ControllerInvert = false;
1542  EG2ControllerInvert = false;
1546  LFO1Frequency = 1.0;
1547  EG2Attack = 0.0;
1548  EG2Decay1 = 0.005;
1549  EG2Sustain = 1000;
1550  EG2Release = 0.3;
1551  LFO2ControlDepth = 0;
1552  LFO2Frequency = 1.0;
1553  LFO2InternalDepth = 0;
1554  EG1Decay2 = 0.0;
1555  EG1InfiniteSustain = true;
1556  EG1PreAttack = 0;
1557  EG2Decay2 = 0.0;
1558  EG2InfiniteSustain = true;
1559  EG2PreAttack = 0;
1566  SampleStartOffset = 0;
1567  PitchTrack = true;
1569  Pan = 0;
1570  SelfMask = true;
1572  LFO3Sync = false;
1577  LFO2FlipPhase = false;
1578  LFO2Sync = false;
1580  LFO1FlipPhase = false;
1581  LFO1Sync = false;
1583  EG3Depth = 0;
1584  ChannelOffset = 0;
1585  MSDecode = false;
1586  SustainDefeat = false;
1587  VelocityUpperLimit = 0;
1588  ReleaseTriggerDecay = 0;
1589  EG1Hold = false;
1590  VCFEnabled = false;
1591  VCFCutoff = 0;
1593  VCFCutoffControllerInvert = false;
1594  VCFVelocityScale = 0;
1595  VCFResonance = 0;
1596  VCFResonanceDynamic = false;
1597  VCFKeyboardTracking = false;
1599  VCFVelocityDynamicRange = 0x04;
1602  memset(DimensionUpperLimits, 127, 8);
1603  }
1604 
1605  pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1608 
1609  pVelocityReleaseTable = GetReleaseVelocityTable(
1612  );
1613 
1614  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1618 
1619  SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1620  VelocityTable = 0;
1621  }
1622 
1623  /*
1624  * Constructs a DimensionRegion by copying all parameters from
1625  * another DimensionRegion
1626  */
1628  Instances++;
1629  //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1630  *this = src; // default memberwise shallow copy of all parameters
1631  pParentList = _3ewl; // restore the chunk pointer
1632 
1633  // deep copy of owned structures
1634  if (src.VelocityTable) {
1635  VelocityTable = new uint8_t[128];
1636  for (int k = 0 ; k < 128 ; k++)
1637  VelocityTable[k] = src.VelocityTable[k];
1638  }
1639  if (src.pSampleLoops) {
1641  for (int k = 0 ; k < src.SampleLoops ; k++)
1642  pSampleLoops[k] = src.pSampleLoops[k];
1643  }
1644  }
1645 
1656  CopyAssign(orig, NULL);
1657  }
1658 
1667  void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1668  // delete all allocated data first
1669  if (VelocityTable) delete [] VelocityTable;
1670  if (pSampleLoops) delete [] pSampleLoops;
1671 
1672  // backup parent list pointer
1673  RIFF::List* p = pParentList;
1674 
1675  gig::Sample* pOriginalSample = pSample;
1676  gig::Region* pOriginalRegion = pRegion;
1677 
1678  //NOTE: copy code copied from assignment constructor above, see comment there as well
1679 
1680  *this = *orig; // default memberwise shallow copy of all parameters
1681 
1682  // restore members that shall not be altered
1683  pParentList = p; // restore the chunk pointer
1684  pRegion = pOriginalRegion;
1685 
1686  // only take the raw sample reference reference if the
1687  // two DimensionRegion objects are part of the same file
1688  if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1689  pSample = pOriginalSample;
1690  }
1691 
1692  if (mSamples && mSamples->count(orig->pSample)) {
1693  pSample = mSamples->find(orig->pSample)->second;
1694  }
1695 
1696  // deep copy of owned structures
1697  if (orig->VelocityTable) {
1698  VelocityTable = new uint8_t[128];
1699  for (int k = 0 ; k < 128 ; k++)
1700  VelocityTable[k] = orig->VelocityTable[k];
1701  }
1702  if (orig->pSampleLoops) {
1704  for (int k = 0 ; k < orig->SampleLoops ; k++)
1705  pSampleLoops[k] = orig->pSampleLoops[k];
1706  }
1707  }
1708 
1713  void DimensionRegion::SetGain(int32_t gain) {
1714  DLS::Sampler::SetGain(gain);
1715  SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1716  }
1717 
1728  // first update base class's chunk
1729  DLS::Sampler::UpdateChunks(pProgress);
1730 
1732  uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1733  pData[12] = Crossfade.in_start;
1734  pData[13] = Crossfade.in_end;
1735  pData[14] = Crossfade.out_start;
1736  pData[15] = Crossfade.out_end;
1737 
1738  // make sure '3ewa' chunk exists
1740  if (!_3ewa) {
1741  File* pFile = (File*) GetParent()->GetParent()->GetParent();
1742  bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1743  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1744  }
1745  pData = (uint8_t*) _3ewa->LoadChunkData();
1746 
1747  // update '3ewa' chunk with DimensionRegion's current settings
1748 
1749  const uint32_t chunksize = _3ewa->GetNewSize();
1750  store32(&pData[0], chunksize); // unknown, always chunk size?
1751 
1752  const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1753  store32(&pData[4], lfo3freq);
1754 
1755  const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1756  store32(&pData[8], eg3attack);
1757 
1758  // next 2 bytes unknown
1759 
1760  store16(&pData[14], LFO1InternalDepth);
1761 
1762  // next 2 bytes unknown
1763 
1764  store16(&pData[18], LFO3InternalDepth);
1765 
1766  // next 2 bytes unknown
1767 
1768  store16(&pData[22], LFO1ControlDepth);
1769 
1770  // next 2 bytes unknown
1771 
1772  store16(&pData[26], LFO3ControlDepth);
1773 
1774  const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1775  store32(&pData[28], eg1attack);
1776 
1777  const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1778  store32(&pData[32], eg1decay1);
1779 
1780  // next 2 bytes unknown
1781 
1782  store16(&pData[38], EG1Sustain);
1783 
1784  const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1785  store32(&pData[40], eg1release);
1786 
1787  const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1788  pData[44] = eg1ctl;
1789 
1790  const uint8_t eg1ctrloptions =
1791  (EG1ControllerInvert ? 0x01 : 0x00) |
1795  pData[45] = eg1ctrloptions;
1796 
1797  const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1798  pData[46] = eg2ctl;
1799 
1800  const uint8_t eg2ctrloptions =
1801  (EG2ControllerInvert ? 0x01 : 0x00) |
1805  pData[47] = eg2ctrloptions;
1806 
1807  const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1808  store32(&pData[48], lfo1freq);
1809 
1810  const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1811  store32(&pData[52], eg2attack);
1812 
1813  const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1814  store32(&pData[56], eg2decay1);
1815 
1816  // next 2 bytes unknown
1817 
1818  store16(&pData[62], EG2Sustain);
1819 
1820  const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1821  store32(&pData[64], eg2release);
1822 
1823  // next 2 bytes unknown
1824 
1825  store16(&pData[70], LFO2ControlDepth);
1826 
1827  const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1828  store32(&pData[72], lfo2freq);
1829 
1830  // next 2 bytes unknown
1831 
1832  store16(&pData[78], LFO2InternalDepth);
1833 
1834  const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1835  store32(&pData[80], eg1decay2);
1836 
1837  // next 2 bytes unknown
1838 
1839  store16(&pData[86], EG1PreAttack);
1840 
1841  const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1842  store32(&pData[88], eg2decay2);
1843 
1844  // next 2 bytes unknown
1845 
1846  store16(&pData[94], EG2PreAttack);
1847 
1848  {
1849  if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1850  uint8_t velocityresponse = VelocityResponseDepth;
1851  switch (VelocityResponseCurve) {
1852  case curve_type_nonlinear:
1853  break;
1854  case curve_type_linear:
1855  velocityresponse += 5;
1856  break;
1857  case curve_type_special:
1858  velocityresponse += 10;
1859  break;
1860  case curve_type_unknown:
1861  default:
1862  throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1863  }
1864  pData[96] = velocityresponse;
1865  }
1866 
1867  {
1868  if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1869  uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1870  switch (ReleaseVelocityResponseCurve) {
1871  case curve_type_nonlinear:
1872  break;
1873  case curve_type_linear:
1874  releasevelocityresponse += 5;
1875  break;
1876  case curve_type_special:
1877  releasevelocityresponse += 10;
1878  break;
1879  case curve_type_unknown:
1880  default:
1881  throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1882  }
1883  pData[97] = releasevelocityresponse;
1884  }
1885 
1886  pData[98] = VelocityResponseCurveScaling;
1887 
1888  pData[99] = AttenuationControllerThreshold;
1889 
1890  // next 4 bytes unknown
1891 
1892  store16(&pData[104], SampleStartOffset);
1893 
1894  // next 2 bytes unknown
1895 
1896  {
1897  uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1898  switch (DimensionBypass) {
1899  case dim_bypass_ctrl_94:
1900  pitchTrackDimensionBypass |= 0x10;
1901  break;
1902  case dim_bypass_ctrl_95:
1903  pitchTrackDimensionBypass |= 0x20;
1904  break;
1905  case dim_bypass_ctrl_none:
1906  //FIXME: should we set anything here?
1907  break;
1908  default:
1909  throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1910  }
1911  pData[108] = pitchTrackDimensionBypass;
1912  }
1913 
1914  const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1915  pData[109] = pan;
1916 
1917  const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1918  pData[110] = selfmask;
1919 
1920  // next byte unknown
1921 
1922  {
1923  uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1924  if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1925  if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1926  if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1927  pData[112] = lfo3ctrl;
1928  }
1929 
1930  const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1931  pData[113] = attenctl;
1932 
1933  {
1934  uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1935  if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1936  if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1937  if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1938  pData[114] = lfo2ctrl;
1939  }
1940 
1941  {
1942  uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1943  if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1944  if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1947  pData[115] = lfo1ctrl;
1948  }
1949 
1950  const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1951  : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1952  store16(&pData[116], eg3depth);
1953 
1954  // next 2 bytes unknown
1955 
1956  const uint8_t channeloffset = ChannelOffset * 4;
1957  pData[120] = channeloffset;
1958 
1959  {
1960  uint8_t regoptions = 0;
1961  if (MSDecode) regoptions |= 0x01; // bit 0
1962  if (SustainDefeat) regoptions |= 0x02; // bit 1
1963  pData[121] = regoptions;
1964  }
1965 
1966  // next 2 bytes unknown
1967 
1968  pData[124] = VelocityUpperLimit;
1969 
1970  // next 3 bytes unknown
1971 
1972  pData[128] = ReleaseTriggerDecay;
1973 
1974  // next 2 bytes unknown
1975 
1976  const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1977  pData[131] = eg1hold;
1978 
1979  const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) | /* bit 7 */
1980  (VCFCutoff & 0x7f); /* lower 7 bits */
1981  pData[132] = vcfcutoff;
1982 
1983  pData[133] = VCFCutoffController;
1984 
1985  const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1986  (VCFVelocityScale & 0x7f); /* lower 7 bits */
1987  pData[134] = vcfvelscale;
1988 
1989  // next byte unknown
1990 
1991  const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1992  (VCFResonance & 0x7f); /* lower 7 bits */
1993  pData[136] = vcfresonance;
1994 
1995  const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1996  (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1997  pData[137] = vcfbreakpoint;
1998 
1999  const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2000  VCFVelocityCurve * 5;
2001  pData[138] = vcfvelocity;
2002 
2003  const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2004  pData[139] = vcftype;
2005 
2006  if (chunksize >= 148) {
2007  memcpy(&pData[140], DimensionUpperLimits, 8);
2008  }
2009  }
2010 
2011  double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2012  curve_type_t curveType = releaseVelocityResponseCurve;
2013  uint8_t depth = releaseVelocityResponseDepth;
2014  // this models a strange behaviour or bug in GSt: two of the
2015  // velocity response curves for release time are not used even
2016  // if specified, instead another curve is chosen.
2017  if ((curveType == curve_type_nonlinear && depth == 0) ||
2018  (curveType == curve_type_special && depth == 4)) {
2019  curveType = curve_type_nonlinear;
2020  depth = 3;
2021  }
2022  return GetVelocityTable(curveType, depth, 0);
2023  }
2024 
2025  double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2026  uint8_t vcfVelocityDynamicRange,
2027  uint8_t vcfVelocityScale,
2028  vcf_cutoff_ctrl_t vcfCutoffController)
2029  {
2030  curve_type_t curveType = vcfVelocityCurve;
2031  uint8_t depth = vcfVelocityDynamicRange;
2032  // even stranger GSt: two of the velocity response curves for
2033  // filter cutoff are not used, instead another special curve
2034  // is chosen. This curve is not used anywhere else.
2035  if ((curveType == curve_type_nonlinear && depth == 0) ||
2036  (curveType == curve_type_special && depth == 4)) {
2037  curveType = curve_type_special;
2038  depth = 5;
2039  }
2040  return GetVelocityTable(curveType, depth,
2041  (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2042  ? vcfVelocityScale : 0);
2043  }
2044 
2045  // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2046  double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2047  {
2048  // sanity check input parameters
2049  // (fallback to some default parameters on ill input)
2050  switch (curveType) {
2051  case curve_type_nonlinear:
2052  case curve_type_linear:
2053  if (depth > 4) {
2054  printf("Warning: Invalid depth (0x%x) for velocity curve type (0x%x).\n", depth, curveType);
2055  depth = 0;
2056  scaling = 0;
2057  }
2058  break;
2059  case curve_type_special:
2060  if (depth > 5) {
2061  printf("Warning: Invalid depth (0x%x) for velocity curve type 'special'.\n", depth);
2062  depth = 0;
2063  scaling = 0;
2064  }
2065  break;
2066  case curve_type_unknown:
2067  default:
2068  printf("Warning: Unknown velocity curve type (0x%x).\n", curveType);
2069  curveType = curve_type_linear;
2070  depth = 0;
2071  scaling = 0;
2072  break;
2073  }
2074 
2075  double* table;
2076  uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2077  if (pVelocityTables->count(tableKey)) { // if key exists
2078  table = (*pVelocityTables)[tableKey];
2079  }
2080  else {
2081  table = CreateVelocityTable(curveType, depth, scaling);
2082  (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2083  }
2084  return table;
2085  }
2086 
2088  return pRegion;
2089  }
2090 
2091 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2092 // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2093 // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2094 //#pragma GCC diagnostic push
2095 //#pragma GCC diagnostic error "-Wswitch"
2096 
2097  leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2098  leverage_ctrl_t decodedcontroller;
2099  switch (EncodedController) {
2100  // special controller
2101  case _lev_ctrl_none:
2102  decodedcontroller.type = leverage_ctrl_t::type_none;
2103  decodedcontroller.controller_number = 0;
2104  break;
2105  case _lev_ctrl_velocity:
2106  decodedcontroller.type = leverage_ctrl_t::type_velocity;
2107  decodedcontroller.controller_number = 0;
2108  break;
2109  case _lev_ctrl_channelaftertouch:
2110  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2111  decodedcontroller.controller_number = 0;
2112  break;
2113 
2114  // ordinary MIDI control change controller
2115  case _lev_ctrl_modwheel:
2116  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2117  decodedcontroller.controller_number = 1;
2118  break;
2119  case _lev_ctrl_breath:
2120  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2121  decodedcontroller.controller_number = 2;
2122  break;
2123  case _lev_ctrl_foot:
2124  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2125  decodedcontroller.controller_number = 4;
2126  break;
2127  case _lev_ctrl_effect1:
2128  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2129  decodedcontroller.controller_number = 12;
2130  break;
2131  case _lev_ctrl_effect2:
2132  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2133  decodedcontroller.controller_number = 13;
2134  break;
2135  case _lev_ctrl_genpurpose1:
2136  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2137  decodedcontroller.controller_number = 16;
2138  break;
2139  case _lev_ctrl_genpurpose2:
2140  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2141  decodedcontroller.controller_number = 17;
2142  break;
2143  case _lev_ctrl_genpurpose3:
2144  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2145  decodedcontroller.controller_number = 18;
2146  break;
2147  case _lev_ctrl_genpurpose4:
2148  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2149  decodedcontroller.controller_number = 19;
2150  break;
2151  case _lev_ctrl_portamentotime:
2152  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2153  decodedcontroller.controller_number = 5;
2154  break;
2155  case _lev_ctrl_sustainpedal:
2156  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2157  decodedcontroller.controller_number = 64;
2158  break;
2159  case _lev_ctrl_portamento:
2160  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2161  decodedcontroller.controller_number = 65;
2162  break;
2163  case _lev_ctrl_sostenutopedal:
2164  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2165  decodedcontroller.controller_number = 66;
2166  break;
2167  case _lev_ctrl_softpedal:
2168  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2169  decodedcontroller.controller_number = 67;
2170  break;
2171  case _lev_ctrl_genpurpose5:
2172  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2173  decodedcontroller.controller_number = 80;
2174  break;
2175  case _lev_ctrl_genpurpose6:
2176  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2177  decodedcontroller.controller_number = 81;
2178  break;
2179  case _lev_ctrl_genpurpose7:
2180  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2181  decodedcontroller.controller_number = 82;
2182  break;
2183  case _lev_ctrl_genpurpose8:
2184  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2185  decodedcontroller.controller_number = 83;
2186  break;
2187  case _lev_ctrl_effect1depth:
2188  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2189  decodedcontroller.controller_number = 91;
2190  break;
2191  case _lev_ctrl_effect2depth:
2192  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2193  decodedcontroller.controller_number = 92;
2194  break;
2195  case _lev_ctrl_effect3depth:
2196  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2197  decodedcontroller.controller_number = 93;
2198  break;
2199  case _lev_ctrl_effect4depth:
2200  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2201  decodedcontroller.controller_number = 94;
2202  break;
2203  case _lev_ctrl_effect5depth:
2204  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2205  decodedcontroller.controller_number = 95;
2206  break;
2207 
2208  // format extension (these controllers are so far only supported by
2209  // LinuxSampler & gigedit) they will *NOT* work with
2210  // Gigasampler/GigaStudio !
2211  case _lev_ctrl_CC3_EXT:
2212  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2213  decodedcontroller.controller_number = 3;
2214  break;
2215  case _lev_ctrl_CC6_EXT:
2216  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2217  decodedcontroller.controller_number = 6;
2218  break;
2219  case _lev_ctrl_CC7_EXT:
2220  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2221  decodedcontroller.controller_number = 7;
2222  break;
2223  case _lev_ctrl_CC8_EXT:
2224  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2225  decodedcontroller.controller_number = 8;
2226  break;
2227  case _lev_ctrl_CC9_EXT:
2228  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2229  decodedcontroller.controller_number = 9;
2230  break;
2231  case _lev_ctrl_CC10_EXT:
2232  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2233  decodedcontroller.controller_number = 10;
2234  break;
2235  case _lev_ctrl_CC11_EXT:
2236  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2237  decodedcontroller.controller_number = 11;
2238  break;
2239  case _lev_ctrl_CC14_EXT:
2240  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2241  decodedcontroller.controller_number = 14;
2242  break;
2243  case _lev_ctrl_CC15_EXT:
2244  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2245  decodedcontroller.controller_number = 15;
2246  break;
2247  case _lev_ctrl_CC20_EXT:
2248  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2249  decodedcontroller.controller_number = 20;
2250  break;
2251  case _lev_ctrl_CC21_EXT:
2252  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2253  decodedcontroller.controller_number = 21;
2254  break;
2255  case _lev_ctrl_CC22_EXT:
2256  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2257  decodedcontroller.controller_number = 22;
2258  break;
2259  case _lev_ctrl_CC23_EXT:
2260  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2261  decodedcontroller.controller_number = 23;
2262  break;
2263  case _lev_ctrl_CC24_EXT:
2264  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2265  decodedcontroller.controller_number = 24;
2266  break;
2267  case _lev_ctrl_CC25_EXT:
2268  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2269  decodedcontroller.controller_number = 25;
2270  break;
2271  case _lev_ctrl_CC26_EXT:
2272  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2273  decodedcontroller.controller_number = 26;
2274  break;
2275  case _lev_ctrl_CC27_EXT:
2276  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2277  decodedcontroller.controller_number = 27;
2278  break;
2279  case _lev_ctrl_CC28_EXT:
2280  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2281  decodedcontroller.controller_number = 28;
2282  break;
2283  case _lev_ctrl_CC29_EXT:
2284  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2285  decodedcontroller.controller_number = 29;
2286  break;
2287  case _lev_ctrl_CC30_EXT:
2288  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2289  decodedcontroller.controller_number = 30;
2290  break;
2291  case _lev_ctrl_CC31_EXT:
2292  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2293  decodedcontroller.controller_number = 31;
2294  break;
2295  case _lev_ctrl_CC68_EXT:
2296  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2297  decodedcontroller.controller_number = 68;
2298  break;
2299  case _lev_ctrl_CC69_EXT:
2300  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2301  decodedcontroller.controller_number = 69;
2302  break;
2303  case _lev_ctrl_CC70_EXT:
2304  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2305  decodedcontroller.controller_number = 70;
2306  break;
2307  case _lev_ctrl_CC71_EXT:
2308  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2309  decodedcontroller.controller_number = 71;
2310  break;
2311  case _lev_ctrl_CC72_EXT:
2312  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2313  decodedcontroller.controller_number = 72;
2314  break;
2315  case _lev_ctrl_CC73_EXT:
2316  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2317  decodedcontroller.controller_number = 73;
2318  break;
2319  case _lev_ctrl_CC74_EXT:
2320  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2321  decodedcontroller.controller_number = 74;
2322  break;
2323  case _lev_ctrl_CC75_EXT:
2324  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2325  decodedcontroller.controller_number = 75;
2326  break;
2327  case _lev_ctrl_CC76_EXT:
2328  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2329  decodedcontroller.controller_number = 76;
2330  break;
2331  case _lev_ctrl_CC77_EXT:
2332  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2333  decodedcontroller.controller_number = 77;
2334  break;
2335  case _lev_ctrl_CC78_EXT:
2336  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2337  decodedcontroller.controller_number = 78;
2338  break;
2339  case _lev_ctrl_CC79_EXT:
2340  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2341  decodedcontroller.controller_number = 79;
2342  break;
2343  case _lev_ctrl_CC84_EXT:
2344  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2345  decodedcontroller.controller_number = 84;
2346  break;
2347  case _lev_ctrl_CC85_EXT:
2348  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2349  decodedcontroller.controller_number = 85;
2350  break;
2351  case _lev_ctrl_CC86_EXT:
2352  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2353  decodedcontroller.controller_number = 86;
2354  break;
2355  case _lev_ctrl_CC87_EXT:
2356  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2357  decodedcontroller.controller_number = 87;
2358  break;
2359  case _lev_ctrl_CC89_EXT:
2360  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2361  decodedcontroller.controller_number = 89;
2362  break;
2363  case _lev_ctrl_CC90_EXT:
2364  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2365  decodedcontroller.controller_number = 90;
2366  break;
2367  case _lev_ctrl_CC96_EXT:
2368  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2369  decodedcontroller.controller_number = 96;
2370  break;
2371  case _lev_ctrl_CC97_EXT:
2372  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2373  decodedcontroller.controller_number = 97;
2374  break;
2375  case _lev_ctrl_CC102_EXT:
2376  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2377  decodedcontroller.controller_number = 102;
2378  break;
2379  case _lev_ctrl_CC103_EXT:
2380  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2381  decodedcontroller.controller_number = 103;
2382  break;
2383  case _lev_ctrl_CC104_EXT:
2384  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2385  decodedcontroller.controller_number = 104;
2386  break;
2387  case _lev_ctrl_CC105_EXT:
2388  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2389  decodedcontroller.controller_number = 105;
2390  break;
2391  case _lev_ctrl_CC106_EXT:
2392  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2393  decodedcontroller.controller_number = 106;
2394  break;
2395  case _lev_ctrl_CC107_EXT:
2396  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2397  decodedcontroller.controller_number = 107;
2398  break;
2399  case _lev_ctrl_CC108_EXT:
2400  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2401  decodedcontroller.controller_number = 108;
2402  break;
2403  case _lev_ctrl_CC109_EXT:
2404  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2405  decodedcontroller.controller_number = 109;
2406  break;
2407  case _lev_ctrl_CC110_EXT:
2408  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2409  decodedcontroller.controller_number = 110;
2410  break;
2411  case _lev_ctrl_CC111_EXT:
2412  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2413  decodedcontroller.controller_number = 111;
2414  break;
2415  case _lev_ctrl_CC112_EXT:
2416  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2417  decodedcontroller.controller_number = 112;
2418  break;
2419  case _lev_ctrl_CC113_EXT:
2420  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2421  decodedcontroller.controller_number = 113;
2422  break;
2423  case _lev_ctrl_CC114_EXT:
2424  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2425  decodedcontroller.controller_number = 114;
2426  break;
2427  case _lev_ctrl_CC115_EXT:
2428  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2429  decodedcontroller.controller_number = 115;
2430  break;
2431  case _lev_ctrl_CC116_EXT:
2432  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2433  decodedcontroller.controller_number = 116;
2434  break;
2435  case _lev_ctrl_CC117_EXT:
2436  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2437  decodedcontroller.controller_number = 117;
2438  break;
2439  case _lev_ctrl_CC118_EXT:
2440  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441  decodedcontroller.controller_number = 118;
2442  break;
2443  case _lev_ctrl_CC119_EXT:
2444  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445  decodedcontroller.controller_number = 119;
2446  break;
2447 
2448  // unknown controller type
2449  default:
2450  throw gig::Exception("Unknown leverage controller type.");
2451  }
2452  return decodedcontroller;
2453  }
2454 
2455 // see above (diagnostic push not supported prior GCC 4.6)
2456 //#pragma GCC diagnostic pop
2457 
2458  DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2459  _lev_ctrl_t encodedcontroller;
2460  switch (DecodedController.type) {
2461  // special controller
2463  encodedcontroller = _lev_ctrl_none;
2464  break;
2466  encodedcontroller = _lev_ctrl_velocity;
2467  break;
2469  encodedcontroller = _lev_ctrl_channelaftertouch;
2470  break;
2471 
2472  // ordinary MIDI control change controller
2474  switch (DecodedController.controller_number) {
2475  case 1:
2476  encodedcontroller = _lev_ctrl_modwheel;
2477  break;
2478  case 2:
2479  encodedcontroller = _lev_ctrl_breath;
2480  break;
2481  case 4:
2482  encodedcontroller = _lev_ctrl_foot;
2483  break;
2484  case 12:
2485  encodedcontroller = _lev_ctrl_effect1;
2486  break;
2487  case 13:
2488  encodedcontroller = _lev_ctrl_effect2;
2489  break;
2490  case 16:
2491  encodedcontroller = _lev_ctrl_genpurpose1;
2492  break;
2493  case 17:
2494  encodedcontroller = _lev_ctrl_genpurpose2;
2495  break;
2496  case 18:
2497  encodedcontroller = _lev_ctrl_genpurpose3;
2498  break;
2499  case 19:
2500  encodedcontroller = _lev_ctrl_genpurpose4;
2501  break;
2502  case 5:
2503  encodedcontroller = _lev_ctrl_portamentotime;
2504  break;
2505  case 64:
2506  encodedcontroller = _lev_ctrl_sustainpedal;
2507  break;
2508  case 65:
2509  encodedcontroller = _lev_ctrl_portamento;
2510  break;
2511  case 66:
2512  encodedcontroller = _lev_ctrl_sostenutopedal;
2513  break;
2514  case 67:
2515  encodedcontroller = _lev_ctrl_softpedal;
2516  break;
2517  case 80:
2518  encodedcontroller = _lev_ctrl_genpurpose5;
2519  break;
2520  case 81:
2521  encodedcontroller = _lev_ctrl_genpurpose6;
2522  break;
2523  case 82:
2524  encodedcontroller = _lev_ctrl_genpurpose7;
2525  break;
2526  case 83:
2527  encodedcontroller = _lev_ctrl_genpurpose8;
2528  break;
2529  case 91:
2530  encodedcontroller = _lev_ctrl_effect1depth;
2531  break;
2532  case 92:
2533  encodedcontroller = _lev_ctrl_effect2depth;
2534  break;
2535  case 93:
2536  encodedcontroller = _lev_ctrl_effect3depth;
2537  break;
2538  case 94:
2539  encodedcontroller = _lev_ctrl_effect4depth;
2540  break;
2541  case 95:
2542  encodedcontroller = _lev_ctrl_effect5depth;
2543  break;
2544 
2545  // format extension (these controllers are so far only
2546  // supported by LinuxSampler & gigedit) they will *NOT*
2547  // work with Gigasampler/GigaStudio !
2548  case 3:
2549  encodedcontroller = _lev_ctrl_CC3_EXT;
2550  break;
2551  case 6:
2552  encodedcontroller = _lev_ctrl_CC6_EXT;
2553  break;
2554  case 7:
2555  encodedcontroller = _lev_ctrl_CC7_EXT;
2556  break;
2557  case 8:
2558  encodedcontroller = _lev_ctrl_CC8_EXT;
2559  break;
2560  case 9:
2561  encodedcontroller = _lev_ctrl_CC9_EXT;
2562  break;
2563  case 10:
2564  encodedcontroller = _lev_ctrl_CC10_EXT;
2565  break;
2566  case 11:
2567  encodedcontroller = _lev_ctrl_CC11_EXT;
2568  break;
2569  case 14:
2570  encodedcontroller = _lev_ctrl_CC14_EXT;
2571  break;
2572  case 15:
2573  encodedcontroller = _lev_ctrl_CC15_EXT;
2574  break;
2575  case 20:
2576  encodedcontroller = _lev_ctrl_CC20_EXT;
2577  break;
2578  case 21:
2579  encodedcontroller = _lev_ctrl_CC21_EXT;
2580  break;
2581  case 22:
2582  encodedcontroller = _lev_ctrl_CC22_EXT;
2583  break;
2584  case 23:
2585  encodedcontroller = _lev_ctrl_CC23_EXT;
2586  break;
2587  case 24:
2588  encodedcontroller = _lev_ctrl_CC24_EXT;
2589  break;
2590  case 25:
2591  encodedcontroller = _lev_ctrl_CC25_EXT;
2592  break;
2593  case 26:
2594  encodedcontroller = _lev_ctrl_CC26_EXT;
2595  break;
2596  case 27:
2597  encodedcontroller = _lev_ctrl_CC27_EXT;
2598  break;
2599  case 28:
2600  encodedcontroller = _lev_ctrl_CC28_EXT;
2601  break;
2602  case 29:
2603  encodedcontroller = _lev_ctrl_CC29_EXT;
2604  break;
2605  case 30:
2606  encodedcontroller = _lev_ctrl_CC30_EXT;
2607  break;
2608  case 31:
2609  encodedcontroller = _lev_ctrl_CC31_EXT;
2610  break;
2611  case 68:
2612  encodedcontroller = _lev_ctrl_CC68_EXT;
2613  break;
2614  case 69:
2615  encodedcontroller = _lev_ctrl_CC69_EXT;
2616  break;
2617  case 70:
2618  encodedcontroller = _lev_ctrl_CC70_EXT;
2619  break;
2620  case 71:
2621  encodedcontroller = _lev_ctrl_CC71_EXT;
2622  break;
2623  case 72:
2624  encodedcontroller = _lev_ctrl_CC72_EXT;
2625  break;
2626  case 73:
2627  encodedcontroller = _lev_ctrl_CC73_EXT;
2628  break;
2629  case 74:
2630  encodedcontroller = _lev_ctrl_CC74_EXT;
2631  break;
2632  case 75:
2633  encodedcontroller = _lev_ctrl_CC75_EXT;
2634  break;
2635  case 76:
2636  encodedcontroller = _lev_ctrl_CC76_EXT;
2637  break;
2638  case 77:
2639  encodedcontroller = _lev_ctrl_CC77_EXT;
2640  break;
2641  case 78:
2642  encodedcontroller = _lev_ctrl_CC78_EXT;
2643  break;
2644  case 79:
2645  encodedcontroller = _lev_ctrl_CC79_EXT;
2646  break;
2647  case 84:
2648  encodedcontroller = _lev_ctrl_CC84_EXT;
2649  break;
2650  case 85:
2651  encodedcontroller = _lev_ctrl_CC85_EXT;
2652  break;
2653  case 86:
2654  encodedcontroller = _lev_ctrl_CC86_EXT;
2655  break;
2656  case 87:
2657  encodedcontroller = _lev_ctrl_CC87_EXT;
2658  break;
2659  case 89:
2660  encodedcontroller = _lev_ctrl_CC89_EXT;
2661  break;
2662  case 90:
2663  encodedcontroller = _lev_ctrl_CC90_EXT;
2664  break;
2665  case 96:
2666  encodedcontroller = _lev_ctrl_CC96_EXT;
2667  break;
2668  case 97:
2669  encodedcontroller = _lev_ctrl_CC97_EXT;
2670  break;
2671  case 102:
2672  encodedcontroller = _lev_ctrl_CC102_EXT;
2673  break;
2674  case 103:
2675  encodedcontroller = _lev_ctrl_CC103_EXT;
2676  break;
2677  case 104:
2678  encodedcontroller = _lev_ctrl_CC104_EXT;
2679  break;
2680  case 105:
2681  encodedcontroller = _lev_ctrl_CC105_EXT;
2682  break;
2683  case 106:
2684  encodedcontroller = _lev_ctrl_CC106_EXT;
2685  break;
2686  case 107:
2687  encodedcontroller = _lev_ctrl_CC107_EXT;
2688  break;
2689  case 108:
2690  encodedcontroller = _lev_ctrl_CC108_EXT;
2691  break;
2692  case 109:
2693  encodedcontroller = _lev_ctrl_CC109_EXT;
2694  break;
2695  case 110:
2696  encodedcontroller = _lev_ctrl_CC110_EXT;
2697  break;
2698  case 111:
2699  encodedcontroller = _lev_ctrl_CC111_EXT;
2700  break;
2701  case 112:
2702  encodedcontroller = _lev_ctrl_CC112_EXT;
2703  break;
2704  case 113:
2705  encodedcontroller = _lev_ctrl_CC113_EXT;
2706  break;
2707  case 114:
2708  encodedcontroller = _lev_ctrl_CC114_EXT;
2709  break;
2710  case 115:
2711  encodedcontroller = _lev_ctrl_CC115_EXT;
2712  break;
2713  case 116:
2714  encodedcontroller = _lev_ctrl_CC116_EXT;
2715  break;
2716  case 117:
2717  encodedcontroller = _lev_ctrl_CC117_EXT;
2718  break;
2719  case 118:
2720  encodedcontroller = _lev_ctrl_CC118_EXT;
2721  break;
2722  case 119:
2723  encodedcontroller = _lev_ctrl_CC119_EXT;
2724  break;
2725 
2726  default:
2727  throw gig::Exception("leverage controller number is not supported by the gig format");
2728  }
2729  break;
2730  default:
2731  throw gig::Exception("Unknown leverage controller type.");
2732  }
2733  return encodedcontroller;
2734  }
2735 
2737  Instances--;
2738  if (!Instances) {
2739  // delete the velocity->volume tables
2740  VelocityTableMap::iterator iter;
2741  for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2742  double* pTable = iter->second;
2743  if (pTable) delete[] pTable;
2744  }
2745  pVelocityTables->clear();
2746  delete pVelocityTables;
2747  pVelocityTables = NULL;
2748  }
2749  if (VelocityTable) delete[] VelocityTable;
2750  }
2751 
2763  double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2764  return pVelocityAttenuationTable[MIDIKeyVelocity];
2765  }
2766 
2767  double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2768  return pVelocityReleaseTable[MIDIKeyVelocity];
2769  }
2770 
2771  double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2772  return pVelocityCutoffTable[MIDIKeyVelocity];
2773  }
2774 
2780  pVelocityAttenuationTable =
2781  GetVelocityTable(
2783  );
2784  VelocityResponseCurve = curve;
2785  }
2786 
2792  pVelocityAttenuationTable =
2793  GetVelocityTable(
2795  );
2796  VelocityResponseDepth = depth;
2797  }
2798 
2804  pVelocityAttenuationTable =
2805  GetVelocityTable(
2807  );
2808  VelocityResponseCurveScaling = scaling;
2809  }
2810 
2816  pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2818  }
2819 
2825  pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2827  }
2828 
2834  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2835  VCFCutoffController = controller;
2836  }
2837 
2843  pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2844  VCFVelocityCurve = curve;
2845  }
2846 
2852  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2853  VCFVelocityDynamicRange = range;
2854  }
2855 
2861  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2862  VCFVelocityScale = scaling;
2863  }
2864 
2865  double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2866 
2867  // line-segment approximations of the 15 velocity curves
2868 
2869  // linear
2870  const int lin0[] = { 1, 1, 127, 127 };
2871  const int lin1[] = { 1, 21, 127, 127 };
2872  const int lin2[] = { 1, 45, 127, 127 };
2873  const int lin3[] = { 1, 74, 127, 127 };
2874  const int lin4[] = { 1, 127, 127, 127 };
2875 
2876  // non-linear
2877  const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2878  const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2879  127, 127 };
2880  const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2881  127, 127 };
2882  const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2883  127, 127 };
2884  const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2885 
2886  // special
2887  const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2888  113, 127, 127, 127 };
2889  const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2890  118, 127, 127, 127 };
2891  const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2892  85, 90, 91, 127, 127, 127 };
2893  const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2894  117, 127, 127, 127 };
2895  const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2896  127, 127 };
2897 
2898  // this is only used by the VCF velocity curve
2899  const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2900  91, 127, 127, 127 };
2901 
2902  const int* const curves[] = { non0, non1, non2, non3, non4,
2903  lin0, lin1, lin2, lin3, lin4,
2904  spe0, spe1, spe2, spe3, spe4, spe5 };
2905 
2906  double* const table = new double[128];
2907 
2908  const int* curve = curves[curveType * 5 + depth];
2909  const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2910 
2911  table[0] = 0;
2912  for (int x = 1 ; x < 128 ; x++) {
2913 
2914  if (x > curve[2]) curve += 2;
2915  double y = curve[1] + (x - curve[0]) *
2916  (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2917  y = y / 127;
2918 
2919  // Scale up for s > 20, down for s < 20. When
2920  // down-scaling, the curve still ends at 1.0.
2921  if (s < 20 && y >= 0.5)
2922  y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2923  else
2924  y = y * (s / 20.0);
2925  if (y > 1) y = 1;
2926 
2927  table[x] = y;
2928  }
2929  return table;
2930  }
2931 
2932 
2933 // *************** Region ***************
2934 // *
2935 
2936  Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2937  // Initialization
2938  Dimensions = 0;
2939  for (int i = 0; i < 256; i++) {
2940  pDimensionRegions[i] = NULL;
2941  }
2942  Layers = 1;
2943  File* file = (File*) GetParent()->GetParent();
2944  int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2945 
2946  // Actual Loading
2947 
2948  if (!file->GetAutoLoad()) return;
2949 
2950  LoadDimensionRegions(rgnList);
2951 
2952  RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2953  if (_3lnk) {
2954  DimensionRegions = _3lnk->ReadUint32();
2955  for (int i = 0; i < dimensionBits; i++) {
2956  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2957  uint8_t bits = _3lnk->ReadUint8();
2958  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2959  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2960  uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2961  if (dimension == dimension_none) { // inactive dimension
2963  pDimensionDefinitions[i].bits = 0;
2967  }
2968  else { // active dimension
2969  pDimensionDefinitions[i].dimension = dimension;
2970  pDimensionDefinitions[i].bits = bits;
2971  pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2972  pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2973  pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
2974  Dimensions++;
2975 
2976  // if this is a layer dimension, remember the amount of layers
2977  if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2978  }
2979  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2980  }
2981  for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2982 
2983  // if there's a velocity dimension and custom velocity zone splits are used,
2984  // update the VelocityTables in the dimension regions
2986 
2987  // jump to start of the wave pool indices (if not already there)
2988  if (file->pVersion && file->pVersion->major == 3)
2989  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2990  else
2991  _3lnk->SetPos(44);
2992 
2993  // load sample references (if auto loading is enabled)
2994  if (file->GetAutoLoad()) {
2995  for (uint i = 0; i < DimensionRegions; i++) {
2996  uint32_t wavepoolindex = _3lnk->ReadUint32();
2997  if (file->pWavePoolTable && pDimensionRegions[i]) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2998  }
2999  GetSample(); // load global region sample reference
3000  }
3001  } else {
3002  DimensionRegions = 0;
3003  for (int i = 0 ; i < 8 ; i++) {
3005  pDimensionDefinitions[i].bits = 0;
3007  }
3008  }
3009 
3010  // make sure there is at least one dimension region
3011  if (!DimensionRegions) {
3012  RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3013  if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3014  RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3015  pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3016  DimensionRegions = 1;
3017  }
3018  }
3019 
3031  // in the gig format we don't care about the Region's sample reference
3032  // but we still have to provide some existing one to not corrupt the
3033  // file, so to avoid the latter we simply always assign the sample of
3034  // the first dimension region of this region
3036 
3037  // first update base class's chunks
3038  DLS::Region::UpdateChunks(pProgress);
3039 
3040  // update dimension region's chunks
3041  for (int i = 0; i < DimensionRegions; i++) {
3042  pDimensionRegions[i]->UpdateChunks(pProgress);
3043  }
3044 
3045  File* pFile = (File*) GetParent()->GetParent();
3046  bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3047  const int iMaxDimensions = version3 ? 8 : 5;
3048  const int iMaxDimensionRegions = version3 ? 256 : 32;
3049 
3050  // make sure '3lnk' chunk exists
3052  if (!_3lnk) {
3053  const int _3lnkChunkSize = version3 ? 1092 : 172;
3054  _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3055  memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3056 
3057  // move 3prg to last position
3059  }
3060 
3061  // update dimension definitions in '3lnk' chunk
3062  uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3063  store32(&pData[0], DimensionRegions);
3064  int shift = 0;
3065  for (int i = 0; i < iMaxDimensions; i++) {
3066  pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3067  pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3068  pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3069  pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3070  pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3071  // next 3 bytes unknown, always zero?
3072 
3073  shift += pDimensionDefinitions[i].bits;
3074  }
3075 
3076  // update wave pool table in '3lnk' chunk
3077  const int iWavePoolOffset = version3 ? 68 : 44;
3078  for (uint i = 0; i < iMaxDimensionRegions; i++) {
3079  int iWaveIndex = -1;
3080  if (i < DimensionRegions) {
3081  if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3082  File::SampleList::iterator iter = pFile->pSamples->begin();
3083  File::SampleList::iterator end = pFile->pSamples->end();
3084  for (int index = 0; iter != end; ++iter, ++index) {
3085  if (*iter == pDimensionRegions[i]->pSample) {
3086  iWaveIndex = index;
3087  break;
3088  }
3089  }
3090  }
3091  store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3092  }
3093  }
3094 
3096  RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3097  if (_3prg) {
3098  int dimensionRegionNr = 0;
3099  RIFF::List* _3ewl = _3prg->GetFirstSubList();
3100  while (_3ewl) {
3101  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3102  pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3103  dimensionRegionNr++;
3104  }
3105  _3ewl = _3prg->GetNextSubList();
3106  }
3107  if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3108  }
3109  }
3110 
3111  void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3112  // update KeyRange struct and make sure regions are in correct order
3113  DLS::Region::SetKeyRange(Low, High);
3114  // update Region key table for fast lookup
3115  ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3116  }
3117 
3119  // get velocity dimension's index
3120  int veldim = -1;
3121  for (int i = 0 ; i < Dimensions ; i++) {
3122  if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3123  veldim = i;
3124  break;
3125  }
3126  }
3127  if (veldim == -1) return;
3128 
3129  int step = 1;
3130  for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3131  int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3132  int end = step * pDimensionDefinitions[veldim].zones;
3133 
3134  // loop through all dimension regions for all dimensions except the velocity dimension
3135  int dim[8] = { 0 };
3136  for (int i = 0 ; i < DimensionRegions ; i++) {
3137 
3138  if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3139  pDimensionRegions[i]->VelocityUpperLimit) {
3140  // create the velocity table
3141  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3142  if (!table) {
3143  table = new uint8_t[128];
3144  pDimensionRegions[i]->VelocityTable = table;
3145  }
3146  int tableidx = 0;
3147  int velocityZone = 0;
3148  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3149  for (int k = i ; k < end ; k += step) {
3151  for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3152  velocityZone++;
3153  }
3154  } else { // gig2
3155  for (int k = i ; k < end ; k += step) {
3157  for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3158  velocityZone++;
3159  }
3160  }
3161  } else {
3162  if (pDimensionRegions[i]->VelocityTable) {
3163  delete[] pDimensionRegions[i]->VelocityTable;
3165  }
3166  }
3167 
3168  int j;
3169  int shift = 0;
3170  for (j = 0 ; j < Dimensions ; j++) {
3171  if (j == veldim) i += skipveldim; // skip velocity dimension
3172  else {
3173  dim[j]++;
3174  if (dim[j] < pDimensionDefinitions[j].zones) break;
3175  else {
3176  // skip unused dimension regions
3177  dim[j] = 0;
3178  i += ((1 << pDimensionDefinitions[j].bits) -
3179  pDimensionDefinitions[j].zones) << shift;
3180  }
3181  }
3182  shift += pDimensionDefinitions[j].bits;
3183  }
3184  if (j == Dimensions) break;
3185  }
3186  }
3187 
3204  // some initial sanity checks of the given dimension definition
3205  if (pDimDef->zones < 2)
3206  throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3207  if (pDimDef->bits < 1)
3208  throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3209  if (pDimDef->dimension == dimension_samplechannel) {
3210  if (pDimDef->zones != 2)
3211  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3212  if (pDimDef->bits != 1)
3213  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3214  }
3215 
3216  // check if max. amount of dimensions reached
3217  File* file = (File*) GetParent()->GetParent();
3218  const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3219  if (Dimensions >= iMaxDimensions)
3220  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3221  // check if max. amount of dimension bits reached
3222  int iCurrentBits = 0;
3223  for (int i = 0; i < Dimensions; i++)
3224  iCurrentBits += pDimensionDefinitions[i].bits;
3225  if (iCurrentBits >= iMaxDimensions)
3226  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3227  const int iNewBits = iCurrentBits + pDimDef->bits;
3228  if (iNewBits > iMaxDimensions)
3229  throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3230  // check if there's already a dimensions of the same type
3231  for (int i = 0; i < Dimensions; i++)
3232  if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3233  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3234 
3235  // pos is where the new dimension should be placed, normally
3236  // last in list, except for the samplechannel dimension which
3237  // has to be first in list
3238  int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3239  int bitpos = 0;
3240  for (int i = 0 ; i < pos ; i++)
3241  bitpos += pDimensionDefinitions[i].bits;
3242 
3243  // make room for the new dimension
3244  for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3245  for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3246  for (int j = Dimensions ; j > pos ; j--) {
3249  }
3250  }
3251 
3252  // assign definition of new dimension
3253  pDimensionDefinitions[pos] = *pDimDef;
3254 
3255  // auto correct certain dimension definition fields (where possible)
3257  __resolveSplitType(pDimensionDefinitions[pos].dimension);
3259  __resolveZoneSize(pDimensionDefinitions[pos]);
3260 
3261  // create new dimension region(s) for this new dimension, and make
3262  // sure that the dimension regions are placed correctly in both the
3263  // RIFF list and the pDimensionRegions array
3264  RIFF::Chunk* moveTo = NULL;
3266  for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3267  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3268  pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3269  }
3270  for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3271  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3272  RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3273  if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3274  // create a new dimension region and copy all parameter values from
3275  // an existing dimension region
3276  pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3277  new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3278 
3279  DimensionRegions++;
3280  }
3281  }
3282  moveTo = pDimensionRegions[i]->pParentList;
3283  }
3284 
3285  // initialize the upper limits for this dimension
3286  int mask = (1 << bitpos) - 1;
3287  for (int z = 0 ; z < pDimDef->zones ; z++) {
3288  uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3289  for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3290  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3291  (z << bitpos) |
3292  (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3293  }
3294  }
3295 
3296  Dimensions++;
3297 
3298  // if this is a layer dimension, update 'Layers' attribute
3299  if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3300 
3302  }
3303 
3316  // get dimension's index
3317  int iDimensionNr = -1;
3318  for (int i = 0; i < Dimensions; i++) {
3319  if (&pDimensionDefinitions[i] == pDimDef) {
3320  iDimensionNr = i;
3321  break;
3322  }
3323  }
3324  if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3325 
3326  // get amount of bits below the dimension to delete
3327  int iLowerBits = 0;
3328  for (int i = 0; i < iDimensionNr; i++)
3329  iLowerBits += pDimensionDefinitions[i].bits;
3330 
3331  // get amount ot bits above the dimension to delete
3332  int iUpperBits = 0;
3333  for (int i = iDimensionNr + 1; i < Dimensions; i++)
3334  iUpperBits += pDimensionDefinitions[i].bits;
3335 
3337 
3338  // delete dimension regions which belong to the given dimension
3339  // (that is where the dimension's bit > 0)
3340  for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3341  for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3342  for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3343  int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3344  iObsoleteBit << iLowerBits |
3345  iLowerBit;
3346 
3347  _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3348  delete pDimensionRegions[iToDelete];
3349  pDimensionRegions[iToDelete] = NULL;
3350  DimensionRegions--;
3351  }
3352  }
3353  }
3354 
3355  // defrag pDimensionRegions array
3356  // (that is remove the NULL spaces within the pDimensionRegions array)
3357  for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3358  if (!pDimensionRegions[iTo]) {
3359  if (iFrom <= iTo) iFrom = iTo + 1;
3360  while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3361  if (iFrom < 256 && pDimensionRegions[iFrom]) {
3362  pDimensionRegions[iTo] = pDimensionRegions[iFrom];
3363  pDimensionRegions[iFrom] = NULL;
3364  }
3365  }
3366  }
3367 
3368  // remove the this dimension from the upper limits arrays
3369  for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3370  DimensionRegion* d = pDimensionRegions[j];
3371  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3372  d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3373  }
3374  d->DimensionUpperLimits[Dimensions - 1] = 127;
3375  }
3376 
3377  // 'remove' dimension definition
3378  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3380  }
3382  pDimensionDefinitions[Dimensions - 1].bits = 0;
3383  pDimensionDefinitions[Dimensions - 1].zones = 0;
3384 
3385  Dimensions--;
3386 
3387  // if this was a layer dimension, update 'Layers' attribute
3388  if (pDimDef->dimension == dimension_layer) Layers = 1;
3389  }
3390 
3406  dimension_def_t* oldDef = GetDimensionDefinition(type);
3407  if (!oldDef)
3408  throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3409  if (oldDef->zones <= 2)
3410  throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3411  if (zone < 0 || zone >= oldDef->zones)
3412  throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3413 
3414  const int newZoneSize = oldDef->zones - 1;
3415 
3416  // create a temporary Region which just acts as a temporary copy
3417  // container and will be deleted at the end of this function and will
3418  // also not be visible through the API during this process
3419  gig::Region* tempRgn = NULL;
3420  {
3421  // adding these temporary chunks is probably not even necessary
3422  Instrument* instr = static_cast<Instrument*>(GetParent());
3423  RIFF::List* pCkInstrument = instr->pCkInstrument;
3424  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3425  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3426  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3427  tempRgn = new Region(instr, rgn);
3428  }
3429 
3430  // copy this region's dimensions (with already the dimension split size
3431  // requested by the arguments of this method call) to the temporary
3432  // region, and don't use Region::CopyAssign() here for this task, since
3433  // it would also alter fast lookup helper variables here and there
3434  dimension_def_t newDef;
3435  for (int i = 0; i < Dimensions; ++i) {
3436  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3437  // is this the dimension requested by the method arguments? ...
3438  if (def.dimension == type) { // ... if yes, decrement zone amount by one
3439  def.zones = newZoneSize;
3440  if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3441  newDef = def;
3442  }
3443  tempRgn->AddDimension(&def);
3444  }
3445 
3446  // find the dimension index in the tempRegion which is the dimension
3447  // type passed to this method (paranoidly expecting different order)
3448  int tempReducedDimensionIndex = -1;
3449  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3450  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3451  tempReducedDimensionIndex = d;
3452  break;
3453  }
3454  }
3455 
3456  // copy dimension regions from this region to the temporary region
3457  for (int iDst = 0; iDst < 256; ++iDst) {
3458  DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3459  if (!dstDimRgn) continue;
3460  std::map<dimension_t,int> dimCase;
3461  bool isValidZone = true;
3462  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3463  const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3464  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3465  (iDst >> baseBits) & ((1 << dstBits) - 1);
3466  baseBits += dstBits;
3467  // there are also DimensionRegion objects of unused zones, skip them
3468  if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3469  isValidZone = false;
3470  break;
3471  }
3472  }
3473  if (!isValidZone) continue;
3474  // a bit paranoid: cope with the chance that the dimensions would
3475  // have different order in source and destination regions
3476  const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3477  if (dimCase[type] >= zone) dimCase[type]++;
3478  DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3479  dstDimRgn->CopyAssign(srcDimRgn);
3480  // if this is the upper most zone of the dimension passed to this
3481  // method, then correct (raise) its upper limit to 127
3482  if (newDef.split_type == split_type_normal && isLastZone)
3483  dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3484  }
3485 
3486  // now tempRegion's dimensions and DimensionRegions basically reflect
3487  // what we wanted to get for this actual Region here, so we now just
3488  // delete and recreate the dimension in question with the new amount
3489  // zones and then copy back from tempRegion
3490  DeleteDimension(oldDef);
3491  AddDimension(&newDef);
3492  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3493  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3494  if (!srcDimRgn) continue;
3495  std::map<dimension_t,int> dimCase;
3496  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3497  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3498  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3499  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3500  baseBits += srcBits;
3501  }
3502  // a bit paranoid: cope with the chance that the dimensions would
3503  // have different order in source and destination regions
3504  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3505  if (!dstDimRgn) continue;
3506  dstDimRgn->CopyAssign(srcDimRgn);
3507  }
3508 
3509  // delete temporary region
3510  delete tempRgn;
3511 
3513  }
3514 
3530  dimension_def_t* oldDef = GetDimensionDefinition(type);
3531  if (!oldDef)
3532  throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3533  if (zone < 0 || zone >= oldDef->zones)
3534  throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3535 
3536  const int newZoneSize = oldDef->zones + 1;
3537 
3538  // create a temporary Region which just acts as a temporary copy
3539  // container and will be deleted at the end of this function and will
3540  // also not be visible through the API during this process
3541  gig::Region* tempRgn = NULL;
3542  {
3543  // adding these temporary chunks is probably not even necessary
3544  Instrument* instr = static_cast<Instrument*>(GetParent());
3545  RIFF::List* pCkInstrument = instr->pCkInstrument;
3546  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3547  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3548  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3549  tempRgn = new Region(instr, rgn);
3550  }
3551 
3552  // copy this region's dimensions (with already the dimension split size
3553  // requested by the arguments of this method call) to the temporary
3554  // region, and don't use Region::CopyAssign() here for this task, since
3555  // it would also alter fast lookup helper variables here and there
3556  dimension_def_t newDef;
3557  for (int i = 0; i < Dimensions; ++i) {
3558  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3559  // is this the dimension requested by the method arguments? ...
3560  if (def.dimension == type) { // ... if yes, increment zone amount by one
3561  def.zones = newZoneSize;
3562  if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3563  newDef = def;
3564  }
3565  tempRgn->AddDimension(&def);
3566  }
3567 
3568  // find the dimension index in the tempRegion which is the dimension
3569  // type passed to this method (paranoidly expecting different order)
3570  int tempIncreasedDimensionIndex = -1;
3571  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3572  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3573  tempIncreasedDimensionIndex = d;
3574  break;
3575  }
3576  }
3577 
3578  // copy dimension regions from this region to the temporary region
3579  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3580  DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3581  if (!srcDimRgn) continue;
3582  std::map<dimension_t,int> dimCase;
3583  bool isValidZone = true;
3584  for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3585  const int srcBits = pDimensionDefinitions[d].bits;
3586  dimCase[pDimensionDefinitions[d].dimension] =
3587  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3588  // there are also DimensionRegion objects for unused zones, skip them
3589  if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3590  isValidZone = false;
3591  break;
3592  }
3593  baseBits += srcBits;
3594  }
3595  if (!isValidZone) continue;
3596  // a bit paranoid: cope with the chance that the dimensions would
3597  // have different order in source and destination regions
3598  if (dimCase[type] > zone) dimCase[type]++;
3599  DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3600  dstDimRgn->CopyAssign(srcDimRgn);
3601  // if this is the requested zone to be splitted, then also copy
3602  // the source DimensionRegion to the newly created target zone
3603  // and set the old zones upper limit lower
3604  if (dimCase[type] == zone) {
3605  // lower old zones upper limit
3606  if (newDef.split_type == split_type_normal) {
3607  const int high =
3608  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3609  int low = 0;
3610  if (zone > 0) {
3611  std::map<dimension_t,int> lowerCase = dimCase;
3612  lowerCase[type]--;
3613  DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3614  low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3615  }
3616  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3617  }
3618  // fill the newly created zone of the divided zone as well
3619  dimCase[type]++;
3620  dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3621  dstDimRgn->CopyAssign(srcDimRgn);
3622  }
3623  }
3624 
3625  // now tempRegion's dimensions and DimensionRegions basically reflect
3626  // what we wanted to get for this actual Region here, so we now just
3627  // delete and recreate the dimension in question with the new amount
3628  // zones and then copy back from tempRegion
3629  DeleteDimension(oldDef);
3630  AddDimension(&newDef);
3631  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3632  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3633  if (!srcDimRgn) continue;
3634  std::map<dimension_t,int> dimCase;
3635  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3636  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3637  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3638  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3639  baseBits += srcBits;
3640  }
3641  // a bit paranoid: cope with the chance that the dimensions would
3642  // have different order in source and destination regions
3643  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3644  if (!dstDimRgn) continue;
3645  dstDimRgn->CopyAssign(srcDimRgn);
3646  }
3647 
3648  // delete temporary region
3649  delete tempRgn;
3650 
3652  }
3653 
3669  if (oldType == newType) return;
3670  dimension_def_t* def = GetDimensionDefinition(oldType);
3671  if (!def)
3672  throw gig::Exception("No dimension with provided old dimension type exists on this region");
3673  if (newType == dimension_samplechannel && def->zones != 2)
3674  throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3675  if (GetDimensionDefinition(newType))
3676  throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3677  def->dimension = newType;
3678  def->split_type = __resolveSplitType(newType);
3679  }
3680 
3681  DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3682  uint8_t bits[8] = {};
3683  for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3684  it != DimCase.end(); ++it)
3685  {
3686  for (int d = 0; d < Dimensions; ++d) {
3687  if (pDimensionDefinitions[d].dimension == it->first) {
3688  bits[d] = it->second;
3689  goto nextDimCaseSlice;
3690  }
3691  }
3692  assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3693  nextDimCaseSlice:
3694  ; // noop
3695  }
3696  return GetDimensionRegionByBit(bits);
3697  }
3698 
3709  for (int i = 0; i < Dimensions; ++i)
3710  if (pDimensionDefinitions[i].dimension == type)
3711  return &pDimensionDefinitions[i];
3712  return NULL;
3713  }
3714 
3716  for (int i = 0; i < 256; i++) {
3717  if (pDimensionRegions[i]) delete pDimensionRegions[i];
3718  }
3719  }
3720 
3740  uint8_t bits;
3741  int veldim = -1;
3742  int velbitpos;
3743  int bitpos = 0;
3744  int dimregidx = 0;
3745  for (uint i = 0; i < Dimensions; i++) {
3746  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3747  // the velocity dimension must be handled after the other dimensions
3748  veldim = i;
3749  velbitpos = bitpos;
3750  } else {
3751  switch (pDimensionDefinitions[i].split_type) {
3752  case split_type_normal:
3753  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3754  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3755  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3756  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3757  }
3758  } else {
3759  // gig2: evenly sized zones
3760  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3761  }
3762  break;
3763  case split_type_bit: // the value is already the sought dimension bit number
3764  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3765  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3766  break;
3767  }
3768  dimregidx |= bits << bitpos;
3769  }
3770  bitpos += pDimensionDefinitions[i].bits;
3771  }
3772  DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3773  if (!dimreg) return NULL;
3774  if (veldim != -1) {
3775  // (dimreg is now the dimension region for the lowest velocity)
3776  if (dimreg->VelocityTable) // custom defined zone ranges
3777  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3778  else // normal split type
3779  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3780 
3781  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3782  dimregidx |= (bits & limiter_mask) << velbitpos;
3783  dimreg = pDimensionRegions[dimregidx & 255];
3784  }
3785  return dimreg;
3786  }
3787 
3788  int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3789  uint8_t bits;
3790  int veldim = -1;
3791  int velbitpos;
3792  int bitpos = 0;
3793  int dimregidx = 0;
3794  for (uint i = 0; i < Dimensions; i++) {
3795  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3796  // the velocity dimension must be handled after the other dimensions
3797  veldim = i;
3798  velbitpos = bitpos;
3799  } else {
3800  switch (pDimensionDefinitions[i].split_type) {
3801  case split_type_normal:
3802  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3803  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3804  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3805  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3806  }
3807  } else {
3808  // gig2: evenly sized zones
3809  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3810  }
3811  break;
3812  case split_type_bit: // the value is already the sought dimension bit number
3813  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3814  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3815  break;
3816  }
3817  dimregidx |= bits << bitpos;
3818  }
3819  bitpos += pDimensionDefinitions[i].bits;
3820  }
3821  dimregidx &= 255;
3822  DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3823  if (!dimreg) return -1;
3824  if (veldim != -1) {
3825  // (dimreg is now the dimension region for the lowest velocity)
3826  if (dimreg->VelocityTable) // custom defined zone ranges
3827  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3828  else // normal split type
3829  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3830 
3831  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3832  dimregidx |= (bits & limiter_mask) << velbitpos;
3833  dimregidx &= 255;
3834  }
3835  return dimregidx;
3836  }
3837 
3849  return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3850  << pDimensionDefinitions[5].bits | DimBits[5])
3851  << pDimensionDefinitions[4].bits | DimBits[4])
3852  << pDimensionDefinitions[3].bits | DimBits[3])
3853  << pDimensionDefinitions[2].bits | DimBits[2])
3854  << pDimensionDefinitions[1].bits | DimBits[1])
3855  << pDimensionDefinitions[0].bits | DimBits[0]];
3856  }
3857 
3868  if (pSample) return static_cast<gig::Sample*>(pSample);
3869  else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3870  }
3871 
3873  if ((int32_t)WavePoolTableIndex == -1) return NULL;
3874  File* file = (File*) GetParent()->GetParent();
3875  if (!file->pWavePoolTable) return NULL;
3876  if (WavePoolTableIndex + 1 > file->WavePoolCount) 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 ...
4131  Compression = COMPRESSION_NONE;
4132  Encoding = ENCODING_ASCII;
4133  Language = LANGUAGE_NKSP;
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 
4174  // recalculate CRC32 check sum
4175  __resetCRC(crc);
4176  __calculateCRC(&data[0], data.size(), crc);
4177  __encodeCRC(crc);
4178  // make sure chunk exists and has the required size
4179  const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4180  if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4181  else pChunk->Resize(chunkSize);
4182  // fill the chunk data to be written to disk
4183  uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4184  int pos = 0;
4185  store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4186  pos += sizeof(int32_t);
4187  store32(&pData[pos], Compression);
4188  pos += sizeof(int32_t);
4189  store32(&pData[pos], Encoding);
4190  pos += sizeof(int32_t);
4191  store32(&pData[pos], Language);
4192  pos += sizeof(int32_t);
4193  store32(&pData[pos], Bypass ? 1 : 0);
4194  pos += sizeof(int32_t);
4195  store32(&pData[pos], crc);
4196  pos += sizeof(int32_t);
4197  store32(&pData[pos], Name.size());
4198  pos += sizeof(int32_t);
4199  for (int i = 0; i < Name.size(); ++i, ++pos)
4200  pData[pos] = Name[i];
4201  for (int i = 0; i < data.size(); ++i, ++pos)
4202  pData[pos] = data[i];
4203  }
4204 
4212  if (this->pGroup = pGroup) return;
4213  if (pChunk)
4214  pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4215  this->pGroup = pGroup;
4216  }
4217 
4225  return pGroup;
4226  }
4227 
4229  File* pFile = pGroup->pFile;
4230  for (int i = 0; pFile->GetInstrument(i); ++i) {
4231  Instrument* instr = pFile->GetInstrument(i);
4232  instr->RemoveScript(this);
4233  }
4234  }
4235 
4236 // *************** ScriptGroup ***************
4237 // *
4238 
4240  pFile = file;
4241  pList = lstRTIS;
4242  pScripts = NULL;
4243  if (lstRTIS) {
4244  RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4245  ::LoadString(ckName, Name);
4246  } else {
4247  Name = "Default Group";
4248  }
4249  }
4250 
4252  if (pScripts) {
4253  std::list<Script*>::iterator iter = pScripts->begin();
4254  std::list<Script*>::iterator end = pScripts->end();
4255  while (iter != end) {
4256  delete *iter;
4257  ++iter;
4258  }
4259  delete pScripts;
4260  }
4261  }
4262 
4273  if (pScripts) {
4274  if (!pList)
4275  pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4276 
4277  // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4278  ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4279 
4280  for (std::list<Script*>::iterator it = pScripts->begin();
4281  it != pScripts->end(); ++it)
4282  {
4283  (*it)->UpdateChunks(pProgress);
4284  }
4285  }
4286  }
4287 
4296  if (!pScripts) LoadScripts();
4297  std::list<Script*>::iterator it = pScripts->begin();
4298  for (uint i = 0; it != pScripts->end(); ++i, ++it)
4299  if (i == index) return *it;
4300  return NULL;
4301  }
4302 
4315  if (!pScripts) LoadScripts();
4316  Script* pScript = new Script(this, NULL);
4317  pScripts->push_back(pScript);
4318  return pScript;
4319  }
4320 
4332  if (!pScripts) LoadScripts();
4333  std::list<Script*>::iterator iter =
4334  find(pScripts->begin(), pScripts->end(), pScript);
4335  if (iter == pScripts->end())
4336  throw gig::Exception("Could not delete script, could not find given script");
4337  pScripts->erase(iter);
4338  pScript->RemoveAllScriptReferences();
4339  if (pScript->pChunk)
4340  pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4341  delete pScript;
4342  }
4343 
4345  if (pScripts) return;
4346  pScripts = new std::list<Script*>;
4347  if (!pList) return;
4348 
4349  for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4350  ck = pList->GetNextSubChunk())
4351  {
4352  if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4353  pScripts->push_back(new Script(this, ck));
4354  }
4355  }
4356  }
4357 
4358 // *************** Instrument ***************
4359 // *
4360 
4361  Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4362  static const DLS::Info::string_length_t fixedStringLengths[] = {
4363  { CHUNK_ID_INAM, 64 },
4364  { CHUNK_ID_ISFT, 12 },
4365  { 0, 0 }
4366  };
4367  pInfo->SetFixedStringLengths(fixedStringLengths);
4368 
4369  // Initialization
4370  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4371  EffectSend = 0;
4372  Attenuation = 0;
4373  FineTune = 0;
4374  PitchbendRange = 0;
4375  PianoReleaseMode = false;
4376  DimensionKeyRange.low = 0;
4377  DimensionKeyRange.high = 0;
4378  pMidiRules = new MidiRule*[3];
4379  pMidiRules[0] = NULL;
4380  pScriptRefs = NULL;
4381 
4382  // Loading
4383  RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
4384  if (lart) {
4385  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4386  if (_3ewg) {
4387  EffectSend = _3ewg->ReadUint16();
4388  Attenuation = _3ewg->ReadInt32();
4389  FineTune = _3ewg->ReadInt16();
4390  PitchbendRange = _3ewg->ReadInt16();
4391  uint8_t dimkeystart = _3ewg->ReadUint8();
4392  PianoReleaseMode = dimkeystart & 0x01;
4393  DimensionKeyRange.low = dimkeystart >> 1;
4394  DimensionKeyRange.high = _3ewg->ReadUint8();
4395 
4396  if (_3ewg->GetSize() > 32) {
4397  // read MIDI rules
4398  int i = 0;
4399  _3ewg->SetPos(32);
4400  uint8_t id1 = _3ewg->ReadUint8();
4401  uint8_t id2 = _3ewg->ReadUint8();
4402 
4403  if (id2 == 16) {
4404  if (id1 == 4) {
4405  pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4406  } else if (id1 == 0) {
4407  pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4408  } else if (id1 == 3) {
4409  pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4410  } else {
4411  pMidiRules[i++] = new MidiRuleUnknown;
4412  }
4413  }
4414  else if (id1 != 0 || id2 != 0) {
4415  pMidiRules[i++] = new MidiRuleUnknown;
4416  }
4417  //TODO: all the other types of rules
4418 
4419  pMidiRules[i] = NULL;
4420  }
4421  }
4422  }
4423 
4424  if (pFile->GetAutoLoad()) {
4425  if (!pRegions) pRegions = new RegionList;
4426  RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4427  if (lrgn) {
4428  RIFF::List* rgn = lrgn->GetFirstSubList();
4429  while (rgn) {
4430  if (rgn->GetListType() == LIST_TYPE_RGN) {
4431  __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4432  pRegions->push_back(new Region(this, rgn));
4433  }
4434  rgn = lrgn->GetNextSubList();
4435  }
4436  // Creating Region Key Table for fast lookup
4438  }
4439  }
4440 
4441  // own gig format extensions
4442  RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4443  if (lst3LS) {
4444  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4445  if (ckSCSL) {
4446  int headerSize = ckSCSL->ReadUint32();
4447  int slotCount = ckSCSL->ReadUint32();
4448  if (slotCount) {
4449  int slotSize = ckSCSL->ReadUint32();
4450  ckSCSL->SetPos(headerSize); // in case of future header extensions
4451  int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4452  for (int i = 0; i < slotCount; ++i) {
4453  _ScriptPooolEntry e;
4454  e.fileOffset = ckSCSL->ReadUint32();
4455  e.bypass = ckSCSL->ReadUint32() & 1;
4456  if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4457  scriptPoolFileOffsets.push_back(e);
4458  }
4459  }
4460  }
4461  }
4462 
4463  __notify_progress(pProgress, 1.0f); // notify done
4464  }
4465 
4467  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4468  RegionList::iterator iter = pRegions->begin();
4469  RegionList::iterator end = pRegions->end();
4470  for (; iter != end; ++iter) {
4471  gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4472  int low = pRegion->KeyRange.low > 0 ? pRegion->KeyRange.low : 0;
4473  int high = pRegion->KeyRange.high > 127 ? 127 : pRegion->KeyRange.high;
4474  for (int iKey = low; iKey <= high; iKey++) {
4475  RegionKeyTable[iKey] = pRegion;
4476  }
4477  }
4478  }
4479 
4481  for (int i = 0 ; pMidiRules[i] ; i++) {
4482  delete pMidiRules[i];
4483  }
4484  delete[] pMidiRules;
4485  if (pScriptRefs) delete pScriptRefs;
4486  }
4487 
4499  // first update base classes' chunks
4500  DLS::Instrument::UpdateChunks(pProgress);
4501 
4502  // update Regions' chunks
4503  {
4504  RegionList::iterator iter = pRegions->begin();
4505  RegionList::iterator end = pRegions->end();
4506  for (; iter != end; ++iter)
4507  (*iter)->UpdateChunks(pProgress);
4508  }
4509 
4510  // make sure 'lart' RIFF list chunk exists
4512  if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4513  // make sure '3ewg' RIFF chunk exists
4514  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4515  if (!_3ewg) {
4516  File* pFile = (File*) GetParent();
4517 
4518  // 3ewg is bigger in gig3, as it includes the iMIDI rules
4519  int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4520  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4521  memset(_3ewg->LoadChunkData(), 0, size);
4522  }
4523  // update '3ewg' RIFF chunk
4524  uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4525  store16(&pData[0], EffectSend);
4526  store32(&pData[2], Attenuation);
4527  store16(&pData[6], FineTune);
4528  store16(&pData[8], PitchbendRange);
4529  const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4530  DimensionKeyRange.low << 1;
4531  pData[10] = dimkeystart;
4532  pData[11] = DimensionKeyRange.high;
4533 
4534  if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4535  pData[32] = 0;
4536  pData[33] = 0;
4537  } else {
4538  for (int i = 0 ; pMidiRules[i] ; i++) {
4539  pMidiRules[i]->UpdateChunks(pData);
4540  }
4541  }
4542 
4543  // own gig format extensions
4544  if (ScriptSlotCount()) {
4545  // make sure we have converted the original loaded script file
4546  // offsets into valid Script object pointers
4547  LoadScripts();
4548 
4550  if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4551  const int slotCount = pScriptRefs->size();
4552  const int headerSize = 3 * sizeof(uint32_t);
4553  const int slotSize = 2 * sizeof(uint32_t);
4554  const int totalChunkSize = headerSize + slotCount * slotSize;
4555  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4556  if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4557  else ckSCSL->Resize(totalChunkSize);
4558  uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4559  int pos = 0;
4560  store32(&pData[pos], headerSize);
4561  pos += sizeof(uint32_t);
4562  store32(&pData[pos], slotCount);
4563  pos += sizeof(uint32_t);
4564  store32(&pData[pos], slotSize);
4565  pos += sizeof(uint32_t);
4566  for (int i = 0; i < slotCount; ++i) {
4567  // arbitrary value, the actual file offset will be updated in
4568  // UpdateScriptFileOffsets() after the file has been resized
4569  int bogusFileOffset = 0;
4570  store32(&pData[pos], bogusFileOffset);
4571  pos += sizeof(uint32_t);
4572  store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4573  pos += sizeof(uint32_t);
4574  }
4575  } else {
4576  // no script slots, so get rid of any LS custom RIFF chunks (if any)
4578  if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4579  }
4580  }
4581 
4583  // own gig format extensions
4584  if (pScriptRefs && pScriptRefs->size() > 0) {
4586  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4587  const int slotCount = pScriptRefs->size();
4588  const int headerSize = 3 * sizeof(uint32_t);
4589  ckSCSL->SetPos(headerSize);
4590  for (int i = 0; i < slotCount; ++i) {
4591  uint32_t fileOffset =
4592  (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4593  (*pScriptRefs)[i].script->pChunk->GetPos() -
4595  ckSCSL->WriteUint32(&fileOffset);
4596  // jump over flags entry (containing the bypass flag)
4597  ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4598  }
4599  }
4600  }
4601 
4609  Region* Instrument::GetRegion(unsigned int Key) {
4610  if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4611  return RegionKeyTable[Key];
4612 
4613  /*for (int i = 0; i < Regions; i++) {
4614  if (Key <= pRegions[i]->KeyRange.high &&
4615  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
4616  }
4617  return NULL;*/
4618  }
4619 
4628  if (!pRegions) return NULL;
4629  RegionsIterator = pRegions->begin();
4630  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4631  }
4632 
4642  if (!pRegions) return NULL;
4643  RegionsIterator++;
4644  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4645  }
4646 
4648  // create new Region object (and its RIFF chunks)
4650  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4651  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4652  Region* pNewRegion = new Region(this, rgn);
4653  pRegions->push_back(pNewRegion);
4654  Regions = pRegions->size();
4655  // update Region key table for fast lookup
4657  // done
4658  return pNewRegion;
4659  }
4660 
4662  if (!pRegions) return;
4664  // update Region key table for fast lookup
4666  }
4667 
4696  if (dst && GetParent() != dst->GetParent())
4697  throw Exception(
4698  "gig::Instrument::MoveTo() can only be used for moving within "
4699  "the same gig file."
4700  );
4701 
4702  File* pFile = (File*) GetParent();
4703 
4704  // move this instrument within the instrument list
4705  {
4706  DLS::File::InstrumentList& list = *pFile->pInstruments;
4707 
4708  DLS::File::InstrumentList::iterator itFrom =
4709  std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4710 
4711  DLS::File::InstrumentList::iterator itTo =
4712  std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4713 
4714  list.splice(itTo, list, itFrom);
4715  }
4716 
4717  // move the instrument's actual list RIFF chunk appropriately
4718  RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4719  lstCkInstruments->MoveSubChunk(
4720  this->pCkInstrument,
4721  (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4722  );
4723  }
4724 
4736  return pMidiRules[i];
4737  }
4738 
4745  delete pMidiRules[0];
4747  pMidiRules[0] = r;
4748  pMidiRules[1] = 0;
4749  return r;
4750  }
4751 
4758  delete pMidiRules[0];
4759  MidiRuleLegato* r = new MidiRuleLegato;
4760  pMidiRules[0] = r;
4761  pMidiRules[1] = 0;
4762  return r;
4763  }
4764 
4771  delete pMidiRules[0];
4773  pMidiRules[0] = r;
4774  pMidiRules[1] = 0;
4775  return r;
4776  }
4777 
4784  delete pMidiRules[i];
4785  pMidiRules[i] = 0;
4786  }
4787 
4789  if (pScriptRefs) return;
4790  pScriptRefs = new std::vector<_ScriptPooolRef>;
4791  if (scriptPoolFileOffsets.empty()) return;
4792  File* pFile = (File*) GetParent();
4793  for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4794  uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4795  for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4796  ScriptGroup* group = pFile->GetScriptGroup(i);
4797  for (uint s = 0; group->GetScript(s); ++s) {
4798  Script* script = group->GetScript(s);
4799  if (script->pChunk) {
4800  uint32_t offset = script->pChunk->GetFilePos() -
4801  script->pChunk->GetPos() -
4803  if (offset == soughtOffset)
4804  {
4805  _ScriptPooolRef ref;
4806  ref.script = script;
4807  ref.bypass = scriptPoolFileOffsets[k].bypass;
4808  pScriptRefs->push_back(ref);
4809  break;
4810  }
4811  }
4812  }
4813  }
4814  }
4815  // we don't need that anymore
4816  scriptPoolFileOffsets.clear();
4817  }
4818 
4832  LoadScripts();
4833  if (index >= pScriptRefs->size()) return NULL;
4834  return pScriptRefs->at(index).script;
4835  }
4836 
4872  void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4873  LoadScripts();
4874  _ScriptPooolRef ref = { pScript, bypass };
4875  pScriptRefs->push_back(ref);
4876  }
4877 
4892  void Instrument::SwapScriptSlots(uint index1, uint index2) {
4893  LoadScripts();
4894  if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4895  return;
4896  _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4897  (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4898  (*pScriptRefs)[index2] = tmp;
4899  }
4900 
4907  void Instrument::RemoveScriptSlot(uint index) {
4908  LoadScripts();
4909  if (index >= pScriptRefs->size()) return;
4910  pScriptRefs->erase( pScriptRefs->begin() + index );
4911  }
4912 
4926  LoadScripts();
4927  for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4928  if ((*pScriptRefs)[i].script == pScript) {
4929  pScriptRefs->erase( pScriptRefs->begin() + i );
4930  }
4931  }
4932  }
4933 
4949  return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4950  }
4951 
4969  if (index >= ScriptSlotCount()) return false;
4970  return pScriptRefs ? pScriptRefs->at(index).bypass
4971  : scriptPoolFileOffsets.at(index).bypass;
4972 
4973  }
4974 
4988  void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4989  if (index >= ScriptSlotCount()) return;
4990  if (pScriptRefs)
4991  pScriptRefs->at(index).bypass = bBypass;
4992  else
4993  scriptPoolFileOffsets.at(index).bypass = bBypass;
4994  }
4995 
5006  CopyAssign(orig, NULL);
5007  }
5008 
5017  void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5018  // handle base class
5019  // (without copying DLS region stuff)
5021 
5022  // handle own member variables
5023  Attenuation = orig->Attenuation;
5024  EffectSend = orig->EffectSend;
5025  FineTune = orig->FineTune;
5029  scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5030  pScriptRefs = orig->pScriptRefs;
5031 
5032  // free old midi rules
5033  for (int i = 0 ; pMidiRules[i] ; i++) {
5034  delete pMidiRules[i];
5035  }
5036  //TODO: MIDI rule copying
5037  pMidiRules[0] = NULL;
5038 
5039  // delete all old regions
5040  while (Regions) DeleteRegion(GetFirstRegion());
5041  // create new regions and copy them from original
5042  {
5043  RegionList::const_iterator it = orig->pRegions->begin();
5044  for (int i = 0; i < orig->Regions; ++i, ++it) {
5045  Region* dstRgn = AddRegion();
5046  //NOTE: Region does semi-deep copy !
5047  dstRgn->CopyAssign(
5048  static_cast<gig::Region*>(*it),
5049  mSamples
5050  );
5051  }
5052  }
5053 
5055  }
5056 
5057 
5058 // *************** Group ***************
5059 // *
5060 
5067  Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5068  pFile = file;
5069  pNameChunk = ck3gnm;
5070  ::LoadString(pNameChunk, Name);
5071  }
5072 
5074  // remove the chunk associated with this group (if any)
5075  if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5076  }
5077 
5088  void Group::UpdateChunks(progress_t* pProgress) {
5089  // make sure <3gri> and <3gnl> list chunks exist
5090  RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5091  if (!_3gri) {
5092  _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5093  pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5094  }
5095  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5096  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5097 
5098  if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5099  // v3 has a fixed list of 128 strings, find a free one
5100  for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5101  if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5102  pNameChunk = ck;
5103  break;
5104  }
5105  }
5106  }
5107 
5108  // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5109  ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5110  }
5111 
5124  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5125  for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5126  if (pSample->GetGroup() == this) return pSample;
5127  }
5128  return NULL;
5129  }
5130 
5142  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5143  for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5144  if (pSample->GetGroup() == this) return pSample;
5145  }
5146  return NULL;
5147  }
5148 
5152  void Group::AddSample(Sample* pSample) {
5153  pSample->pGroup = this;
5154  }
5155 
5163  // get "that" other group first
5164  Group* pOtherGroup = NULL;
5165  for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5166  if (pOtherGroup != this) break;
5167  }
5168  if (!pOtherGroup) throw Exception(
5169  "Could not move samples to another group, since there is no "
5170  "other Group. This is a bug, report it!"
5171  );
5172  // now move all samples of this group to the other group
5173  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5174  pOtherGroup->AddSample(pSample);
5175  }
5176  }
5177 
5178 
5179 
5180 // *************** File ***************
5181 // *
5182 
5185  0, 2, 19980628 & 0xffff, 19980628 >> 16
5186  };
5187 
5190  0, 3, 20030331 & 0xffff, 20030331 >> 16
5191  };
5192 
5193  static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5194  { CHUNK_ID_IARL, 256 },
5195  { CHUNK_ID_IART, 128 },
5196  { CHUNK_ID_ICMS, 128 },
5197  { CHUNK_ID_ICMT, 1024 },
5198  { CHUNK_ID_ICOP, 128 },
5199  { CHUNK_ID_ICRD, 128 },
5200  { CHUNK_ID_IENG, 128 },
5201  { CHUNK_ID_IGNR, 128 },
5202  { CHUNK_ID_IKEY, 128 },
5203  { CHUNK_ID_IMED, 128 },
5204  { CHUNK_ID_INAM, 128 },
5205  { CHUNK_ID_IPRD, 128 },
5206  { CHUNK_ID_ISBJ, 128 },
5207  { CHUNK_ID_ISFT, 128 },
5208  { CHUNK_ID_ISRC, 128 },
5209  { CHUNK_ID_ISRF, 128 },
5210  { CHUNK_ID_ITCH, 128 },
5211  { 0, 0 }
5212  };
5213 
5215  bAutoLoad = true;
5216  *pVersion = VERSION_3;
5217  pGroups = NULL;
5218  pScriptGroups = NULL;
5219  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5220  pInfo->ArchivalLocation = String(256, ' ');
5221 
5222  // add some mandatory chunks to get the file chunks in right
5223  // order (INFO chunk will be moved to first position later)
5227 
5228  GenerateDLSID();
5229  }
5230 
5232  bAutoLoad = true;
5233  pGroups = NULL;
5234  pScriptGroups = NULL;
5235  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5236  }
5237 
5239  if (pGroups) {
5240  std::list<Group*>::iterator iter = pGroups->begin();
5241  std::list<Group*>::iterator end = pGroups->end();
5242  while (iter != end) {
5243  delete *iter;
5244  ++iter;
5245  }
5246  delete pGroups;
5247  }
5248  if (pScriptGroups) {
5249  std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5250  std::list<ScriptGroup*>::iterator end = pScriptGroups->end();
5251  while (iter != end) {
5252  delete *iter;
5253  ++iter;
5254  }
5255  delete pScriptGroups;
5256  }
5257  }
5258 
5260  if (!pSamples) LoadSamples(pProgress);
5261  if (!pSamples) return NULL;
5262  SamplesIterator = pSamples->begin();
5263  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5264  }
5265 
5267  if (!pSamples) return NULL;
5268  SamplesIterator++;
5269  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5270  }
5271 
5277  Sample* File::GetSample(uint index) {
5278  if (!pSamples) LoadSamples();
5279  if (!pSamples) return NULL;
5280  DLS::File::SampleList::iterator it = pSamples->begin();
5281  for (int i = 0; i < index; ++i) {
5282  ++it;
5283  if (it == pSamples->end()) return NULL;
5284  }
5285  if (it == pSamples->end()) return NULL;
5286  return static_cast<gig::Sample*>( *it );
5287  }
5288 
5297  if (!pSamples) LoadSamples();
5300  // create new Sample object and its respective 'wave' list chunk
5301  RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5302  Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5303 
5304  // add mandatory chunks to get the chunks in right order
5305  wave->AddSubChunk(CHUNK_ID_FMT, 16);
5306  wave->AddSubList(LIST_TYPE_INFO);
5307 
5308  pSamples->push_back(pSample);
5309  return pSample;
5310  }
5311 
5321  void File::DeleteSample(Sample* pSample) {
5322  if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5323  SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5324  if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5325  if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5326  pSamples->erase(iter);
5327  delete pSample;
5328 
5329  SampleList::iterator tmp = SamplesIterator;
5330  // remove all references to the sample
5331  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5332  instrument = GetNextInstrument()) {
5333  for (Region* region = instrument->GetFirstRegion() ; region ;
5334  region = instrument->GetNextRegion()) {
5335 
5336  if (region->GetSample() == pSample) region->SetSample(NULL);
5337 
5338  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5339  gig::DimensionRegion *d = region->pDimensionRegions[i];
5340  if (d->pSample == pSample) d->pSample = NULL;
5341  }
5342  }
5343  }
5344  SamplesIterator = tmp; // restore iterator
5345  }
5346 
5348  LoadSamples(NULL);
5349  }
5350 
5351  void File::LoadSamples(progress_t* pProgress) {
5352  // Groups must be loaded before samples, because samples will try
5353  // to resolve the group they belong to
5354  if (!pGroups) LoadGroups();
5355 
5356  if (!pSamples) pSamples = new SampleList;
5357 
5358  RIFF::File* file = pRIFF;
5359 
5360  // just for progress calculation
5361  int iSampleIndex = 0;
5362  int iTotalSamples = WavePoolCount;
5363 
5364  // check if samples should be loaded from extension files
5365  int lastFileNo = 0;
5366  for (int i = 0 ; i < WavePoolCount ; i++) {
5367  if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5368  }
5369  String name(pRIFF->GetFileName());
5370  int nameLen = name.length();
5371  char suffix[6];
5372  if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5373 
5374  for (int fileNo = 0 ; ; ) {
5375  RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5376  if (wvpl) {
5377  unsigned long wvplFileOffset = wvpl->GetFilePos();
5378  RIFF::List* wave = wvpl->GetFirstSubList();
5379  while (wave) {
5380  if (wave->GetListType() == LIST_TYPE_WAVE) {
5381  // notify current progress
5382  const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5383  __notify_progress(pProgress, subprogress);
5384 
5385  unsigned long waveFileOffset = wave->GetFilePos();
5386  pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5387 
5388  iSampleIndex++;
5389  }
5390  wave = wvpl->GetNextSubList();
5391  }
5392 
5393  if (fileNo == lastFileNo) break;
5394 
5395  // open extension file (*.gx01, *.gx02, ...)
5396  fileNo++;
5397  sprintf(suffix, ".gx%02d", fileNo);
5398  name.replace(nameLen, 5, suffix);
5399  file = new RIFF::File(name);
5400  ExtensionFiles.push_back(file);
5401  } else break;
5402  }
5403 
5404  __notify_progress(pProgress, 1.0); // notify done
5405  }
5406 
5408  if (!pInstruments) LoadInstruments();
5409  if (!pInstruments) return NULL;
5410  InstrumentsIterator = pInstruments->begin();
5411  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5412  }
5413 
5415  if (!pInstruments) return NULL;
5417  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5418  }
5419 
5427  Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
5428  if (!pInstruments) {
5429  // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
5430 
5431  // sample loading subtask
5432  progress_t subprogress;
5433  __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5434  __notify_progress(&subprogress, 0.0f);
5435  if (GetAutoLoad())
5436  GetFirstSample(&subprogress); // now force all samples to be loaded
5437  __notify_progress(&subprogress, 1.0f);
5438 
5439  // instrument loading subtask
5440  if (pProgress && pProgress->callback) {
5441  subprogress.__range_min = subprogress.__range_max;
5442  subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
5443  }
5444  __notify_progress(&subprogress, 0.0f);
5445  LoadInstruments(&subprogress);
5446  __notify_progress(&subprogress, 1.0f);
5447  }
5448  if (!pInstruments) return NULL;
5449  InstrumentsIterator = pInstruments->begin();
5450  for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5451  if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5453  }
5454  return NULL;
5455  }
5456 
5465  if (!pInstruments) LoadInstruments();
5467  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5468  RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5469 
5470  // add mandatory chunks to get the chunks in right order
5471  lstInstr->AddSubList(LIST_TYPE_INFO);
5472  lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5473 
5474  Instrument* pInstrument = new Instrument(this, lstInstr);
5475  pInstrument->GenerateDLSID();
5476 
5477  lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5478 
5479  // this string is needed for the gig to be loadable in GSt:
5480  pInstrument->pInfo->Software = "Endless Wave";
5481 
5482  pInstruments->push_back(pInstrument);
5483  return pInstrument;
5484  }
5485 
5502  Instrument* instr = AddInstrument();
5503  instr->CopyAssign(orig);
5504  return instr;
5505  }
5506 
5518  void File::AddContentOf(File* pFile) {
5519  static int iCallCount = -1;
5520  iCallCount++;
5521  std::map<Group*,Group*> mGroups;
5522  std::map<Sample*,Sample*> mSamples;
5523 
5524  // clone sample groups
5525  for (int i = 0; pFile->GetGroup(i); ++i) {
5526  Group* g = AddGroup();
5527  g->Name =
5528  "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5529  mGroups[pFile->GetGroup(i)] = g;
5530  }
5531 
5532  // clone samples (not waveform data here yet)
5533  for (int i = 0; pFile->GetSample(i); ++i) {
5534  Sample* s = AddSample();
5535  s->CopyAssignMeta(pFile->GetSample(i));
5536  mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5537  mSamples[pFile->GetSample(i)] = s;
5538  }
5539 
5540  //BUG: For some reason this method only works with this additional
5541  // Save() call in between here.
5542  //
5543  // Important: The correct one of the 2 Save() methods has to be called
5544  // here, depending on whether the file is completely new or has been
5545  // saved to disk already, otherwise it will result in data corruption.
5546  if (pRIFF->IsNew())
5547  Save(GetFileName());
5548  else
5549  Save();
5550 
5551  // clone instruments
5552  // (passing the crosslink table here for the cloned samples)
5553  for (int i = 0; pFile->GetInstrument(i); ++i) {
5554  Instrument* instr = AddInstrument();
5555  instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5556  }
5557 
5558  // Mandatory: file needs to be saved to disk at this point, so this
5559  // file has the correct size and data layout for writing the samples'
5560  // waveform data to disk.
5561  Save();
5562 
5563  // clone samples' waveform data
5564  // (using direct read & write disk streaming)
5565  for (int i = 0; pFile->GetSample(i); ++i) {
5566  mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5567  }
5568  }
5569 
5578  void File::DeleteInstrument(Instrument* pInstrument) {
5579  if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5580  InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5581  if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5582  pInstruments->erase(iter);
5583  delete pInstrument;
5584  }
5585 
5587  LoadInstruments(NULL);
5588  }
5589 
5592  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5593  if (lstInstruments) {
5594  int iInstrumentIndex = 0;
5595  RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
5596  while (lstInstr) {
5597  if (lstInstr->GetListType() == LIST_TYPE_INS) {
5598  // notify current progress
5599  const float localProgress = (float) iInstrumentIndex / (float) Instruments;
5600  __notify_progress(pProgress, localProgress);
5601 
5602  // divide local progress into subprogress for loading current Instrument
5603  progress_t subprogress;
5604  __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5605 
5606  pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5607 
5608  iInstrumentIndex++;
5609  }
5610  lstInstr = lstInstruments->GetNextSubList();
5611  }
5612  __notify_progress(pProgress, 1.0); // notify done
5613  }
5614  }
5615 
5619  void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5621  if (!_3crc) return;
5622 
5623  // get the index of the sample
5624  int iWaveIndex = -1;
5625  File::SampleList::iterator iter = pSamples->begin();
5626  File::SampleList::iterator end = pSamples->end();
5627  for (int index = 0; iter != end; ++iter, ++index) {
5628  if (*iter == pSample) {
5629  iWaveIndex = index;
5630  break;
5631  }
5632  }
5633  if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5634 
5635  // write the CRC-32 checksum to disk
5636  _3crc->SetPos(iWaveIndex * 8);
5637  uint32_t tmp = 1;
5638  _3crc->WriteUint32(&tmp); // unknown, always 1?
5639  _3crc->WriteUint32(&crc);
5640  }
5641 
5643  if (!pGroups) LoadGroups();
5644  // there must always be at least one group
5645  GroupsIterator = pGroups->begin();
5646  return *GroupsIterator;
5647  }
5648 
5650  if (!pGroups) return NULL;
5651  ++GroupsIterator;
5652  return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5653  }
5654 
5661  Group* File::GetGroup(uint index) {
5662  if (!pGroups) LoadGroups();
5663  GroupsIterator = pGroups->begin();
5664  for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5665  if (i == index) return *GroupsIterator;
5666  ++GroupsIterator;
5667  }
5668  return NULL;
5669  }
5670 
5682  if (!pGroups) LoadGroups();
5683  GroupsIterator = pGroups->begin();
5684  for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5685  if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5686  return NULL;
5687  }
5688 
5690  if (!pGroups) LoadGroups();
5691  // there must always be at least one group
5693  Group* pGroup = new Group(this, NULL);
5694  pGroups->push_back(pGroup);
5695  return pGroup;
5696  }
5697 
5707  void File::DeleteGroup(Group* pGroup) {
5708  if (!pGroups) LoadGroups();
5709  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5710  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5711  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5712  // delete all members of this group
5713  for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5714  DeleteSample(pSample);
5715  }
5716  // now delete this group object
5717  pGroups->erase(iter);
5718  delete pGroup;
5719  }
5720 
5732  if (!pGroups) LoadGroups();
5733  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5734  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5735  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5736  // move all members of this group to another group
5737  pGroup->MoveAll();
5738  pGroups->erase(iter);
5739  delete pGroup;
5740  }
5741 
5743  if (!pGroups) pGroups = new std::list<Group*>;
5744  // try to read defined groups from file
5746  if (lst3gri) {
5747  RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5748  if (lst3gnl) {
5749  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5750  while (ck) {
5751  if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5752  if (pVersion && pVersion->major == 3 &&
5753  strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5754 
5755  pGroups->push_back(new Group(this, ck));
5756  }
5757  ck = lst3gnl->GetNextSubChunk();
5758  }
5759  }
5760  }
5761  // if there were no group(s), create at least the mandatory default group
5762  if (!pGroups->size()) {
5763  Group* pGroup = new Group(this, NULL);
5764  pGroup->Name = "Default Group";
5765  pGroups->push_back(pGroup);
5766  }
5767  }
5768 
5777  if (!pScriptGroups) LoadScriptGroups();
5778  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5779  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5780  if (i == index) return *it;
5781  return NULL;
5782  }
5783 
5793  if (!pScriptGroups) LoadScriptGroups();
5794  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5795  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5796  if ((*it)->Name == name) return *it;
5797  return NULL;
5798  }
5799 
5809  if (!pScriptGroups) LoadScriptGroups();
5810  ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5811  pScriptGroups->push_back(pScriptGroup);
5812  return pScriptGroup;
5813  }
5814 
5827  void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5828  if (!pScriptGroups) LoadScriptGroups();
5829  std::list<ScriptGroup*>::iterator iter =
5830  find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5831  if (iter == pScriptGroups->end())
5832  throw gig::Exception("Could not delete script group, could not find given script group");
5833  pScriptGroups->erase(iter);
5834  for (int i = 0; pScriptGroup->GetScript(i); ++i)
5835  pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5836  if (pScriptGroup->pList)
5837  pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5838  delete pScriptGroup;
5839  }
5840 
5842  if (pScriptGroups) return;
5843  pScriptGroups = new std::list<ScriptGroup*>;
5845  if (lstLS) {
5846  for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5847  lst = lstLS->GetNextSubList())
5848  {
5849  if (lst->GetListType() == LIST_TYPE_RTIS) {
5850  pScriptGroups->push_back(new ScriptGroup(this, lst));
5851  }
5852  }
5853  }
5854  }
5855 
5867  void File::UpdateChunks(progress_t* pProgress) {
5868  bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5869 
5871 
5872  // update own gig format extension chunks
5873  // (not part of the GigaStudio 4 format)
5874  //
5875  // This must be performed before writing the chunks for instruments,
5876  // because the instruments' script slots will write the file offsets
5877  // of the respective instrument script chunk as reference.
5878  if (pScriptGroups) {
5880  if (pScriptGroups->empty()) {
5881  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5882  } else {
5883  if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5884 
5885  // Update instrument script (group) chunks.
5886 
5887  for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5888  it != pScriptGroups->end(); ++it)
5889  {
5890  (*it)->UpdateChunks(pProgress);
5891  }
5892  }
5893  }
5894 
5895  // first update base class's chunks
5896  DLS::File::UpdateChunks(pProgress);
5897 
5898  if (newFile) {
5899  // INFO was added by Resource::UpdateChunks - make sure it
5900  // is placed first in file
5902  RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5903  if (first != info) {
5904  pRIFF->MoveSubChunk(info, first);
5905  }
5906  }
5907 
5908  // update group's chunks
5909  if (pGroups) {
5910  // make sure '3gri' and '3gnl' list chunks exist
5911  // (before updating the Group chunks)
5913  if (!_3gri) {
5914  _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5916  }
5917  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5918  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5919 
5920  // v3: make sure the file has 128 3gnm chunks
5921  // (before updating the Group chunks)
5922  if (pVersion && pVersion->major == 3) {
5923  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5924  for (int i = 0 ; i < 128 ; i++) {
5925  if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5926  if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5927  }
5928  }
5929 
5930  std::list<Group*>::iterator iter = pGroups->begin();
5931  std::list<Group*>::iterator end = pGroups->end();
5932  for (; iter != end; ++iter) {
5933  (*iter)->UpdateChunks(pProgress);
5934  }
5935  }
5936 
5937  // update einf chunk
5938 
5939  // The einf chunk contains statistics about the gig file, such
5940  // as the number of regions and samples used by each
5941  // instrument. It is divided in equally sized parts, where the
5942  // first part contains information about the whole gig file,
5943  // and the rest of the parts map to each instrument in the
5944  // file.
5945  //
5946  // At the end of each part there is a bit map of each sample
5947  // in the file, where a set bit means that the sample is used
5948  // by the file/instrument.
5949  //
5950  // Note that there are several fields with unknown use. These
5951  // are set to zero.
5952 
5953  int sublen = pSamples->size() / 8 + 49;
5954  int einfSize = (Instruments + 1) * sublen;
5955 
5957  if (einf) {
5958  if (einf->GetSize() != einfSize) {
5959  einf->Resize(einfSize);
5960  memset(einf->LoadChunkData(), 0, einfSize);
5961  }
5962  } else if (newFile) {
5963  einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5964  }
5965  if (einf) {
5966  uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5967 
5968  std::map<gig::Sample*,int> sampleMap;
5969  int sampleIdx = 0;
5970  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5971  sampleMap[pSample] = sampleIdx++;
5972  }
5973 
5974  int totnbusedsamples = 0;
5975  int totnbusedchannels = 0;
5976  int totnbregions = 0;
5977  int totnbdimregions = 0;
5978  int totnbloops = 0;
5979  int instrumentIdx = 0;
5980 
5981  memset(&pData[48], 0, sublen - 48);
5982 
5983  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5984  instrument = GetNextInstrument()) {
5985  int nbusedsamples = 0;
5986  int nbusedchannels = 0;
5987  int nbdimregions = 0;
5988  int nbloops = 0;
5989 
5990  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5991 
5992  for (Region* region = instrument->GetFirstRegion() ; region ;
5993  region = instrument->GetNextRegion()) {
5994  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5995  gig::DimensionRegion *d = region->pDimensionRegions[i];
5996  if (d->pSample) {
5997  int sampleIdx = sampleMap[d->pSample];
5998  int byte = 48 + sampleIdx / 8;
5999  int bit = 1 << (sampleIdx & 7);
6000  if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6001  pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6002  nbusedsamples++;
6003  nbusedchannels += d->pSample->Channels;
6004 
6005  if ((pData[byte] & bit) == 0) {
6006  pData[byte] |= bit;
6007  totnbusedsamples++;
6008  totnbusedchannels += d->pSample->Channels;
6009  }
6010  }
6011  }
6012  if (d->SampleLoops) nbloops++;
6013  }
6014  nbdimregions += region->DimensionRegions;
6015  }
6016  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6017  // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6018  store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6019  store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6020  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6021  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6022  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6023  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6024  // next 8 bytes unknown
6025  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6026  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
6027  // next 4 bytes unknown
6028 
6029  totnbregions += instrument->Regions;
6030  totnbdimregions += nbdimregions;
6031  totnbloops += nbloops;
6032  instrumentIdx++;
6033  }
6034  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6035  // store32(&pData[0], sublen);
6036  store32(&pData[4], totnbusedchannels);
6037  store32(&pData[8], totnbusedsamples);
6038  store32(&pData[12], Instruments);
6039  store32(&pData[16], totnbregions);
6040  store32(&pData[20], totnbdimregions);
6041  store32(&pData[24], totnbloops);
6042  // next 8 bytes unknown
6043  // next 4 bytes unknown, not always 0
6044  store32(&pData[40], pSamples->size());
6045  // next 4 bytes unknown
6046  }
6047 
6048  // update 3crc chunk
6049 
6050  // The 3crc chunk contains CRC-32 checksums for the
6051  // samples. The actual checksum values will be filled in
6052  // later, by Sample::Write.
6053 
6055  if (_3crc) {
6056  _3crc->Resize(pSamples->size() * 8);
6057  } else if (newFile) {
6058  _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6059  _3crc->LoadChunkData();
6060 
6061  // the order of einf and 3crc is not the same in v2 and v3
6062  if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6063  }
6064  }
6065 
6068 
6069  for (Instrument* instrument = GetFirstInstrument(); instrument;
6070  instrument = GetNextInstrument())
6071  {
6072  instrument->UpdateScriptFileOffsets();
6073  }
6074  }
6075 
6091  void File::SetAutoLoad(bool b) {
6092  bAutoLoad = b;
6093  }
6094 
6100  return bAutoLoad;
6101  }
6102 
6103 
6104 
6105 // *************** Exception ***************
6106 // *
6107 
6108  Exception::Exception(String Message) : DLS::Exception(Message) {
6109  }
6110 
6112  std::cout << "gig::Exception: " << Message << std::endl;
6113  }
6114 
6115 
6116 // *************** functions ***************
6117 // *
6118 
6125  return PACKAGE;
6126  }
6127 
6133  return VERSION;
6134  }
6135 
6136 } // namespace gig
range_t KeySwitchRange
Key range for key switch selector.
Definition: gig.h:938
bool LFO2FlipPhase
Inverts phase of the filter cutoff LFO wave.
Definition: gig.h:407
void UpdateRegionKeyTable()
Definition: gig.cpp:4466
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:5518
#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:5162
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:2009
#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:649
dim_bypass_ctrl_t DimensionBypass
If defined, the MIDI controller can switch on/off the dimension in realtime.
Definition: gig.h:441
~Instrument()
Destructor.
Definition: gig.cpp:4480
Encapsulates articulation informations of a dimension region.
Definition: gig.h:366
void LoadScripts()
Definition: gig.cpp:4788
range_t DimensionKeyRange
0-127 (where 0 means C1 and 127 means G9)
Definition: gig.h:1091
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:372
#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:424
void SetDimensionType(dimension_t oldType, dimension_t newType)
Change type of an existing dimension.
Definition: gig.cpp:3668
unsigned long FrameOffset
Current offset (sample points) in current sample frame (for decompression only).
Definition: gig.h:677
bool reverse
If playback direction is currently backwards (in case there is a pingpong or reverse loop defined)...
Definition: gig.h:311
uint8_t AltSustain2Key
Key triggering a second set of alternate sustain samples.
Definition: gig.h:890
uint32_t Regions
Reflects the number of Region defintions this Instrument has.
Definition: DLS.h:466
Region * GetRegion(unsigned int Key)
Returns the appropriate Region for a triggered note.
Definition: gig.cpp:4609
void AddSample(Sample *pSample)
Move Sample given by pSample from another Group to this Group.
Definition: gig.cpp:5152
String GetScriptAsText()
Returns the current script (i.e.
Definition: gig.cpp:4146
MidiRuleAlternator * AddMidiRuleAlternator()
Adds the alternator MIDI rule to the instrument.
Definition: gig.cpp:4770
Sample * AddSample()
Add a new sample.
Definition: gig.cpp:5296
bool VCFEnabled
If filter should be used.
Definition: gig.h:418
no SMPTE offset
Definition: gig.h:101
void AddDimension(dimension_def_t *pDimDef)
Einstein would have dreamed of it - create a new dimension.
Definition: gig.cpp:3203
stream_whence_t
File stream position dependent to these relations.
Definition: RIFF.h:159
void LoadScripts()
Definition: gig.cpp:4344
uint32_t FineTune
Specifies the fraction of a semitone up from the specified MIDI unity note field. A value of 0x800000...
Definition: gig.h:637
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:296
uint8_t BypassKey
Key to be used to bypass the sustain note.
Definition: gig.h:883
uint16_t LFO1ControlDepth
Controller depth influencing sample amplitude LFO pitch (0 - 1200 cents).
Definition: gig.h:386
Chunk * GetFirstSubChunk()
Returns the first subchunk within the list.
Definition: RIFF.cpp:1070
lfo1_ctrl_t
Defines how LFO1 is controlled by.
Definition: gig.h:142
Group of Gigasampler samples.
Definition: gig.h:1156
uint32_t LoopType
Defines how the waveform samples will be looped (appropriate loop types for the gig format are define...
Definition: DLS.h:232
uint8_t VCFVelocityDynamicRange
0x04 = lowest, 0x00 = highest .
Definition: gig.h:425
String Name
Stores the name of this Group.
Definition: gig.h:1158
DimensionRegion * GetDimensionRegionByBit(const uint8_t DimBits[8])
Returns the appropriate DimensionRegion for the given dimension bit numbers (zone index)...
Definition: gig.cpp:3848
Special dimension for triggering samples on releasing a key.
Definition: gig.h:229
uint16_t PitchbendRange
Number of semitones pitchbend controller can pitch (default is 2).
Definition: gig.h:1089
double EG1Release
Release time of the sample amplitude EG (0.000 - 60.000s).
Definition: gig.h:377
#define CHUNK_ID_SMPL
Definition: RIFF.h:107
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:895
virtual ~File()
Definition: gig.cpp:5238
#define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)
Definition: gig.cpp:47
uint8_t Triggers
Number of triggers.
Definition: gig.h:841
#define LIST_TYPE_WAVE
Definition: DLS.h:67
#define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)
Definition: gig.cpp:52
#define CHUNK_ID_ISBJ
Definition: DLS.h:81
uint32_t GetChunkID()
Chunk ID in unsigned integer representation.
Definition: RIFF.h:209
vcf_type_t VCFType
Defines the general filter characteristic (lowpass, highpass, bandpass, etc.).
Definition: gig.h:419
Script * AddScript()
Add new instrument script.
Definition: gig.cpp:4314
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:1076
void __ensureMandatoryChunksExist()
Checks if all (for DLS) mandatory chunks exist, if not they will be created.
Definition: DLS.cpp:1855
uint32_t LoopSize
Caution: Use the respective fields in the DimensionRegion instead of this one! (Intended purpose: Len...
Definition: gig.h:645
Instrument * AddInstrument()
Add a new instrument definition.
Definition: gig.cpp:5464
virtual void LoadScriptGroups()
Definition: gig.cpp:5841
Script * GetScript(uint index)
Get instrument script.
Definition: gig.cpp:4295
loop_type_t LoopType
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition: gig.h:642
lfo1_ctrl_t LFO1Controller
MIDI Controller which controls sample amplitude LFO.
Definition: gig.h:387
Group * AddGroup()
Definition: gig.cpp:5689
#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:134
Sample * GetFirstSample()
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: DLS.cpp:1511
uint8_t low
Low value of range.
Definition: gig.h:76
void UpdateChunks(progress_t *pProgress)
Apply this script group to the respective RIFF chunks.
Definition: gig.cpp:4272
uint16_t SampleStartOffset
Number of samples the sample start should be moved (0 - 2000).
Definition: gig.h:450
MIDI rule for triggering notes by control change events.
Definition: gig.h:838
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:1173
void(* callback)(progress_t *)
Callback function pointer which has to be assigned to a function for progress notification.
Definition: RIFF.h:192
#define CHUNK_ID_PTBL
Definition: DLS.h:92
uint8_t Key
Key to trigger.
Definition: gig.h:846
unsigned long GetSize() const
Returns sample size.
Definition: DLS.cpp:858
unsigned long WorstCaseFrameSize
For compressed samples only: size (in bytes) of the largest possible sample frame.
Definition: gig.h:681
#define LIST_TYPE_WVPL
Definition: DLS.h:65
String GetFileName()
Definition: RIFF.cpp:1632
RIFF::List * pCkRegion
Definition: DLS.h:447
void AddScriptSlot(Script *pScript, bool bypass=false)
Add new instrument script slot (gig format extension).
Definition: gig.cpp:4872
bool EG1Hold
If true, Decay1 stage should be postponed until the sample reached the sample loop start...
Definition: gig.h:378
range_t PlayRange
Key range of the playable keys in the instrument.
Definition: gig.h:916
uint16_t ThresholdTime
Maximum time (ms) between two notes that should be played legato.
Definition: gig.h:885
RIFF::Chunk * pCk3gix
Definition: gig.h:685
dimension values are already the sought bit number
Definition: gig.h:266
uint8_t VelocityResponseCurveScaling
0 - 127 (usually you don&#39;t have to interpret this parameter, use GetVelocityAttenuation() instead)...
Definition: gig.h:434
bool Descending
If the change in CC value should be downwards.
Definition: gig.h:844
Group * GetGroup() const
Returns pointer to the Group this Sample belongs to.
Definition: gig.cpp:1336
double GetVelocityCutoff(uint8_t MIDIKeyVelocity)
Definition: gig.cpp:2771
unsigned long Size
Size of the actual data in the buffer in bytes.
Definition: gig.h:83
Instrument * GetFirstInstrument()
Returns a pointer to the first Instrument object of the file, NULL otherwise.
Definition: gig.cpp:5407
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:215
#define CHUNK_ID_ICMT
Definition: RIFF.h:99
void ReadString(String &s, int size)
Reads a null-padded string of size characters and copies it into the string s.
Definition: RIFF.cpp:628
#define CHUNK_ID_ISFT
Definition: RIFF.h:105
Region * RegionKeyTable[128]
fast lookup for the corresponding Region of a MIDI key
Definition: gig.h:1121
uint8_t ReleaseTriggerKey
Key triggering release samples.
Definition: gig.h:888
Sample(File *pFile, RIFF::List *waveList, unsigned long WavePoolOffset, unsigned long fileNo=0)
Constructor.
Definition: gig.cpp:338
#define CHUNK_ID_3EWA
Definition: gig.h:56
uint32_t * pWavePoolTable
Definition: DLS.h:530
For MIDI tools like legato and repetition mode.
Definition: gig.h:233
bool VCFKeyboardTracking
If true: VCF cutoff frequence will be dependend to the note key position relative to the defined brea...
Definition: gig.h:429
#define CHUNK_ID_IMED
Definition: DLS.h:80
uint32_t WavePoolTableIndex
Definition: DLS.h:448
uint8_t Velocity
Velocity of the note to trigger. 255 means that velocity should depend on the speed of the controller...
Definition: gig.h:848
void CopyAssignWave(const Sample *orig)
Should be called after CopyAssignMeta() and File::Save() sequence.
Definition: gig.cpp:476
Defines a controller that has a certain contrained influence on a particular synthesis parameter (use...
Definition: gig.h:183
#define CHUNK_ID_IPRD
Definition: RIFF.h:104
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:398
uint8_t Controller
CC number for controller selector.
Definition: gig.h:939
void SetVCFVelocityScale(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2860
RIFF::List * pCkInstrument
Definition: DLS.h:481
Defines Region information of a Gigasampler/GigaStudio instrument.
Definition: gig.h:741
#define GIG_EXP_ENCODE(x)
Definition: gig.cpp:42
uint32_t SamplerOptions
Definition: DLS.h:382
void UpdateVelocityTable()
Definition: gig.cpp:3118
unsigned long SamplesPerFrame
For compressed samples only: number of samples in a full sample frame.
Definition: gig.h:682
uint32_t LoopPlayCount
Number of times the loop should be played (a value of 0 = infinite).
Definition: gig.h:647
uint8_t ReleaseTriggerDecay
0 - 8
Definition: gig.h:437
lfo3_ctrl_t LFO3Controller
MIDI Controller which controls the sample pitch LFO.
Definition: gig.h:415
static unsigned int Instances
Number of instances of class Sample.
Definition: gig.h:674
bool Chained
If all patterns should be chained together.
Definition: gig.h:942
uint32_t MIDIUnityNote
Specifies the musical note at which the sample will be played at it&#39;s original sample rate...
Definition: gig.h:636
uint8_t ControllerNumber
MIDI controller number.
Definition: gig.h:840
Sampler(RIFF::List *ParentList)
Definition: DLS.cpp:550
#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:1045
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
Definition: RIFF.cpp:1297
uint8_t ChannelOffset
Audio output where the audio signal of the dimension region should be routed to (0 - 9)...
Definition: gig.h:447
void Resize(int iNewSize)
Resize sample.
Definition: gig.cpp:796
Defines Sample Loop Points.
Definition: DLS.h:230
Region * GetParent() const
Definition: gig.cpp:2087
uint8_t VCFResonance
Firm internal filter resonance weight.
Definition: gig.h:426
bool VCFResonanceDynamic
If true: Increases the resonance Q according to changes of controllers that actually control the VCF ...
Definition: gig.h:427
void DeleteMidiRule(int i)
Deletes a MIDI rule from the instrument.
Definition: gig.cpp:4783
unsigned int Dimensions
Number of defined dimensions, do not alter!
Definition: gig.h:743
Only controlled by external modulation wheel.
Definition: gig.h:126
#define GIG_VCF_RESONANCE_CTRL_ENCODE(x)
Definition: gig.cpp:46
#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:420
#define CHUNK_HEADER_SIZE
Definition: RIFF.h:111
virtual void SetGain(int32_t gain)
Definition: DLS.cpp:586
MidiRuleCtrlTrigger * AddMidiRuleCtrlTrigger()
Adds the "controller trigger" MIDI rule to the instrument.
Definition: gig.cpp:4744
unsigned long RemainingBytes()
Returns the number of bytes left to read in the chunk body.
Definition: RIFF.cpp:247
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:373
List * GetFirstSubList()
Returns the first sublist within the list (that is a subchunk with chunk ID "LIST").
Definition: RIFF.cpp:1104
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:3739
void UpdateScriptFileOffsets()
Definition: gig.cpp:4582
lfo2_ctrl_t LFO2Controller
MIDI Controlle which controls the filter cutoff LFO.
Definition: gig.h:406
RIFF::List * pParentList
Definition: DLS.h:380
void LoadDimensionRegions(RIFF::List *rgn)
Definition: gig.cpp:3095
Different samples triggered each time a note is played, any key advances the counter.
Definition: gig.h:234
bool Dithered
For 24-bit compressed samples only: if dithering was used during compression with bit reduction...
Definition: gig.h:650
Region * GetFirstRegion()
Returns the first Region of the instrument.
Definition: gig.cpp:4627
String libraryVersion()
Returns version of this C++ library.
Definition: gig.cpp:6132
#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:368
uint8_t ReleaseVelocityResponseDepth
Dynamic range of release velocity affecting envelope time (0 - 4).
Definition: gig.h:436
RIFF::List * pParentList
Definition: DLS.h:296
void RemoveAllScriptReferences()
Definition: gig.cpp:4228
std::list< Sample * > SampleList
Definition: DLS.h:519
Will be thrown whenever a gig specific error occurs while trying to access a Gigasampler File...
Definition: gig.h:1289
buffer_t LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount)
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition: gig.cpp:685
void UpdateChunks(progress_t *pProgress)
Apply this script to the respective RIFF chunks.
Definition: gig.cpp:4173
InstrumentList::iterator InstrumentsIterator
Definition: DLS.h:527
Instrument(File *pFile, RIFF::List *insList, progress_t *pProgress=NULL)
Definition: gig.cpp:4361
void GenerateDLSID()
Generates a new DLSID for the resource.
Definition: DLS.cpp:495
uint8_t in_end
End position of fade in.
Definition: gig.h:302
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:2833
unsigned long WorstCaseMaxSamples(buffer_t *pDecompressionBuffer)
Definition: gig.h:710
static const DLS::version_t VERSION_2
Reflects Gigasampler file format version 2.0 (1998-06-28).
Definition: gig.h:1212
Sample * pSample
Points to the Sample which is assigned to the dimension region.
Definition: gig.h:369
uint FrameSize
Reflects the size (in bytes) of one single sample point (only if known sample data format is used...
Definition: DLS.h:404
buffer_t LoadSampleData()
Loads (and uncompresses if needed) the whole sample wave into RAM.
Definition: gig.cpp:636
uint16_t ReleaseTime
Release time.
Definition: gig.h:886
uint32_t LoopStart
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: The ...
Definition: gig.h:643
Group * GetNextGroup()
Returns a pointer to the next Group object of the file, NULL otherwise.
Definition: gig.cpp:5649
Loop forward (normal)
Definition: gig.h:94
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:611
void SetVCFVelocityCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2842
#define CHUNK_ID_IENG
Definition: RIFF.h:102
double EG2Decay1
Decay time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:393
#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:381
unsigned long GetPos()
Position within the chunk data body.
Definition: RIFF.h:214
#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:310
String pArticulations[32]
Names of the articulations.
Definition: gig.h:914
crossfade_t Crossfade
Definition: gig.h:439
Compression_t
Definition: gig.h:996
void SetAutoLoad(bool b)
Enable / disable automatic loading.
Definition: gig.cpp:6091
MidiRule * GetMidiRule(int i)
Returns a MIDI rule of the instrument.
Definition: gig.cpp:4735
smpte_format_t SMPTEFormat
Specifies the Society of Motion Pictures and Television E time format used in the following SMPTEOffs...
Definition: gig.h:638
uint16_t low
Low value of range.
Definition: DLS.h:206
double SampleAttenuation
Sample volume (calculated from DLS::Sampler::Gain)
Definition: gig.h:451
File()
Definition: gig.cpp:5214
lfo3_ctrl_t
Defines how LFO3 is controlled by.
Definition: gig.h:124
bool b64BitWavePoolOffsets
Definition: DLS.h:532
RIFF List Chunk.
Definition: RIFF.h:302
#define CHUNK_ID_WSMP
Definition: DLS.h:93
double EG1Decay2
Only if EG1InfiniteSustain == false: 2nd decay stage time of the sample amplitude EG (0...
Definition: gig.h:374
bool PianoReleaseMode
Definition: gig.h:1090
RIFF::Chunk * pCkData
Definition: DLS.h:417
#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:296
void RemoveScript(Script *pScript)
Remove reference to given Script (gig format extension).
Definition: gig.cpp:4925
RegionList * pRegions
Definition: DLS.h:482
uint8_t BypassController
Controller to be used to bypass the sustain note.
Definition: gig.h:884
attenuation_ctrl_t AttenuationController
MIDI Controller which has influence on the volume level of the sample (or entire sample group)...
Definition: gig.h:444
static buffer_t InternalDecompressionBuffer
Buffer used for decompression as well as for truncation of 24 Bit -> 16 Bit samples.
Definition: gig.h:675
static void DestroyDecompressionBuffer(buffer_t &DecompressionBuffer)
Free decompression buffer, previously created with CreateDecompressionBuffer().
Definition: gig.cpp:1319
Pointer address and size of a buffer.
Definition: gig.h:81
virtual void LoadSamples()
Definition: gig.cpp:5347
friend class ScriptGroup
Definition: gig.h:1273
uint8_t in_start
Start position of fade in.
Definition: gig.h:301
uint8_t Patterns
Number of alternator patterns.
Definition: gig.h:918
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:1070
dimension_t dimension
Specifies which source (usually a MIDI controller) is associated with the dimension.
Definition: gig.h:271
range_t KeyRange
Key range for legato notes.
Definition: gig.h:887
friend class Sample
Definition: gig.h:1270
unsigned long SamplesInLastFrame
For compressed samples only: length of the last sample frame.
Definition: gig.h:680
bool EG2ControllerInvert
Invert values coming from defined EG2 controller.
Definition: gig.h:399
uint8_t Articulations
Number of articulations in the instrument.
Definition: gig.h:913
friend class Region
Definition: gig.h:1130
Group * GetFirstGroup()
Returns a pointer to the first Group object of the file, NULL otherwise.
Definition: gig.cpp:5642
Group * GetGroup(uint index)
Returns the group with the given index.
Definition: gig.cpp:5661
uint8_t VelSensitivity
How sensitive the velocity should be to the speed of the controller change.
Definition: gig.h:845
#define LIST_TYPE_3GRI
Definition: gig.h:51
uint32_t DimensionRegions
Total number of DimensionRegions this Region contains, do not alter!
Definition: gig.h:745
Instrument * AddDuplicateInstrument(const Instrument *orig)
Add a duplicate of an existing instrument.
Definition: gig.cpp:5501
std::string String
Definition: gig.h:71
uint ScriptSlotCount() const
Instrument&#39;s amount of script slots.
Definition: gig.cpp:4948
bool MSDecode
Gigastudio flag: defines if Mid Side Recordings should be decoded.
Definition: gig.h:449
Key Velocity (this is the only dimension in gig2 where the ranges can exactly be defined).
Definition: gig.h:227
bool EG1InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released...
Definition: gig.h:375
bool Compressed
If the sample wave is compressed (probably just interesting for instrument and sample editors...
Definition: gig.h:648
void ReleaseSampleData()
Frees the cached sample from RAM if loaded with LoadSampleData() previously.
Definition: gig.cpp:759
uint32_t SampleLoops
Reflects the number of sample loops.
Definition: DLS.h:371
More poles than normal lowpass.
Definition: gig.h:281
virtual void Save(const String &Path, progress_t *pProgress=NULL)
Save changes to another file.
Definition: DLS.cpp:1787
Resource * pParent
Definition: DLS.h:356
uint16_t LFO2InternalDepth
Firm pitch of the filter cutoff LFO (0 - 1200 cents).
Definition: gig.h:404
void Resize(int iNewSize)
Resize sample.
Definition: DLS.cpp:891
SampleList * pSamples
Definition: DLS.h:524
#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:3405
uint16_t LFO1InternalDepth
Firm pitch of the sample amplitude LFO (0 - 1200 cents).
Definition: gig.h:385
#define CHUNK_ID_3CRC
Definition: gig.h:62
The difference between none and none2 is unknown.
Definition: gig.h:153
virtual void LoadInstruments()
Definition: gig.cpp:5586
float zone_size
Intended for internal usage: reflects the size of each zone (128/zones) for normal split types only...
Definition: gig.h:275
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition: gig.cpp:6066
String Message
Definition: RIFF.h:408
bool PitchTrack
If true: sample will be pitched according to the key position (this will be disabled for drums for ex...
Definition: gig.h:440
double GetVelocityRelease(uint8_t MIDIKeyVelocity)
Definition: gig.cpp:2767
#define CHUNK_ID_LSNM
Definition: gig.h:64
unsigned long Write(void *pBuffer, unsigned long SampleCount)
Write sample wave data.
Definition: gig.cpp:1259
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:574
Encoding_t
Definition: gig.h:993
uint16_t high
High value of range.
Definition: DLS.h:207
friend class Instrument
Definition: gig.h:1271
bool BypassUseController
If a controller should be used to bypass the sustain note.
Definition: gig.h:882
float __range_min
Only for internal usage, do not modify!
Definition: RIFF.h:195
unsigned int Layers
Amount of defined layers (1 - 32). A value of 1 actually means no layering, a value > 1 means there i...
Definition: gig.h:747
void * pStart
Points to the beginning of the buffer.
Definition: gig.h:82
bool EG2InfiniteSustain
If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released...
Definition: gig.h:395
Region * AddRegion()
Definition: gig.cpp:4647
unsigned long SamplePos
For compressed samples only: stores the current position (in sample points).
Definition: gig.h:679
Group * pGroup
pointer to the Group this sample belongs to (always not-NULL)
Definition: gig.h:676
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition: RIFF.cpp:1026
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:1086
MidiRuleLegato * AddMidiRuleLegato()
Adds the legato MIDI rule to the instrument.
Definition: gig.cpp:4757
std::list< Instrument * > InstrumentList
Definition: DLS.h:520
uint8_t EG2ControllerAttackInfluence
Amount EG2 Controller has influence on the EG2 Attack time (0 - 3, where 0 means off).
Definition: gig.h:400
Exception(String Message)
Definition: gig.cpp:6108
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:443
#define CHUNK_ID_ICRD
Definition: RIFF.h:101
#define LIST_TYPE_RTIS
Definition: gig.h:54
int16_t LFO3ControlDepth
Controller depth of the sample pitch LFO (-1200 - +1200 cents).
Definition: gig.h:414
RIFF::Chunk * pCkSmpl
Definition: gig.h:686
#define GET_PARAMS(params)
void RemoveScriptSlot(uint index)
Remove script slot.
Definition: gig.cpp:4907
double EG3Attack
Attack time of the sample pitch EG (0.000 - 10.000s).
Definition: gig.h:410
void DeleteDimension(dimension_def_t *pDimDef)
Delete an existing dimension.
Definition: gig.cpp:3315
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:3965
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:4014
#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:5414
unsigned long SamplesTotal
Reflects total number of sample points (only if known sample data format is used, 0 otherwise)...
Definition: DLS.h:403
uint8_t LegatoSamples
Number of legato samples per key in each direction (always 12)
Definition: gig.h:881
uint8_t out_end
End postition of fade out.
Definition: gig.h:304
void DeleteGroupOnly(Group *pGroup)
Delete a group.
Definition: gig.cpp:5731
double EG2Attack
Attack time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:392
uint16_t BitDepth
Size of each sample per channel (only if known sample data format is used, 0 otherwise).
Definition: DLS.h:402
bool InvertAttenuationController
Inverts the values coming from the defined Attenuation Controller.
Definition: gig.h:445
double LFO1Frequency
Frequency of the sample amplitude LFO (0.10 - 10.00 Hz).
Definition: gig.h:384
Ordinary RIFF Chunk.
Definition: RIFF.h:205
uint32_t GetListType()
Returns unsigned integer representation of the list&#39;s ID.
Definition: RIFF.h:306
DimensionRegion(Region *pParent, RIFF::List *_3ewl)
Definition: gig.cpp:1359
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:641
uint16_t EffectSend
Definition: gig.h:1087
#define CHUNK_ID_ICMS
Definition: DLS.h:77
bool LFO1FlipPhase
Inverts phase of the sample amplitude LFO wave.
Definition: gig.h:388
uint8_t AltSustain1Key
Key triggering alternate sustain samples.
Definition: gig.h:889
void DeleteSample(Sample *pSample)
Delete a sample.
Definition: gig.cpp:5321
unsigned long GetFilePos()
Current, actual offset in file.
Definition: RIFF.h:215
int16_t FineTune
in cents
Definition: gig.h:1088
Region(Instrument *pInstrument, RIFF::List *rgnList)
Definition: gig.cpp:2936
static buffer_t CreateDecompressionBuffer(unsigned long MaxReadSize)
Allocates a decompression buffer for streaming (compressed) samples with Sample::Read().
Definition: gig.cpp:1302
#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:416
#define CHUNK_ID_INAM
Definition: RIFF.h:103
bool IsScriptSlotBypassed(uint index)
Whether script execution shall be skipped.
Definition: gig.cpp:4968
double LFO3Frequency
Frequency of the sample pitch LFO (0.10 - 10.00 Hz).
Definition: gig.h:412
static const DLS::version_t VERSION_3
Reflects Gigasampler file format version 3.0 (2003-03-31).
Definition: gig.h:1213
uint32_t LoopLength
Length of the looping area (in sample points).
Definition: DLS.h:234
void DeleteRegion(Region *pRegion)
Definition: gig.cpp:4661
#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:4251
ScriptGroup * AddScriptGroup()
Add new instrument script group.
Definition: gig.cpp:5808
#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:746
#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:634
bool LFO1Sync
If set to true only one LFO should be used for all voices.
Definition: gig.h:389
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:500
split_type_t
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition: gig.h:264
Alternating loop (forward/backward, also known as Ping Pong)
Definition: gig.h:95
ScriptGroup * GetScriptGroup(uint index)
Get instrument script group (by index).
Definition: gig.cpp:5776
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:312
~Sample()
Destructor.
Definition: gig.cpp:1340
void SetSampleChecksum(Sample *pSample, uint32_t crc)
Updates the 3crc chunk with the checksum of a sample.
Definition: gig.cpp:5619
Sample * GetNextSample()
Returns the next Sample of the Group.
Definition: gig.cpp:5141
uint8_t EG2ControllerReleaseInfluence
Amount EG2 Controller has influence on the EG2 Release time (0 - 3, where 0 means off)...
Definition: gig.h:402
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:359
Used for indicating the progress of a certain task.
Definition: RIFF.h:191
SampleList::iterator SamplesIterator
Definition: DLS.h:525
List * GetParent()
Returns pointer to the chunk&#39;s parent list chunk.
Definition: RIFF.h:211
uint16_t EG2PreAttack
Preattack value of the filter cutoff EG (0 - 1000 permille).
Definition: gig.h:391
Chunk * AddSubChunk(uint32_t uiChunkID, uint uiBodySize)
Creates a new sub chunk.
Definition: RIFF.cpp:1206
uint32_t Loops
Caution: Use the respective field in the DimensionRegion instead of this one! (Intended purpose: Numb...
Definition: gig.h:640
bool LFO2Sync
If set to true only one LFO should be used for all voices.
Definition: gig.h:408
uint32_t SMPTEOffset
The SMPTE Offset value specifies the time offset to be used for the synchronization / calibration to ...
Definition: gig.h:639
unsigned long FileNo
File number (> 0 when sample is stored in an extension file, 0 when it&#39;s in the gig) ...
Definition: gig.h:684
void SplitDimensionZone(dimension_t type, int zone)
Divide split zone of a dimension in two (increment zone amount).
Definition: gig.cpp:3529
Sample * GetFirstSample(progress_t *pProgress=NULL)
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: gig.cpp:5259
bool EG1ControllerInvert
Invert values coming from defined EG1 controller.
Definition: gig.h:380
friend class Group
Definition: gig.h:1272
Ordinary MIDI control change controller, see field &#39;controller_number&#39;.
Definition: gig.h:188
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition: DLS.cpp:1307
vcf_type_t
Defines which frequencies are filtered by the VCF.
Definition: gig.h:279
version_t * pVersion
Points to a version_t structure if the file provided a version number else is set to NULL...
Definition: DLS.h:498
void DeleteInstrument(Instrument *pInstrument)
Delete an instrument.
Definition: gig.cpp:5578
uint16_t LFO2ControlDepth
Controller depth influencing filter cutoff LFO pitch (0 - 1200).
Definition: gig.h:405
uint32_t LoopStart
The start value specifies the offset (in sample points) in the waveform data of the first sample poin...
Definition: DLS.h:233
virtual void UpdateChunks(progress_t *pProgress)
Update chunks with current group settings.
Definition: gig.cpp:5088
uint16_t major
Definition: DLS.h:112
RegionList::iterator RegionsIterator
Definition: DLS.h:483
int GetDimensionRegionIndexByValue(const uint DimValues[8])
Definition: gig.cpp:3788
Loop backward (reverse)
Definition: gig.h:96
int16_t EG3Depth
Depth of the sample pitch EG (-1200 - +1200).
Definition: gig.h:411
bool GetAutoLoad()
Returns whether automatic loading is enabled.
Definition: gig.cpp:6099
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:4074
uint8_t VCFKeyboardTrackingBreakpoint
See VCFKeyboardTracking (0 - 127).
Definition: gig.h:430
eg2_ctrl_t EG2Controller
MIDI Controller which has influence on filter cutoff EG parameters (attack, decay, release).
Definition: gig.h:398
#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:226
void * LoadChunkData()
Load chunk body into RAM.
Definition: RIFF.cpp:774
bool VCFCutoffControllerInvert
Inverts values coming from the defined cutoff controller.
Definition: gig.h:421
Different samples triggered each time a note is played, random order.
Definition: gig.h:232
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
#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:4892
double EG2Release
Release time of the filter cutoff EG (0.000 - 60.000s).
Definition: gig.h:397
uint8_t EG1ControllerReleaseInfluence
Amount EG1 Controller has influence on the EG1 Release time (0 - 3, where 0 means off)...
Definition: gig.h:383
#define CHUNK_ID_IART
Definition: DLS.h:76
uint8_t EG2ControllerDecayInfluence
Amount EG2 Controller has influence on the EG2 Decay time (0 - 3, where 0 means off).
Definition: gig.h:401
~Region()
Destructor.
Definition: gig.cpp:3715
bool Polyphonic
If alternator should step forward only when all notes are off.
Definition: gig.h:941
Abstract base class for all MIDI rules.
Definition: gig.h:817
ScriptGroup * GetGroup() const
Returns the script group this script currently belongs to.
Definition: gig.cpp:4224
void SetVelocityResponseCurveScaling(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2803
virtual void UpdateChunks(progress_t *pProgress)
Apply all the gig file&#39;s current instruments, samples, groups and settings to the respective RIFF chu...
Definition: gig.cpp:5867
#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:223
ScriptGroup(File *file, RIFF::List *lstRTIS)
Definition: gig.cpp:4239
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:644
curve_type_t ReleaseVelocityResponseCurve
Defines a transformation curve to the incoming release veloctiy values affecting envelope times...
Definition: gig.h:435
Different samples triggered each time a note is played, dimension regions selected in sequence...
Definition: gig.h:231
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:744
#define CHUNK_ID_COLH
Definition: DLS.h:94
uint8_t zones
Number of zones the dimension has.
Definition: gig.h:273
Effect 5 Depth (MIDI Controller 95)
Definition: gig.h:120
#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:446
#define CHUNK_ID_ICOP
Definition: RIFF.h:100
RIFF::File * pRIFF
Definition: DLS.h:522
buffer_t GetCache()
Returns current cached sample points.
Definition: gig.cpp:744
void SetVCFVelocityDynamicRange(uint8_t range)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2851
vcf_cutoff_ctrl_t
Defines how the filter cutoff frequency is controlled by.
Definition: gig.h:151
No controller defined.
Definition: gig.h:185
Encapsulates sample waves of Gigasampler/GigaStudio files used for playback.
Definition: gig.h:631
virtual void SetGain(int32_t gain)
Updates the respective member variable and updates SampleAttenuation which depends on this value...
Definition: gig.cpp:1713
RIFF File.
Definition: RIFF.h:351
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
Definition: RIFF.cpp:1277
Group(File *file, RIFF::Chunk *ck3gnm)
Constructor.
Definition: gig.cpp:5067
InstrumentList * pInstruments
Definition: DLS.h:526
unsigned long GuessSize(unsigned long samples)
Definition: gig.h:693
virtual void UpdateChunks(progress_t *pProgress)
Apply all sample player options to the respective RIFF chunk.
Definition: DLS.cpp:596
dimension value between 0-127
Definition: gig.h:265
unsigned long GetSize() const
Chunk size in bytes (without header, thus the chunk data body)
Definition: RIFF.h:212
int16_t LFO3InternalDepth
Firm depth of the sample pitch LFO (-1200 - +1200 cents).
Definition: gig.h:413
virtual void UpdateChunks(progress_t *pProgress)
Apply dimension region settings to the respective RIFF chunks.
Definition: gig.cpp:1727
String Software
<ISFT-ck>. Identifies the name of the sofware package used to create the file.
Definition: DLS.h:318
String ArchivalLocation
<IARL-ck>. Indicates where the subject of the file is stored.
Definition: DLS.h:308
Sample * GetNextSample()
Returns a pointer to the next Sample object of the file, NULL otherwise.
Definition: gig.cpp:5266
unsigned long ulWavePoolOffset
Definition: DLS.h:419
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:394
int32_t Attenuation
in dB
Definition: gig.h:1086
Encapsulates sample waves used for playback.
Definition: DLS.h:395
virtual void UpdateChunks(progress_t *pProgress)
Apply Instrument with all its Regions to the respective RIFF chunks.
Definition: gig.cpp:4498
type_t type
Controller type.
Definition: gig.h:191
uint controller_number
MIDI controller number if this controller is a control change controller, 0 otherwise.
Definition: gig.h:192
uint8_t * VelocityTable
For velocity dimensions with custom defined zone ranges only: used for fast converting from velocity ...
Definition: gig.h:483
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
Definition: RIFF.cpp:1229
uint32_t SamplesPerSecond
Sampling rate at which each channel should be played (defaults to 44100 if Sample was created with In...
Definition: DLS.h:399
curve_type_t VelocityResponseCurve
Defines a transformation curve to the incoming velocity values affecting amplitude (usually you don&#39;t...
Definition: gig.h:432
A MIDI rule not yet implemented by libgig.
Definition: gig.h:964
void PrintMessage()
Definition: gig.cpp:6111
uint16_t EG1Sustain
Sustain value of the sample amplitude EG (0 - 1000 permille).
Definition: gig.h:376
Sample * GetSample(uint index)
Returns Sample object of index.
Definition: gig.cpp:5277
uint32_t WavePoolCount
Definition: DLS.h:529
String GetFileName()
File name of this DLS file.
Definition: DLS.cpp:1675
Real-time instrument script (gig format extension).
Definition: gig.h:991
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:84
#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:2791
RIFF::List * pWaveList
Definition: DLS.h:416
Sample * GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t *pProgress=NULL)
Definition: gig.cpp:3872
Gigasampler/GigaStudio specific classes and definitions.
Definition: gig.h:69
float __range_max
Only for internal usage, do not modify!
Definition: RIFF.h:196
uint8_t DimensionUpperLimits[8]
gig3: defines the upper limit of the dimension values for this dimension region. In case you wondered...
Definition: gig.h:452
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:1655
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings and all its DimensionRegions to the respective RIFF chunks. ...
Definition: gig.cpp:3030
uint8_t TriggerPoint
The CC value to pass for the note to be triggered.
Definition: gig.h:843
uint8_t VelocityResponseDepth
Dynamic range of velocity affecting amplitude (0 - 4) (usually you don&#39;t have to interpret this param...
Definition: gig.h:433
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:646
uint32_t TruncatedBits
For 24-bit compressed samples only: number of bits truncated during compression (0, 4 or 6)
Definition: gig.h:649
Instrument * GetInstrument(uint index, progress_t *pProgress=NULL)
Returns the instrument with the given index.
Definition: gig.cpp:5427
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:537
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:769
#define LIST_TYPE_LINS
Definition: DLS.h:68
Resource * GetParent()
Definition: DLS.h:350
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:1038
Language_t
Definition: gig.h:999
int8_t Pan
Panorama / Balance (-64..0..63 <-> left..middle..right)
Definition: gig.h:442
Only internally controlled.
Definition: gig.h:143
Provides convenient access to Gigasampler/GigaStudio .gig files.
Definition: gig.h:1210
void DeleteRegion(Region *pRegion)
Definition: DLS.cpp:1291
void SetGroup(ScriptGroup *pGroup)
Move this script from its current ScriptGroup to another ScriptGroup given by pGroup.
Definition: gig.cpp:4211
lfo2_ctrl_t
Defines how LFO2 is controlled by.
Definition: gig.h:133
Dimension for keyswitching.
Definition: gig.h:230
Sample * pSample
Definition: DLS.h:449
#define LIST_TYPE_INFO
Definition: RIFF.h:98
MIDI rule for instruments with legato samples.
Definition: gig.h:879
virtual ~Group()
Definition: gig.cpp:5073
void SetReleaseVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2824
range_t KeyRange
Definition: DLS.h:431
#define CHUNK_ID_ISRC
Definition: DLS.h:82
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
Definition: DLS.cpp:968
Sample * GetFirstSample()
Returns the first Sample of this Group.
Definition: gig.cpp:5123
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:3708
uint16_t EG2Sustain
Sustain value of the filter cutoff EG (0 - 1000 permille).
Definition: gig.h:396
uint32_t Instruments
Reflects the number of available Instrument objects.
Definition: DLS.h:499
Provides all neccessary information for the synthesis of a DLS Instrument.
Definition: DLS.h:459
Provides access to a Gigasampler/GigaStudio instrument.
Definition: gig.h:1073
void SetScriptSlotBypassed(uint index, bool bBypass)
Defines whether execution shall be skipped.
Definition: gig.cpp:4988
void DeleteGroup(Group *pGroup)
Delete a group and its samples.
Definition: gig.cpp:5707
bool SustainDefeat
If true: Sustain pedal will not hold a note.
Definition: gig.h:448
buffer_t RAMCache
Buffers samples (already uncompressed) in RAM.
Definition: gig.h:683
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:5005
bool NoteOff
If a note off should be triggered instead of a note on.
Definition: gig.h:847
String libraryName()
Returns the name of this C++ library.
Definition: gig.cpp:6124
unsigned long GetPos() const
Returns the current position in the sample (in sample points).
Definition: gig.cpp:856
int32_t Gain
Definition: DLS.h:368
virtual void LoadGroups()
Definition: gig.cpp:5742
Quadtuple version number ("major.minor.release.build").
Definition: DLS.h:110
#define SKIP_ONE(x)
void MoveTo(Instrument *dst)
Move this instrument at the position before.
Definition: gig.cpp:4695
double LFO2Frequency
Frequency of the filter cutoff LFO (0.10 - 10.00 Hz).
Definition: gig.h:403
unsigned long GetNewSize()
New chunk size if it was modified with Resize().
Definition: RIFF.h:213
uint32_t SamplePeriod
Specifies the duration of time that passes during the playback of one sample in nanoseconds (normally...
Definition: gig.h:635
uint16_t EG1PreAttack
Preattack value of the sample amplitude EG (0 - 1000 permille).
Definition: gig.h:371
Script * GetScriptOfSlot(uint index)
Get instrument script (gig format extension).
Definition: gig.cpp:4831
Dimension not in use.
Definition: gig.h:224
unsigned long * FrameTable
For positioning within compressed samples only: stores the offset values for each frame...
Definition: gig.h:678
void CopyAssignCore(const Instrument *orig)
Definition: DLS.cpp:1359
curve_type_t
Defines the shape of a function graph.
Definition: gig.h:109
uint8_t bits
Number of "bits" (1 bit = 2 splits/zones, 2 bit = 4 splits/zones, 3 bit = 8 splits/zones,...).
Definition: gig.h:272
selector_t Selector
Method by which pattern is chosen.
Definition: gig.h:937
uint8_t out_start
Start position of fade out.
Definition: gig.h:303
uint8_t VCFCutoff
Max. cutoff frequency.
Definition: gig.h:422
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:3111
DLS specific classes and definitions.
Definition: DLS.h:104
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:822
Info * pInfo
Points (in any case) to an Info object, providing additional, optional infos and comments.
Definition: DLS.h:347
uint32_t Manufacturer
Specifies the MIDI Manufacturer&#39;s Association (MMA) Manufacturer code for the sampler intended to rec...
Definition: gig.h:633
uint8_t high
High value of range.
Definition: gig.h:77
bool OverridePedal
If a note off should be triggered even if the sustain pedal is down.
Definition: gig.h:849
MIDI rule to automatically cycle through specified sequences of different articulations.
Definition: gig.h:911
Reflects the current playback state for a sample.
Definition: gig.h:309
General dimension definition.
Definition: gig.h:270
int Size
Number of steps in the pattern.
Definition: gig.h:921
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:440
eg1_ctrl_t EG1Controller
MIDI Controller which has influence on sample amplitude EG parameters (attack, decay, release).
Definition: gig.h:379
uint32_t * pWavePoolTableHi
Definition: DLS.h:531
virtual void UpdateChunks(progress_t *pProgress)
Apply Region settings to the respective RIFF chunks.
Definition: DLS.cpp:1111
split_type_t split_type
Intended for internal usage: will be used to convert a dimension value into the corresponding dimensi...
Definition: gig.h:274
void DeleteScript(Script *pScript)
Delete an instrument script.
Definition: gig.cpp:4331
If used sample has more than one channel (thus is not mono).
Definition: gig.h:225
void Resize(int iNewSize)
Resize chunk.
Definition: RIFF.cpp:843
virtual void UpdateChunks(progress_t *pProgress)
Apply sample and its settings to the respective RIFF chunks.
Definition: gig.cpp:504
void SetReleaseVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2815
vcf_res_ctrl_t VCFResonanceController
Specifies which external controller has influence on the filter resonance Q.
Definition: gig.h:428
curve_type_t VCFVelocityCurve
Defines a transformation curve for the incoming velocity values, affecting the VCF.
Definition: gig.h:423
#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:382
List * GetNextSubList()
Returns the next sublist (that is a subchunk with chunk ID "LIST") within the list.
Definition: RIFF.cpp:1126
Defines Region information of an Instrument.
Definition: DLS.h:429
Effect 4 Depth (MIDI Controller 94)
Definition: gig.h:119
double GetVelocityAttenuation(uint8_t MIDIKeyVelocity)
Returns the correct amplitude factor for the given MIDIKeyVelocity.
Definition: gig.cpp:2763
std::list< RIFF::File * > ExtensionFiles
Definition: DLS.h:523
Sample * GetSample()
Returns pointer address to the Sample referenced with this region.
Definition: gig.cpp:3867
void SetVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2779
#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:372
void DeleteScriptGroup(ScriptGroup *pGroup)
Delete an instrument script group.
Definition: gig.cpp:5827
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:426
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:463
std::list< Region * > RegionList
Definition: DLS.h:475
Region * GetNextRegion()
Returns the next Region of the instrument.
Definition: gig.cpp:4641
#define CHUNK_ID_SCRI
Definition: gig.h:63
virtual void UpdateChunks(progress_t *pProgress)
Apply all the DLS file&#39;s current instruments, samples and settings to the respective RIFF chunks...
Definition: DLS.cpp:1695
virtual void UpdateFileOffsets()
Updates all file offsets stored all over the file.
Definition: DLS.cpp:1846
#define COPY_ONE(x)
#define CHUNK_ID_EWAV
Definition: gig.h:59