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  double* table;
2049  uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
2050  if (pVelocityTables->count(tableKey)) { // if key exists
2051  table = (*pVelocityTables)[tableKey];
2052  }
2053  else {
2054  table = CreateVelocityTable(curveType, depth, scaling);
2055  (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
2056  }
2057  return table;
2058  }
2059 
2061  return pRegion;
2062  }
2063 
2064 // show error if some _lev_ctrl_* enum entry is not listed in the following function
2065 // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2066 // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2067 //#pragma GCC diagnostic push
2068 //#pragma GCC diagnostic error "-Wswitch"
2069 
2070  leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2071  leverage_ctrl_t decodedcontroller;
2072  switch (EncodedController) {
2073  // special controller
2074  case _lev_ctrl_none:
2075  decodedcontroller.type = leverage_ctrl_t::type_none;
2076  decodedcontroller.controller_number = 0;
2077  break;
2078  case _lev_ctrl_velocity:
2079  decodedcontroller.type = leverage_ctrl_t::type_velocity;
2080  decodedcontroller.controller_number = 0;
2081  break;
2082  case _lev_ctrl_channelaftertouch:
2083  decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
2084  decodedcontroller.controller_number = 0;
2085  break;
2086 
2087  // ordinary MIDI control change controller
2088  case _lev_ctrl_modwheel:
2089  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2090  decodedcontroller.controller_number = 1;
2091  break;
2092  case _lev_ctrl_breath:
2093  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2094  decodedcontroller.controller_number = 2;
2095  break;
2096  case _lev_ctrl_foot:
2097  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2098  decodedcontroller.controller_number = 4;
2099  break;
2100  case _lev_ctrl_effect1:
2101  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2102  decodedcontroller.controller_number = 12;
2103  break;
2104  case _lev_ctrl_effect2:
2105  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2106  decodedcontroller.controller_number = 13;
2107  break;
2108  case _lev_ctrl_genpurpose1:
2109  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2110  decodedcontroller.controller_number = 16;
2111  break;
2112  case _lev_ctrl_genpurpose2:
2113  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2114  decodedcontroller.controller_number = 17;
2115  break;
2116  case _lev_ctrl_genpurpose3:
2117  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2118  decodedcontroller.controller_number = 18;
2119  break;
2120  case _lev_ctrl_genpurpose4:
2121  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2122  decodedcontroller.controller_number = 19;
2123  break;
2124  case _lev_ctrl_portamentotime:
2125  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2126  decodedcontroller.controller_number = 5;
2127  break;
2128  case _lev_ctrl_sustainpedal:
2129  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2130  decodedcontroller.controller_number = 64;
2131  break;
2132  case _lev_ctrl_portamento:
2133  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2134  decodedcontroller.controller_number = 65;
2135  break;
2136  case _lev_ctrl_sostenutopedal:
2137  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2138  decodedcontroller.controller_number = 66;
2139  break;
2140  case _lev_ctrl_softpedal:
2141  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2142  decodedcontroller.controller_number = 67;
2143  break;
2144  case _lev_ctrl_genpurpose5:
2145  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2146  decodedcontroller.controller_number = 80;
2147  break;
2148  case _lev_ctrl_genpurpose6:
2149  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2150  decodedcontroller.controller_number = 81;
2151  break;
2152  case _lev_ctrl_genpurpose7:
2153  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2154  decodedcontroller.controller_number = 82;
2155  break;
2156  case _lev_ctrl_genpurpose8:
2157  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2158  decodedcontroller.controller_number = 83;
2159  break;
2160  case _lev_ctrl_effect1depth:
2161  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2162  decodedcontroller.controller_number = 91;
2163  break;
2164  case _lev_ctrl_effect2depth:
2165  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2166  decodedcontroller.controller_number = 92;
2167  break;
2168  case _lev_ctrl_effect3depth:
2169  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2170  decodedcontroller.controller_number = 93;
2171  break;
2172  case _lev_ctrl_effect4depth:
2173  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2174  decodedcontroller.controller_number = 94;
2175  break;
2176  case _lev_ctrl_effect5depth:
2177  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2178  decodedcontroller.controller_number = 95;
2179  break;
2180 
2181  // format extension (these controllers are so far only supported by
2182  // LinuxSampler & gigedit) they will *NOT* work with
2183  // Gigasampler/GigaStudio !
2184  case _lev_ctrl_CC3_EXT:
2185  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186  decodedcontroller.controller_number = 3;
2187  break;
2188  case _lev_ctrl_CC6_EXT:
2189  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190  decodedcontroller.controller_number = 6;
2191  break;
2192  case _lev_ctrl_CC7_EXT:
2193  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194  decodedcontroller.controller_number = 7;
2195  break;
2196  case _lev_ctrl_CC8_EXT:
2197  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198  decodedcontroller.controller_number = 8;
2199  break;
2200  case _lev_ctrl_CC9_EXT:
2201  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202  decodedcontroller.controller_number = 9;
2203  break;
2204  case _lev_ctrl_CC10_EXT:
2205  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206  decodedcontroller.controller_number = 10;
2207  break;
2208  case _lev_ctrl_CC11_EXT:
2209  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2210  decodedcontroller.controller_number = 11;
2211  break;
2212  case _lev_ctrl_CC14_EXT:
2213  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214  decodedcontroller.controller_number = 14;
2215  break;
2216  case _lev_ctrl_CC15_EXT:
2217  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218  decodedcontroller.controller_number = 15;
2219  break;
2220  case _lev_ctrl_CC20_EXT:
2221  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222  decodedcontroller.controller_number = 20;
2223  break;
2224  case _lev_ctrl_CC21_EXT:
2225  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226  decodedcontroller.controller_number = 21;
2227  break;
2228  case _lev_ctrl_CC22_EXT:
2229  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230  decodedcontroller.controller_number = 22;
2231  break;
2232  case _lev_ctrl_CC23_EXT:
2233  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234  decodedcontroller.controller_number = 23;
2235  break;
2236  case _lev_ctrl_CC24_EXT:
2237  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238  decodedcontroller.controller_number = 24;
2239  break;
2240  case _lev_ctrl_CC25_EXT:
2241  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242  decodedcontroller.controller_number = 25;
2243  break;
2244  case _lev_ctrl_CC26_EXT:
2245  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246  decodedcontroller.controller_number = 26;
2247  break;
2248  case _lev_ctrl_CC27_EXT:
2249  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250  decodedcontroller.controller_number = 27;
2251  break;
2252  case _lev_ctrl_CC28_EXT:
2253  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254  decodedcontroller.controller_number = 28;
2255  break;
2256  case _lev_ctrl_CC29_EXT:
2257  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258  decodedcontroller.controller_number = 29;
2259  break;
2260  case _lev_ctrl_CC30_EXT:
2261  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262  decodedcontroller.controller_number = 30;
2263  break;
2264  case _lev_ctrl_CC31_EXT:
2265  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2266  decodedcontroller.controller_number = 31;
2267  break;
2268  case _lev_ctrl_CC68_EXT:
2269  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270  decodedcontroller.controller_number = 68;
2271  break;
2272  case _lev_ctrl_CC69_EXT:
2273  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274  decodedcontroller.controller_number = 69;
2275  break;
2276  case _lev_ctrl_CC70_EXT:
2277  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278  decodedcontroller.controller_number = 70;
2279  break;
2280  case _lev_ctrl_CC71_EXT:
2281  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282  decodedcontroller.controller_number = 71;
2283  break;
2284  case _lev_ctrl_CC72_EXT:
2285  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286  decodedcontroller.controller_number = 72;
2287  break;
2288  case _lev_ctrl_CC73_EXT:
2289  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290  decodedcontroller.controller_number = 73;
2291  break;
2292  case _lev_ctrl_CC74_EXT:
2293  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294  decodedcontroller.controller_number = 74;
2295  break;
2296  case _lev_ctrl_CC75_EXT:
2297  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298  decodedcontroller.controller_number = 75;
2299  break;
2300  case _lev_ctrl_CC76_EXT:
2301  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302  decodedcontroller.controller_number = 76;
2303  break;
2304  case _lev_ctrl_CC77_EXT:
2305  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306  decodedcontroller.controller_number = 77;
2307  break;
2308  case _lev_ctrl_CC78_EXT:
2309  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310  decodedcontroller.controller_number = 78;
2311  break;
2312  case _lev_ctrl_CC79_EXT:
2313  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314  decodedcontroller.controller_number = 79;
2315  break;
2316  case _lev_ctrl_CC84_EXT:
2317  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318  decodedcontroller.controller_number = 84;
2319  break;
2320  case _lev_ctrl_CC85_EXT:
2321  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322  decodedcontroller.controller_number = 85;
2323  break;
2324  case _lev_ctrl_CC86_EXT:
2325  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326  decodedcontroller.controller_number = 86;
2327  break;
2328  case _lev_ctrl_CC87_EXT:
2329  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330  decodedcontroller.controller_number = 87;
2331  break;
2332  case _lev_ctrl_CC89_EXT:
2333  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334  decodedcontroller.controller_number = 89;
2335  break;
2336  case _lev_ctrl_CC90_EXT:
2337  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338  decodedcontroller.controller_number = 90;
2339  break;
2340  case _lev_ctrl_CC96_EXT:
2341  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342  decodedcontroller.controller_number = 96;
2343  break;
2344  case _lev_ctrl_CC97_EXT:
2345  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346  decodedcontroller.controller_number = 97;
2347  break;
2348  case _lev_ctrl_CC102_EXT:
2349  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350  decodedcontroller.controller_number = 102;
2351  break;
2352  case _lev_ctrl_CC103_EXT:
2353  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354  decodedcontroller.controller_number = 103;
2355  break;
2356  case _lev_ctrl_CC104_EXT:
2357  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358  decodedcontroller.controller_number = 104;
2359  break;
2360  case _lev_ctrl_CC105_EXT:
2361  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362  decodedcontroller.controller_number = 105;
2363  break;
2364  case _lev_ctrl_CC106_EXT:
2365  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366  decodedcontroller.controller_number = 106;
2367  break;
2368  case _lev_ctrl_CC107_EXT:
2369  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370  decodedcontroller.controller_number = 107;
2371  break;
2372  case _lev_ctrl_CC108_EXT:
2373  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374  decodedcontroller.controller_number = 108;
2375  break;
2376  case _lev_ctrl_CC109_EXT:
2377  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378  decodedcontroller.controller_number = 109;
2379  break;
2380  case _lev_ctrl_CC110_EXT:
2381  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382  decodedcontroller.controller_number = 110;
2383  break;
2384  case _lev_ctrl_CC111_EXT:
2385  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386  decodedcontroller.controller_number = 111;
2387  break;
2388  case _lev_ctrl_CC112_EXT:
2389  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390  decodedcontroller.controller_number = 112;
2391  break;
2392  case _lev_ctrl_CC113_EXT:
2393  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394  decodedcontroller.controller_number = 113;
2395  break;
2396  case _lev_ctrl_CC114_EXT:
2397  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398  decodedcontroller.controller_number = 114;
2399  break;
2400  case _lev_ctrl_CC115_EXT:
2401  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402  decodedcontroller.controller_number = 115;
2403  break;
2404  case _lev_ctrl_CC116_EXT:
2405  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406  decodedcontroller.controller_number = 116;
2407  break;
2408  case _lev_ctrl_CC117_EXT:
2409  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410  decodedcontroller.controller_number = 117;
2411  break;
2412  case _lev_ctrl_CC118_EXT:
2413  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414  decodedcontroller.controller_number = 118;
2415  break;
2416  case _lev_ctrl_CC119_EXT:
2417  decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418  decodedcontroller.controller_number = 119;
2419  break;
2420 
2421  // unknown controller type
2422  default:
2423  throw gig::Exception("Unknown leverage controller type.");
2424  }
2425  return decodedcontroller;
2426  }
2427 
2428 // see above (diagnostic push not supported prior GCC 4.6)
2429 //#pragma GCC diagnostic pop
2430 
2431  DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2432  _lev_ctrl_t encodedcontroller;
2433  switch (DecodedController.type) {
2434  // special controller
2436  encodedcontroller = _lev_ctrl_none;
2437  break;
2439  encodedcontroller = _lev_ctrl_velocity;
2440  break;
2442  encodedcontroller = _lev_ctrl_channelaftertouch;
2443  break;
2444 
2445  // ordinary MIDI control change controller
2447  switch (DecodedController.controller_number) {
2448  case 1:
2449  encodedcontroller = _lev_ctrl_modwheel;
2450  break;
2451  case 2:
2452  encodedcontroller = _lev_ctrl_breath;
2453  break;
2454  case 4:
2455  encodedcontroller = _lev_ctrl_foot;
2456  break;
2457  case 12:
2458  encodedcontroller = _lev_ctrl_effect1;
2459  break;
2460  case 13:
2461  encodedcontroller = _lev_ctrl_effect2;
2462  break;
2463  case 16:
2464  encodedcontroller = _lev_ctrl_genpurpose1;
2465  break;
2466  case 17:
2467  encodedcontroller = _lev_ctrl_genpurpose2;
2468  break;
2469  case 18:
2470  encodedcontroller = _lev_ctrl_genpurpose3;
2471  break;
2472  case 19:
2473  encodedcontroller = _lev_ctrl_genpurpose4;
2474  break;
2475  case 5:
2476  encodedcontroller = _lev_ctrl_portamentotime;
2477  break;
2478  case 64:
2479  encodedcontroller = _lev_ctrl_sustainpedal;
2480  break;
2481  case 65:
2482  encodedcontroller = _lev_ctrl_portamento;
2483  break;
2484  case 66:
2485  encodedcontroller = _lev_ctrl_sostenutopedal;
2486  break;
2487  case 67:
2488  encodedcontroller = _lev_ctrl_softpedal;
2489  break;
2490  case 80:
2491  encodedcontroller = _lev_ctrl_genpurpose5;
2492  break;
2493  case 81:
2494  encodedcontroller = _lev_ctrl_genpurpose6;
2495  break;
2496  case 82:
2497  encodedcontroller = _lev_ctrl_genpurpose7;
2498  break;
2499  case 83:
2500  encodedcontroller = _lev_ctrl_genpurpose8;
2501  break;
2502  case 91:
2503  encodedcontroller = _lev_ctrl_effect1depth;
2504  break;
2505  case 92:
2506  encodedcontroller = _lev_ctrl_effect2depth;
2507  break;
2508  case 93:
2509  encodedcontroller = _lev_ctrl_effect3depth;
2510  break;
2511  case 94:
2512  encodedcontroller = _lev_ctrl_effect4depth;
2513  break;
2514  case 95:
2515  encodedcontroller = _lev_ctrl_effect5depth;
2516  break;
2517 
2518  // format extension (these controllers are so far only
2519  // supported by LinuxSampler & gigedit) they will *NOT*
2520  // work with Gigasampler/GigaStudio !
2521  case 3:
2522  encodedcontroller = _lev_ctrl_CC3_EXT;
2523  break;
2524  case 6:
2525  encodedcontroller = _lev_ctrl_CC6_EXT;
2526  break;
2527  case 7:
2528  encodedcontroller = _lev_ctrl_CC7_EXT;
2529  break;
2530  case 8:
2531  encodedcontroller = _lev_ctrl_CC8_EXT;
2532  break;
2533  case 9:
2534  encodedcontroller = _lev_ctrl_CC9_EXT;
2535  break;
2536  case 10:
2537  encodedcontroller = _lev_ctrl_CC10_EXT;
2538  break;
2539  case 11:
2540  encodedcontroller = _lev_ctrl_CC11_EXT;
2541  break;
2542  case 14:
2543  encodedcontroller = _lev_ctrl_CC14_EXT;
2544  break;
2545  case 15:
2546  encodedcontroller = _lev_ctrl_CC15_EXT;
2547  break;
2548  case 20:
2549  encodedcontroller = _lev_ctrl_CC20_EXT;
2550  break;
2551  case 21:
2552  encodedcontroller = _lev_ctrl_CC21_EXT;
2553  break;
2554  case 22:
2555  encodedcontroller = _lev_ctrl_CC22_EXT;
2556  break;
2557  case 23:
2558  encodedcontroller = _lev_ctrl_CC23_EXT;
2559  break;
2560  case 24:
2561  encodedcontroller = _lev_ctrl_CC24_EXT;
2562  break;
2563  case 25:
2564  encodedcontroller = _lev_ctrl_CC25_EXT;
2565  break;
2566  case 26:
2567  encodedcontroller = _lev_ctrl_CC26_EXT;
2568  break;
2569  case 27:
2570  encodedcontroller = _lev_ctrl_CC27_EXT;
2571  break;
2572  case 28:
2573  encodedcontroller = _lev_ctrl_CC28_EXT;
2574  break;
2575  case 29:
2576  encodedcontroller = _lev_ctrl_CC29_EXT;
2577  break;
2578  case 30:
2579  encodedcontroller = _lev_ctrl_CC30_EXT;
2580  break;
2581  case 31:
2582  encodedcontroller = _lev_ctrl_CC31_EXT;
2583  break;
2584  case 68:
2585  encodedcontroller = _lev_ctrl_CC68_EXT;
2586  break;
2587  case 69:
2588  encodedcontroller = _lev_ctrl_CC69_EXT;
2589  break;
2590  case 70:
2591  encodedcontroller = _lev_ctrl_CC70_EXT;
2592  break;
2593  case 71:
2594  encodedcontroller = _lev_ctrl_CC71_EXT;
2595  break;
2596  case 72:
2597  encodedcontroller = _lev_ctrl_CC72_EXT;
2598  break;
2599  case 73:
2600  encodedcontroller = _lev_ctrl_CC73_EXT;
2601  break;
2602  case 74:
2603  encodedcontroller = _lev_ctrl_CC74_EXT;
2604  break;
2605  case 75:
2606  encodedcontroller = _lev_ctrl_CC75_EXT;
2607  break;
2608  case 76:
2609  encodedcontroller = _lev_ctrl_CC76_EXT;
2610  break;
2611  case 77:
2612  encodedcontroller = _lev_ctrl_CC77_EXT;
2613  break;
2614  case 78:
2615  encodedcontroller = _lev_ctrl_CC78_EXT;
2616  break;
2617  case 79:
2618  encodedcontroller = _lev_ctrl_CC79_EXT;
2619  break;
2620  case 84:
2621  encodedcontroller = _lev_ctrl_CC84_EXT;
2622  break;
2623  case 85:
2624  encodedcontroller = _lev_ctrl_CC85_EXT;
2625  break;
2626  case 86:
2627  encodedcontroller = _lev_ctrl_CC86_EXT;
2628  break;
2629  case 87:
2630  encodedcontroller = _lev_ctrl_CC87_EXT;
2631  break;
2632  case 89:
2633  encodedcontroller = _lev_ctrl_CC89_EXT;
2634  break;
2635  case 90:
2636  encodedcontroller = _lev_ctrl_CC90_EXT;
2637  break;
2638  case 96:
2639  encodedcontroller = _lev_ctrl_CC96_EXT;
2640  break;
2641  case 97:
2642  encodedcontroller = _lev_ctrl_CC97_EXT;
2643  break;
2644  case 102:
2645  encodedcontroller = _lev_ctrl_CC102_EXT;
2646  break;
2647  case 103:
2648  encodedcontroller = _lev_ctrl_CC103_EXT;
2649  break;
2650  case 104:
2651  encodedcontroller = _lev_ctrl_CC104_EXT;
2652  break;
2653  case 105:
2654  encodedcontroller = _lev_ctrl_CC105_EXT;
2655  break;
2656  case 106:
2657  encodedcontroller = _lev_ctrl_CC106_EXT;
2658  break;
2659  case 107:
2660  encodedcontroller = _lev_ctrl_CC107_EXT;
2661  break;
2662  case 108:
2663  encodedcontroller = _lev_ctrl_CC108_EXT;
2664  break;
2665  case 109:
2666  encodedcontroller = _lev_ctrl_CC109_EXT;
2667  break;
2668  case 110:
2669  encodedcontroller = _lev_ctrl_CC110_EXT;
2670  break;
2671  case 111:
2672  encodedcontroller = _lev_ctrl_CC111_EXT;
2673  break;
2674  case 112:
2675  encodedcontroller = _lev_ctrl_CC112_EXT;
2676  break;
2677  case 113:
2678  encodedcontroller = _lev_ctrl_CC113_EXT;
2679  break;
2680  case 114:
2681  encodedcontroller = _lev_ctrl_CC114_EXT;
2682  break;
2683  case 115:
2684  encodedcontroller = _lev_ctrl_CC115_EXT;
2685  break;
2686  case 116:
2687  encodedcontroller = _lev_ctrl_CC116_EXT;
2688  break;
2689  case 117:
2690  encodedcontroller = _lev_ctrl_CC117_EXT;
2691  break;
2692  case 118:
2693  encodedcontroller = _lev_ctrl_CC118_EXT;
2694  break;
2695  case 119:
2696  encodedcontroller = _lev_ctrl_CC119_EXT;
2697  break;
2698 
2699  default:
2700  throw gig::Exception("leverage controller number is not supported by the gig format");
2701  }
2702  break;
2703  default:
2704  throw gig::Exception("Unknown leverage controller type.");
2705  }
2706  return encodedcontroller;
2707  }
2708 
2710  Instances--;
2711  if (!Instances) {
2712  // delete the velocity->volume tables
2713  VelocityTableMap::iterator iter;
2714  for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
2715  double* pTable = iter->second;
2716  if (pTable) delete[] pTable;
2717  }
2718  pVelocityTables->clear();
2719  delete pVelocityTables;
2720  pVelocityTables = NULL;
2721  }
2722  if (VelocityTable) delete[] VelocityTable;
2723  }
2724 
2736  double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
2737  return pVelocityAttenuationTable[MIDIKeyVelocity];
2738  }
2739 
2740  double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2741  return pVelocityReleaseTable[MIDIKeyVelocity];
2742  }
2743 
2744  double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2745  return pVelocityCutoffTable[MIDIKeyVelocity];
2746  }
2747 
2753  pVelocityAttenuationTable =
2754  GetVelocityTable(
2756  );
2757  VelocityResponseCurve = curve;
2758  }
2759 
2765  pVelocityAttenuationTable =
2766  GetVelocityTable(
2768  );
2769  VelocityResponseDepth = depth;
2770  }
2771 
2777  pVelocityAttenuationTable =
2778  GetVelocityTable(
2780  );
2781  VelocityResponseCurveScaling = scaling;
2782  }
2783 
2789  pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2791  }
2792 
2798  pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2800  }
2801 
2807  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2808  VCFCutoffController = controller;
2809  }
2810 
2816  pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2817  VCFVelocityCurve = curve;
2818  }
2819 
2825  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2826  VCFVelocityDynamicRange = range;
2827  }
2828 
2834  pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2835  VCFVelocityScale = scaling;
2836  }
2837 
2838  double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2839 
2840  // line-segment approximations of the 15 velocity curves
2841 
2842  // linear
2843  const int lin0[] = { 1, 1, 127, 127 };
2844  const int lin1[] = { 1, 21, 127, 127 };
2845  const int lin2[] = { 1, 45, 127, 127 };
2846  const int lin3[] = { 1, 74, 127, 127 };
2847  const int lin4[] = { 1, 127, 127, 127 };
2848 
2849  // non-linear
2850  const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2851  const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2852  127, 127 };
2853  const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2854  127, 127 };
2855  const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2856  127, 127 };
2857  const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2858 
2859  // special
2860  const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2861  113, 127, 127, 127 };
2862  const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2863  118, 127, 127, 127 };
2864  const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2865  85, 90, 91, 127, 127, 127 };
2866  const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2867  117, 127, 127, 127 };
2868  const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2869  127, 127 };
2870 
2871  // this is only used by the VCF velocity curve
2872  const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2873  91, 127, 127, 127 };
2874 
2875  const int* const curves[] = { non0, non1, non2, non3, non4,
2876  lin0, lin1, lin2, lin3, lin4,
2877  spe0, spe1, spe2, spe3, spe4, spe5 };
2878 
2879  double* const table = new double[128];
2880 
2881  const int* curve = curves[curveType * 5 + depth];
2882  const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2883 
2884  table[0] = 0;
2885  for (int x = 1 ; x < 128 ; x++) {
2886 
2887  if (x > curve[2]) curve += 2;
2888  double y = curve[1] + (x - curve[0]) *
2889  (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2890  y = y / 127;
2891 
2892  // Scale up for s > 20, down for s < 20. When
2893  // down-scaling, the curve still ends at 1.0.
2894  if (s < 20 && y >= 0.5)
2895  y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2896  else
2897  y = y * (s / 20.0);
2898  if (y > 1) y = 1;
2899 
2900  table[x] = y;
2901  }
2902  return table;
2903  }
2904 
2905 
2906 // *************** Region ***************
2907 // *
2908 
2909  Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2910  // Initialization
2911  Dimensions = 0;
2912  for (int i = 0; i < 256; i++) {
2913  pDimensionRegions[i] = NULL;
2914  }
2915  Layers = 1;
2916  File* file = (File*) GetParent()->GetParent();
2917  int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2918 
2919  // Actual Loading
2920 
2921  if (!file->GetAutoLoad()) return;
2922 
2923  LoadDimensionRegions(rgnList);
2924 
2925  RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2926  if (_3lnk) {
2927  DimensionRegions = _3lnk->ReadUint32();
2928  for (int i = 0; i < dimensionBits; i++) {
2929  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2930  uint8_t bits = _3lnk->ReadUint8();
2931  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2932  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2933  uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2934  if (dimension == dimension_none) { // inactive dimension
2936  pDimensionDefinitions[i].bits = 0;
2940  }
2941  else { // active dimension
2942  pDimensionDefinitions[i].dimension = dimension;
2943  pDimensionDefinitions[i].bits = bits;
2944  pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2945  pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2946  pDimensionDefinitions[i].zone_size = __resolveZoneSize(pDimensionDefinitions[i]);
2947  Dimensions++;
2948 
2949  // if this is a layer dimension, remember the amount of layers
2950  if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2951  }
2952  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2953  }
2954  for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2955 
2956  // if there's a velocity dimension and custom velocity zone splits are used,
2957  // update the VelocityTables in the dimension regions
2959 
2960  // jump to start of the wave pool indices (if not already there)
2961  if (file->pVersion && file->pVersion->major == 3)
2962  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2963  else
2964  _3lnk->SetPos(44);
2965 
2966  // load sample references (if auto loading is enabled)
2967  if (file->GetAutoLoad()) {
2968  for (uint i = 0; i < DimensionRegions; i++) {
2969  uint32_t wavepoolindex = _3lnk->ReadUint32();
2970  if (file->pWavePoolTable && pDimensionRegions[i]) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2971  }
2972  GetSample(); // load global region sample reference
2973  }
2974  } else {
2975  DimensionRegions = 0;
2976  for (int i = 0 ; i < 8 ; i++) {
2978  pDimensionDefinitions[i].bits = 0;
2980  }
2981  }
2982 
2983  // make sure there is at least one dimension region
2984  if (!DimensionRegions) {
2985  RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2986  if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2987  RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2988  pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2989  DimensionRegions = 1;
2990  }
2991  }
2992 
3004  // in the gig format we don't care about the Region's sample reference
3005  // but we still have to provide some existing one to not corrupt the
3006  // file, so to avoid the latter we simply always assign the sample of
3007  // the first dimension region of this region
3009 
3010  // first update base class's chunks
3011  DLS::Region::UpdateChunks(pProgress);
3012 
3013  // update dimension region's chunks
3014  for (int i = 0; i < DimensionRegions; i++) {
3015  pDimensionRegions[i]->UpdateChunks(pProgress);
3016  }
3017 
3018  File* pFile = (File*) GetParent()->GetParent();
3019  bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3020  const int iMaxDimensions = version3 ? 8 : 5;
3021  const int iMaxDimensionRegions = version3 ? 256 : 32;
3022 
3023  // make sure '3lnk' chunk exists
3025  if (!_3lnk) {
3026  const int _3lnkChunkSize = version3 ? 1092 : 172;
3027  _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3028  memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3029 
3030  // move 3prg to last position
3032  }
3033 
3034  // update dimension definitions in '3lnk' chunk
3035  uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3036  store32(&pData[0], DimensionRegions);
3037  int shift = 0;
3038  for (int i = 0; i < iMaxDimensions; i++) {
3039  pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3040  pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3041  pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3042  pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3043  pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3044  // next 3 bytes unknown, always zero?
3045 
3046  shift += pDimensionDefinitions[i].bits;
3047  }
3048 
3049  // update wave pool table in '3lnk' chunk
3050  const int iWavePoolOffset = version3 ? 68 : 44;
3051  for (uint i = 0; i < iMaxDimensionRegions; i++) {
3052  int iWaveIndex = -1;
3053  if (i < DimensionRegions) {
3054  if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3055  File::SampleList::iterator iter = pFile->pSamples->begin();
3056  File::SampleList::iterator end = pFile->pSamples->end();
3057  for (int index = 0; iter != end; ++iter, ++index) {
3058  if (*iter == pDimensionRegions[i]->pSample) {
3059  iWaveIndex = index;
3060  break;
3061  }
3062  }
3063  }
3064  store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3065  }
3066  }
3067 
3069  RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
3070  if (_3prg) {
3071  int dimensionRegionNr = 0;
3072  RIFF::List* _3ewl = _3prg->GetFirstSubList();
3073  while (_3ewl) {
3074  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3075  pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3076  dimensionRegionNr++;
3077  }
3078  _3ewl = _3prg->GetNextSubList();
3079  }
3080  if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
3081  }
3082  }
3083 
3084  void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3085  // update KeyRange struct and make sure regions are in correct order
3086  DLS::Region::SetKeyRange(Low, High);
3087  // update Region key table for fast lookup
3088  ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3089  }
3090 
3092  // get velocity dimension's index
3093  int veldim = -1;
3094  for (int i = 0 ; i < Dimensions ; i++) {
3095  if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3096  veldim = i;
3097  break;
3098  }
3099  }
3100  if (veldim == -1) return;
3101 
3102  int step = 1;
3103  for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3104  int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3105  int end = step * pDimensionDefinitions[veldim].zones;
3106 
3107  // loop through all dimension regions for all dimensions except the velocity dimension
3108  int dim[8] = { 0 };
3109  for (int i = 0 ; i < DimensionRegions ; i++) {
3110 
3111  if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3112  pDimensionRegions[i]->VelocityUpperLimit) {
3113  // create the velocity table
3114  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3115  if (!table) {
3116  table = new uint8_t[128];
3117  pDimensionRegions[i]->VelocityTable = table;
3118  }
3119  int tableidx = 0;
3120  int velocityZone = 0;
3121  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3122  for (int k = i ; k < end ; k += step) {
3124  for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3125  velocityZone++;
3126  }
3127  } else { // gig2
3128  for (int k = i ; k < end ; k += step) {
3130  for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3131  velocityZone++;
3132  }
3133  }
3134  } else {
3135  if (pDimensionRegions[i]->VelocityTable) {
3136  delete[] pDimensionRegions[i]->VelocityTable;
3138  }
3139  }
3140 
3141  int j;
3142  int shift = 0;
3143  for (j = 0 ; j < Dimensions ; j++) {
3144  if (j == veldim) i += skipveldim; // skip velocity dimension
3145  else {
3146  dim[j]++;
3147  if (dim[j] < pDimensionDefinitions[j].zones) break;
3148  else {
3149  // skip unused dimension regions
3150  dim[j] = 0;
3151  i += ((1 << pDimensionDefinitions[j].bits) -
3152  pDimensionDefinitions[j].zones) << shift;
3153  }
3154  }
3155  shift += pDimensionDefinitions[j].bits;
3156  }
3157  if (j == Dimensions) break;
3158  }
3159  }
3160 
3177  // some initial sanity checks of the given dimension definition
3178  if (pDimDef->zones < 2)
3179  throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3180  if (pDimDef->bits < 1)
3181  throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3182  if (pDimDef->dimension == dimension_samplechannel) {
3183  if (pDimDef->zones != 2)
3184  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3185  if (pDimDef->bits != 1)
3186  throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3187  }
3188 
3189  // check if max. amount of dimensions reached
3190  File* file = (File*) GetParent()->GetParent();
3191  const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3192  if (Dimensions >= iMaxDimensions)
3193  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3194  // check if max. amount of dimension bits reached
3195  int iCurrentBits = 0;
3196  for (int i = 0; i < Dimensions; i++)
3197  iCurrentBits += pDimensionDefinitions[i].bits;
3198  if (iCurrentBits >= iMaxDimensions)
3199  throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3200  const int iNewBits = iCurrentBits + pDimDef->bits;
3201  if (iNewBits > iMaxDimensions)
3202  throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3203  // check if there's already a dimensions of the same type
3204  for (int i = 0; i < Dimensions; i++)
3205  if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3206  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3207 
3208  // pos is where the new dimension should be placed, normally
3209  // last in list, except for the samplechannel dimension which
3210  // has to be first in list
3211  int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3212  int bitpos = 0;
3213  for (int i = 0 ; i < pos ; i++)
3214  bitpos += pDimensionDefinitions[i].bits;
3215 
3216  // make room for the new dimension
3217  for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3218  for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3219  for (int j = Dimensions ; j > pos ; j--) {
3222  }
3223  }
3224 
3225  // assign definition of new dimension
3226  pDimensionDefinitions[pos] = *pDimDef;
3227 
3228  // auto correct certain dimension definition fields (where possible)
3230  __resolveSplitType(pDimensionDefinitions[pos].dimension);
3232  __resolveZoneSize(pDimensionDefinitions[pos]);
3233 
3234  // create new dimension region(s) for this new dimension, and make
3235  // sure that the dimension regions are placed correctly in both the
3236  // RIFF list and the pDimensionRegions array
3237  RIFF::Chunk* moveTo = NULL;
3239  for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3240  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3241  pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3242  }
3243  for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3244  for (int k = 0 ; k < (1 << bitpos) ; k++) {
3245  RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3246  if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3247  // create a new dimension region and copy all parameter values from
3248  // an existing dimension region
3249  pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3250  new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3251 
3252  DimensionRegions++;
3253  }
3254  }
3255  moveTo = pDimensionRegions[i]->pParentList;
3256  }
3257 
3258  // initialize the upper limits for this dimension
3259  int mask = (1 << bitpos) - 1;
3260  for (int z = 0 ; z < pDimDef->zones ; z++) {
3261  uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3262  for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3263  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3264  (z << bitpos) |
3265  (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3266  }
3267  }
3268 
3269  Dimensions++;
3270 
3271  // if this is a layer dimension, update 'Layers' attribute
3272  if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3273 
3275  }
3276 
3289  // get dimension's index
3290  int iDimensionNr = -1;
3291  for (int i = 0; i < Dimensions; i++) {
3292  if (&pDimensionDefinitions[i] == pDimDef) {
3293  iDimensionNr = i;
3294  break;
3295  }
3296  }
3297  if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3298 
3299  // get amount of bits below the dimension to delete
3300  int iLowerBits = 0;
3301  for (int i = 0; i < iDimensionNr; i++)
3302  iLowerBits += pDimensionDefinitions[i].bits;
3303 
3304  // get amount ot bits above the dimension to delete
3305  int iUpperBits = 0;
3306  for (int i = iDimensionNr + 1; i < Dimensions; i++)
3307  iUpperBits += pDimensionDefinitions[i].bits;
3308 
3310 
3311  // delete dimension regions which belong to the given dimension
3312  // (that is where the dimension's bit > 0)
3313  for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3314  for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3315  for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3316  int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3317  iObsoleteBit << iLowerBits |
3318  iLowerBit;
3319 
3320  _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3321  delete pDimensionRegions[iToDelete];
3322  pDimensionRegions[iToDelete] = NULL;
3323  DimensionRegions--;
3324  }
3325  }
3326  }
3327 
3328  // defrag pDimensionRegions array
3329  // (that is remove the NULL spaces within the pDimensionRegions array)
3330  for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3331  if (!pDimensionRegions[iTo]) {
3332  if (iFrom <= iTo) iFrom = iTo + 1;
3333  while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3334  if (iFrom < 256 && pDimensionRegions[iFrom]) {
3335  pDimensionRegions[iTo] = pDimensionRegions[iFrom];
3336  pDimensionRegions[iFrom] = NULL;
3337  }
3338  }
3339  }
3340 
3341  // remove the this dimension from the upper limits arrays
3342  for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3343  DimensionRegion* d = pDimensionRegions[j];
3344  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3345  d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3346  }
3347  d->DimensionUpperLimits[Dimensions - 1] = 127;
3348  }
3349 
3350  // 'remove' dimension definition
3351  for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3353  }
3355  pDimensionDefinitions[Dimensions - 1].bits = 0;
3356  pDimensionDefinitions[Dimensions - 1].zones = 0;
3357 
3358  Dimensions--;
3359 
3360  // if this was a layer dimension, update 'Layers' attribute
3361  if (pDimDef->dimension == dimension_layer) Layers = 1;
3362  }
3363 
3379  dimension_def_t* oldDef = GetDimensionDefinition(type);
3380  if (!oldDef)
3381  throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3382  if (oldDef->zones <= 2)
3383  throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3384  if (zone < 0 || zone >= oldDef->zones)
3385  throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3386 
3387  const int newZoneSize = oldDef->zones - 1;
3388 
3389  // create a temporary Region which just acts as a temporary copy
3390  // container and will be deleted at the end of this function and will
3391  // also not be visible through the API during this process
3392  gig::Region* tempRgn = NULL;
3393  {
3394  // adding these temporary chunks is probably not even necessary
3395  Instrument* instr = static_cast<Instrument*>(GetParent());
3396  RIFF::List* pCkInstrument = instr->pCkInstrument;
3397  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3398  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3399  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3400  tempRgn = new Region(instr, rgn);
3401  }
3402 
3403  // copy this region's dimensions (with already the dimension split size
3404  // requested by the arguments of this method call) to the temporary
3405  // region, and don't use Region::CopyAssign() here for this task, since
3406  // it would also alter fast lookup helper variables here and there
3407  dimension_def_t newDef;
3408  for (int i = 0; i < Dimensions; ++i) {
3409  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3410  // is this the dimension requested by the method arguments? ...
3411  if (def.dimension == type) { // ... if yes, decrement zone amount by one
3412  def.zones = newZoneSize;
3413  if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3414  newDef = def;
3415  }
3416  tempRgn->AddDimension(&def);
3417  }
3418 
3419  // find the dimension index in the tempRegion which is the dimension
3420  // type passed to this method (paranoidly expecting different order)
3421  int tempReducedDimensionIndex = -1;
3422  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3423  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3424  tempReducedDimensionIndex = d;
3425  break;
3426  }
3427  }
3428 
3429  // copy dimension regions from this region to the temporary region
3430  for (int iDst = 0; iDst < 256; ++iDst) {
3431  DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3432  if (!dstDimRgn) continue;
3433  std::map<dimension_t,int> dimCase;
3434  bool isValidZone = true;
3435  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3436  const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3437  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3438  (iDst >> baseBits) & ((1 << dstBits) - 1);
3439  baseBits += dstBits;
3440  // there are also DimensionRegion objects of unused zones, skip them
3441  if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3442  isValidZone = false;
3443  break;
3444  }
3445  }
3446  if (!isValidZone) continue;
3447  // a bit paranoid: cope with the chance that the dimensions would
3448  // have different order in source and destination regions
3449  const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3450  if (dimCase[type] >= zone) dimCase[type]++;
3451  DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3452  dstDimRgn->CopyAssign(srcDimRgn);
3453  // if this is the upper most zone of the dimension passed to this
3454  // method, then correct (raise) its upper limit to 127
3455  if (newDef.split_type == split_type_normal && isLastZone)
3456  dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3457  }
3458 
3459  // now tempRegion's dimensions and DimensionRegions basically reflect
3460  // what we wanted to get for this actual Region here, so we now just
3461  // delete and recreate the dimension in question with the new amount
3462  // zones and then copy back from tempRegion
3463  DeleteDimension(oldDef);
3464  AddDimension(&newDef);
3465  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3466  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3467  if (!srcDimRgn) continue;
3468  std::map<dimension_t,int> dimCase;
3469  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3470  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3471  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3472  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3473  baseBits += srcBits;
3474  }
3475  // a bit paranoid: cope with the chance that the dimensions would
3476  // have different order in source and destination regions
3477  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3478  if (!dstDimRgn) continue;
3479  dstDimRgn->CopyAssign(srcDimRgn);
3480  }
3481 
3482  // delete temporary region
3483  delete tempRgn;
3484 
3486  }
3487 
3503  dimension_def_t* oldDef = GetDimensionDefinition(type);
3504  if (!oldDef)
3505  throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3506  if (zone < 0 || zone >= oldDef->zones)
3507  throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3508 
3509  const int newZoneSize = oldDef->zones + 1;
3510 
3511  // create a temporary Region which just acts as a temporary copy
3512  // container and will be deleted at the end of this function and will
3513  // also not be visible through the API during this process
3514  gig::Region* tempRgn = NULL;
3515  {
3516  // adding these temporary chunks is probably not even necessary
3517  Instrument* instr = static_cast<Instrument*>(GetParent());
3518  RIFF::List* pCkInstrument = instr->pCkInstrument;
3519  RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3520  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3521  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3522  tempRgn = new Region(instr, rgn);
3523  }
3524 
3525  // copy this region's dimensions (with already the dimension split size
3526  // requested by the arguments of this method call) to the temporary
3527  // region, and don't use Region::CopyAssign() here for this task, since
3528  // it would also alter fast lookup helper variables here and there
3529  dimension_def_t newDef;
3530  for (int i = 0; i < Dimensions; ++i) {
3531  dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3532  // is this the dimension requested by the method arguments? ...
3533  if (def.dimension == type) { // ... if yes, increment zone amount by one
3534  def.zones = newZoneSize;
3535  if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3536  newDef = def;
3537  }
3538  tempRgn->AddDimension(&def);
3539  }
3540 
3541  // find the dimension index in the tempRegion which is the dimension
3542  // type passed to this method (paranoidly expecting different order)
3543  int tempIncreasedDimensionIndex = -1;
3544  for (int d = 0; d < tempRgn->Dimensions; ++d) {
3545  if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3546  tempIncreasedDimensionIndex = d;
3547  break;
3548  }
3549  }
3550 
3551  // copy dimension regions from this region to the temporary region
3552  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3553  DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3554  if (!srcDimRgn) continue;
3555  std::map<dimension_t,int> dimCase;
3556  bool isValidZone = true;
3557  for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3558  const int srcBits = pDimensionDefinitions[d].bits;
3559  dimCase[pDimensionDefinitions[d].dimension] =
3560  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3561  // there are also DimensionRegion objects for unused zones, skip them
3562  if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3563  isValidZone = false;
3564  break;
3565  }
3566  baseBits += srcBits;
3567  }
3568  if (!isValidZone) continue;
3569  // a bit paranoid: cope with the chance that the dimensions would
3570  // have different order in source and destination regions
3571  if (dimCase[type] > zone) dimCase[type]++;
3572  DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3573  dstDimRgn->CopyAssign(srcDimRgn);
3574  // if this is the requested zone to be splitted, then also copy
3575  // the source DimensionRegion to the newly created target zone
3576  // and set the old zones upper limit lower
3577  if (dimCase[type] == zone) {
3578  // lower old zones upper limit
3579  if (newDef.split_type == split_type_normal) {
3580  const int high =
3581  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3582  int low = 0;
3583  if (zone > 0) {
3584  std::map<dimension_t,int> lowerCase = dimCase;
3585  lowerCase[type]--;
3586  DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3587  low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3588  }
3589  dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3590  }
3591  // fill the newly created zone of the divided zone as well
3592  dimCase[type]++;
3593  dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3594  dstDimRgn->CopyAssign(srcDimRgn);
3595  }
3596  }
3597 
3598  // now tempRegion's dimensions and DimensionRegions basically reflect
3599  // what we wanted to get for this actual Region here, so we now just
3600  // delete and recreate the dimension in question with the new amount
3601  // zones and then copy back from tempRegion
3602  DeleteDimension(oldDef);
3603  AddDimension(&newDef);
3604  for (int iSrc = 0; iSrc < 256; ++iSrc) {
3605  DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3606  if (!srcDimRgn) continue;
3607  std::map<dimension_t,int> dimCase;
3608  for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3609  const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3610  dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3611  (iSrc >> baseBits) & ((1 << srcBits) - 1);
3612  baseBits += srcBits;
3613  }
3614  // a bit paranoid: cope with the chance that the dimensions would
3615  // have different order in source and destination regions
3616  DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3617  if (!dstDimRgn) continue;
3618  dstDimRgn->CopyAssign(srcDimRgn);
3619  }
3620 
3621  // delete temporary region
3622  delete tempRgn;
3623 
3625  }
3626 
3642  if (oldType == newType) return;
3643  dimension_def_t* def = GetDimensionDefinition(oldType);
3644  if (!def)
3645  throw gig::Exception("No dimension with provided old dimension type exists on this region");
3646  if (newType == dimension_samplechannel && def->zones != 2)
3647  throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3648  if (GetDimensionDefinition(newType))
3649  throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3650  def->dimension = newType;
3651  def->split_type = __resolveSplitType(newType);
3652  }
3653 
3654  DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3655  uint8_t bits[8] = {};
3656  for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3657  it != DimCase.end(); ++it)
3658  {
3659  for (int d = 0; d < Dimensions; ++d) {
3660  if (pDimensionDefinitions[d].dimension == it->first) {
3661  bits[d] = it->second;
3662  goto nextDimCaseSlice;
3663  }
3664  }
3665  assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3666  nextDimCaseSlice:
3667  ; // noop
3668  }
3669  return GetDimensionRegionByBit(bits);
3670  }
3671 
3682  for (int i = 0; i < Dimensions; ++i)
3683  if (pDimensionDefinitions[i].dimension == type)
3684  return &pDimensionDefinitions[i];
3685  return NULL;
3686  }
3687 
3689  for (int i = 0; i < 256; i++) {
3690  if (pDimensionRegions[i]) delete pDimensionRegions[i];
3691  }
3692  }
3693 
3713  uint8_t bits;
3714  int veldim = -1;
3715  int velbitpos;
3716  int bitpos = 0;
3717  int dimregidx = 0;
3718  for (uint i = 0; i < Dimensions; i++) {
3719  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3720  // the velocity dimension must be handled after the other dimensions
3721  veldim = i;
3722  velbitpos = bitpos;
3723  } else {
3724  switch (pDimensionDefinitions[i].split_type) {
3725  case split_type_normal:
3726  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3727  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3728  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3729  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3730  }
3731  } else {
3732  // gig2: evenly sized zones
3733  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3734  }
3735  break;
3736  case split_type_bit: // the value is already the sought dimension bit number
3737  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3738  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3739  break;
3740  }
3741  dimregidx |= bits << bitpos;
3742  }
3743  bitpos += pDimensionDefinitions[i].bits;
3744  }
3745  DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3746  if (!dimreg) return NULL;
3747  if (veldim != -1) {
3748  // (dimreg is now the dimension region for the lowest velocity)
3749  if (dimreg->VelocityTable) // custom defined zone ranges
3750  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3751  else // normal split type
3752  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3753 
3754  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3755  dimregidx |= (bits & limiter_mask) << velbitpos;
3756  dimreg = pDimensionRegions[dimregidx & 255];
3757  }
3758  return dimreg;
3759  }
3760 
3761  int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3762  uint8_t bits;
3763  int veldim = -1;
3764  int velbitpos;
3765  int bitpos = 0;
3766  int dimregidx = 0;
3767  for (uint i = 0; i < Dimensions; i++) {
3768  if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3769  // the velocity dimension must be handled after the other dimensions
3770  veldim = i;
3771  velbitpos = bitpos;
3772  } else {
3773  switch (pDimensionDefinitions[i].split_type) {
3774  case split_type_normal:
3775  if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3776  // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3777  for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3778  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3779  }
3780  } else {
3781  // gig2: evenly sized zones
3782  bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3783  }
3784  break;
3785  case split_type_bit: // the value is already the sought dimension bit number
3786  const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3787  bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3788  break;
3789  }
3790  dimregidx |= bits << bitpos;
3791  }
3792  bitpos += pDimensionDefinitions[i].bits;
3793  }
3794  dimregidx &= 255;
3795  DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3796  if (!dimreg) return -1;
3797  if (veldim != -1) {
3798  // (dimreg is now the dimension region for the lowest velocity)
3799  if (dimreg->VelocityTable) // custom defined zone ranges
3800  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3801  else // normal split type
3802  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3803 
3804  const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3805  dimregidx |= (bits & limiter_mask) << velbitpos;
3806  dimregidx &= 255;
3807  }
3808  return dimregidx;
3809  }
3810 
3822  return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
3823  << pDimensionDefinitions[5].bits | DimBits[5])
3824  << pDimensionDefinitions[4].bits | DimBits[4])
3825  << pDimensionDefinitions[3].bits | DimBits[3])
3826  << pDimensionDefinitions[2].bits | DimBits[2])
3827  << pDimensionDefinitions[1].bits | DimBits[1])
3828  << pDimensionDefinitions[0].bits | DimBits[0]];
3829  }
3830 
3841  if (pSample) return static_cast<gig::Sample*>(pSample);
3842  else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
3843  }
3844 
3846  if ((int32_t)WavePoolTableIndex == -1) return NULL;
3847  File* file = (File*) GetParent()->GetParent();
3848  if (!file->pWavePoolTable) return NULL;
3849  unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3850  unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3851  Sample* sample = file->GetFirstSample(pProgress);
3852  while (sample) {
3853  if (sample->ulWavePoolOffset == soughtoffset &&
3854  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3855  sample = file->GetNextSample();
3856  }
3857  return NULL;
3858  }
3859 
3869  void Region::CopyAssign(const Region* orig) {
3870  CopyAssign(orig, NULL);
3871  }
3872 
3880  void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3881  // handle base classes
3883 
3884  if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3885  pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3886  }
3887 
3888  // handle own member variables
3889  for (int i = Dimensions - 1; i >= 0; --i) {
3891  }
3892  Layers = 0; // just to be sure
3893  for (int i = 0; i < orig->Dimensions; i++) {
3894  // we need to copy the dim definition here, to avoid the compiler
3895  // complaining about const-ness issue
3896  dimension_def_t def = orig->pDimensionDefinitions[i];
3897  AddDimension(&def);
3898  }
3899  for (int i = 0; i < 256; i++) {
3900  if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3902  orig->pDimensionRegions[i],
3903  mSamples
3904  );
3905  }
3906  }
3907  Layers = orig->Layers;
3908  }
3909 
3910 
3911 // *************** MidiRule ***************
3912 // *
3913 
3915  _3ewg->SetPos(36);
3916  Triggers = _3ewg->ReadUint8();
3917  _3ewg->SetPos(40);
3918  ControllerNumber = _3ewg->ReadUint8();
3919  _3ewg->SetPos(46);
3920  for (int i = 0 ; i < Triggers ; i++) {
3921  pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3922  pTriggers[i].Descending = _3ewg->ReadUint8();
3923  pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3924  pTriggers[i].Key = _3ewg->ReadUint8();
3925  pTriggers[i].NoteOff = _3ewg->ReadUint8();
3926  pTriggers[i].Velocity = _3ewg->ReadUint8();
3927  pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3928  _3ewg->ReadUint8();
3929  }
3930  }
3931 
3933  ControllerNumber(0),
3934  Triggers(0) {
3935  }
3936 
3937  void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3938  pData[32] = 4;
3939  pData[33] = 16;
3940  pData[36] = Triggers;
3941  pData[40] = ControllerNumber;
3942  for (int i = 0 ; i < Triggers ; i++) {
3943  pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3944  pData[47 + i * 8] = pTriggers[i].Descending;
3945  pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3946  pData[49 + i * 8] = pTriggers[i].Key;
3947  pData[50 + i * 8] = pTriggers[i].NoteOff;
3948  pData[51 + i * 8] = pTriggers[i].Velocity;
3949  pData[52 + i * 8] = pTriggers[i].OverridePedal;
3950  }
3951  }
3952 
3954  _3ewg->SetPos(36);
3955  LegatoSamples = _3ewg->ReadUint8(); // always 12
3956  _3ewg->SetPos(40);
3957  BypassUseController = _3ewg->ReadUint8();
3958  BypassKey = _3ewg->ReadUint8();
3959  BypassController = _3ewg->ReadUint8();
3960  ThresholdTime = _3ewg->ReadUint16();
3961  _3ewg->ReadInt16();
3962  ReleaseTime = _3ewg->ReadUint16();
3963  _3ewg->ReadInt16();
3964  KeyRange.low = _3ewg->ReadUint8();
3965  KeyRange.high = _3ewg->ReadUint8();
3966  _3ewg->SetPos(64);
3967  ReleaseTriggerKey = _3ewg->ReadUint8();
3968  AltSustain1Key = _3ewg->ReadUint8();
3969  AltSustain2Key = _3ewg->ReadUint8();
3970  }
3971 
3973  LegatoSamples(12),
3974  BypassUseController(false),
3975  BypassKey(0),
3976  BypassController(1),
3977  ThresholdTime(20),
3978  ReleaseTime(20),
3979  ReleaseTriggerKey(0),
3980  AltSustain1Key(0),
3981  AltSustain2Key(0)
3982  {
3983  KeyRange.low = KeyRange.high = 0;
3984  }
3985 
3986  void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3987  pData[32] = 0;
3988  pData[33] = 16;
3989  pData[36] = LegatoSamples;
3990  pData[40] = BypassUseController;
3991  pData[41] = BypassKey;
3992  pData[42] = BypassController;
3993  store16(&pData[43], ThresholdTime);
3994  store16(&pData[47], ReleaseTime);
3995  pData[51] = KeyRange.low;
3996  pData[52] = KeyRange.high;
3997  pData[64] = ReleaseTriggerKey;
3998  pData[65] = AltSustain1Key;
3999  pData[66] = AltSustain2Key;
4000  }
4001 
4003  _3ewg->SetPos(36);
4004  Articulations = _3ewg->ReadUint8();
4005  int flags = _3ewg->ReadUint8();
4006  Polyphonic = flags & 8;
4007  Chained = flags & 4;
4008  Selector = (flags & 2) ? selector_controller :
4009  (flags & 1) ? selector_key_switch : selector_none;
4010  Patterns = _3ewg->ReadUint8();
4011  _3ewg->ReadUint8(); // chosen row
4012  _3ewg->ReadUint8(); // unknown
4013  _3ewg->ReadUint8(); // unknown
4014  _3ewg->ReadUint8(); // unknown
4015  KeySwitchRange.low = _3ewg->ReadUint8();
4016  KeySwitchRange.high = _3ewg->ReadUint8();
4017  Controller = _3ewg->ReadUint8();
4018  PlayRange.low = _3ewg->ReadUint8();
4019  PlayRange.high = _3ewg->ReadUint8();
4020 
4021  int n = std::min(int(Articulations), 32);
4022  for (int i = 0 ; i < n ; i++) {
4023  _3ewg->ReadString(pArticulations[i], 32);
4024  }
4025  _3ewg->SetPos(1072);
4026  n = std::min(int(Patterns), 32);
4027  for (int i = 0 ; i < n ; i++) {
4028  _3ewg->ReadString(pPatterns[i].Name, 16);
4029  pPatterns[i].Size = _3ewg->ReadUint8();
4030  _3ewg->Read(&pPatterns[i][0], 1, 32);
4031  }
4032  }
4033 
4035  Articulations(0),
4036  Patterns(0),
4037  Selector(selector_none),
4038  Controller(0),
4039  Polyphonic(false),
4040  Chained(false)
4041  {
4042  PlayRange.low = PlayRange.high = 0;
4044  }
4045 
4046  void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4047  pData[32] = 3;
4048  pData[33] = 16;
4049  pData[36] = Articulations;
4050  pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4051  (Selector == selector_controller ? 2 :
4052  (Selector == selector_key_switch ? 1 : 0));
4053  pData[38] = Patterns;
4054 
4055  pData[43] = KeySwitchRange.low;
4056  pData[44] = KeySwitchRange.high;
4057  pData[45] = Controller;
4058  pData[46] = PlayRange.low;
4059  pData[47] = PlayRange.high;
4060 
4061  char* str = reinterpret_cast<char*>(pData);
4062  int pos = 48;
4063  int n = std::min(int(Articulations), 32);
4064  for (int i = 0 ; i < n ; i++, pos += 32) {
4065  strncpy(&str[pos], pArticulations[i].c_str(), 32);
4066  }
4067 
4068  pos = 1072;
4069  n = std::min(int(Patterns), 32);
4070  for (int i = 0 ; i < n ; i++, pos += 49) {
4071  strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4072  pData[pos + 16] = pPatterns[i].Size;
4073  memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4074  }
4075  }
4076 
4077 // *************** Script ***************
4078 // *
4079 
4081  pGroup = group;
4082  pChunk = ckScri;
4083  if (ckScri) { // object is loaded from file ...
4084  // read header
4085  uint32_t headerSize = ckScri->ReadUint32();
4086  Compression = (Compression_t) ckScri->ReadUint32();
4087  Encoding = (Encoding_t) ckScri->ReadUint32();
4088  Language = (Language_t) ckScri->ReadUint32();
4089  Bypass = (Language_t) ckScri->ReadUint32() & 1;
4090  crc = ckScri->ReadUint32();
4091  uint32_t nameSize = ckScri->ReadUint32();
4092  Name.resize(nameSize, ' ');
4093  for (int i = 0; i < nameSize; ++i)
4094  Name[i] = ckScri->ReadUint8();
4095  // to handle potential future extensions of the header
4096  ckScri->SetPos(sizeof(int32_t) + headerSize);
4097  // read actual script data
4098  uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4099  data.resize(scriptSize);
4100  for (int i = 0; i < scriptSize; ++i)
4101  data[i] = ckScri->ReadUint8();
4102  } else { // this is a new script object, so just initialize it as such ...
4103  Compression = COMPRESSION_NONE;
4104  Encoding = ENCODING_ASCII;
4105  Language = LANGUAGE_NKSP;
4106  Bypass = false;
4107  crc = 0;
4108  Name = "Unnamed Script";
4109  }
4110  }
4111 
4113  }
4114 
4119  String s;
4120  s.resize(data.size(), ' ');
4121  memcpy(&s[0], &data[0], data.size());
4122  return s;
4123  }
4124 
4131  void Script::SetScriptAsText(const String& text) {
4132  data.resize(text.size());
4133  memcpy(&data[0], &text[0], text.size());
4134  }
4135 
4146  // recalculate CRC32 check sum
4147  __resetCRC(crc);
4148  __calculateCRC(&data[0], data.size(), crc);
4149  __encodeCRC(crc);
4150  // make sure chunk exists and has the required size
4151  const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4152  if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4153  else pChunk->Resize(chunkSize);
4154  // fill the chunk data to be written to disk
4155  uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4156  int pos = 0;
4157  store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4158  pos += sizeof(int32_t);
4159  store32(&pData[pos], Compression);
4160  pos += sizeof(int32_t);
4161  store32(&pData[pos], Encoding);
4162  pos += sizeof(int32_t);
4163  store32(&pData[pos], Language);
4164  pos += sizeof(int32_t);
4165  store32(&pData[pos], Bypass ? 1 : 0);
4166  pos += sizeof(int32_t);
4167  store32(&pData[pos], crc);
4168  pos += sizeof(int32_t);
4169  store32(&pData[pos], Name.size());
4170  pos += sizeof(int32_t);
4171  for (int i = 0; i < Name.size(); ++i, ++pos)
4172  pData[pos] = Name[i];
4173  for (int i = 0; i < data.size(); ++i, ++pos)
4174  pData[pos] = data[i];
4175  }
4176 
4184  if (this->pGroup = pGroup) return;
4185  if (pChunk)
4186  pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4187  this->pGroup = pGroup;
4188  }
4189 
4197  return pGroup;
4198  }
4199 
4201  File* pFile = pGroup->pFile;
4202  for (int i = 0; pFile->GetInstrument(i); ++i) {
4203  Instrument* instr = pFile->GetInstrument(i);
4204  instr->RemoveScript(this);
4205  }
4206  }
4207 
4208 // *************** ScriptGroup ***************
4209 // *
4210 
4212  pFile = file;
4213  pList = lstRTIS;
4214  pScripts = NULL;
4215  if (lstRTIS) {
4216  RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4217  ::LoadString(ckName, Name);
4218  } else {
4219  Name = "Default Group";
4220  }
4221  }
4222 
4224  if (pScripts) {
4225  std::list<Script*>::iterator iter = pScripts->begin();
4226  std::list<Script*>::iterator end = pScripts->end();
4227  while (iter != end) {
4228  delete *iter;
4229  ++iter;
4230  }
4231  delete pScripts;
4232  }
4233  }
4234 
4245  if (pScripts) {
4246  if (!pList)
4247  pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4248 
4249  // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4250  ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4251 
4252  for (std::list<Script*>::iterator it = pScripts->begin();
4253  it != pScripts->end(); ++it)
4254  {
4255  (*it)->UpdateChunks(pProgress);
4256  }
4257  }
4258  }
4259 
4268  if (!pScripts) LoadScripts();
4269  std::list<Script*>::iterator it = pScripts->begin();
4270  for (uint i = 0; it != pScripts->end(); ++i, ++it)
4271  if (i == index) return *it;
4272  return NULL;
4273  }
4274 
4287  if (!pScripts) LoadScripts();
4288  Script* pScript = new Script(this, NULL);
4289  pScripts->push_back(pScript);
4290  return pScript;
4291  }
4292 
4304  if (!pScripts) LoadScripts();
4305  std::list<Script*>::iterator iter =
4306  find(pScripts->begin(), pScripts->end(), pScript);
4307  if (iter == pScripts->end())
4308  throw gig::Exception("Could not delete script, could not find given script");
4309  pScripts->erase(iter);
4310  pScript->RemoveAllScriptReferences();
4311  if (pScript->pChunk)
4312  pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4313  delete pScript;
4314  }
4315 
4317  if (pScripts) return;
4318  pScripts = new std::list<Script*>;
4319  if (!pList) return;
4320 
4321  for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4322  ck = pList->GetNextSubChunk())
4323  {
4324  if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4325  pScripts->push_back(new Script(this, ck));
4326  }
4327  }
4328  }
4329 
4330 // *************** Instrument ***************
4331 // *
4332 
4333  Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4334  static const DLS::Info::string_length_t fixedStringLengths[] = {
4335  { CHUNK_ID_INAM, 64 },
4336  { CHUNK_ID_ISFT, 12 },
4337  { 0, 0 }
4338  };
4339  pInfo->SetFixedStringLengths(fixedStringLengths);
4340 
4341  // Initialization
4342  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4343  EffectSend = 0;
4344  Attenuation = 0;
4345  FineTune = 0;
4346  PitchbendRange = 0;
4347  PianoReleaseMode = false;
4348  DimensionKeyRange.low = 0;
4349  DimensionKeyRange.high = 0;
4350  pMidiRules = new MidiRule*[3];
4351  pMidiRules[0] = NULL;
4352  pScriptRefs = NULL;
4353 
4354  // Loading
4355  RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
4356  if (lart) {
4357  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4358  if (_3ewg) {
4359  EffectSend = _3ewg->ReadUint16();
4360  Attenuation = _3ewg->ReadInt32();
4361  FineTune = _3ewg->ReadInt16();
4362  PitchbendRange = _3ewg->ReadInt16();
4363  uint8_t dimkeystart = _3ewg->ReadUint8();
4364  PianoReleaseMode = dimkeystart & 0x01;
4365  DimensionKeyRange.low = dimkeystart >> 1;
4366  DimensionKeyRange.high = _3ewg->ReadUint8();
4367 
4368  if (_3ewg->GetSize() > 32) {
4369  // read MIDI rules
4370  int i = 0;
4371  _3ewg->SetPos(32);
4372  uint8_t id1 = _3ewg->ReadUint8();
4373  uint8_t id2 = _3ewg->ReadUint8();
4374 
4375  if (id2 == 16) {
4376  if (id1 == 4) {
4377  pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4378  } else if (id1 == 0) {
4379  pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4380  } else if (id1 == 3) {
4381  pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4382  } else {
4383  pMidiRules[i++] = new MidiRuleUnknown;
4384  }
4385  }
4386  else if (id1 != 0 || id2 != 0) {
4387  pMidiRules[i++] = new MidiRuleUnknown;
4388  }
4389  //TODO: all the other types of rules
4390 
4391  pMidiRules[i] = NULL;
4392  }
4393  }
4394  }
4395 
4396  if (pFile->GetAutoLoad()) {
4397  if (!pRegions) pRegions = new RegionList;
4398  RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4399  if (lrgn) {
4400  RIFF::List* rgn = lrgn->GetFirstSubList();
4401  while (rgn) {
4402  if (rgn->GetListType() == LIST_TYPE_RGN) {
4403  __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4404  pRegions->push_back(new Region(this, rgn));
4405  }
4406  rgn = lrgn->GetNextSubList();
4407  }
4408  // Creating Region Key Table for fast lookup
4410  }
4411  }
4412 
4413  // own gig format extensions
4414  RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4415  if (lst3LS) {
4416  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4417  if (ckSCSL) {
4418  int headerSize = ckSCSL->ReadUint32();
4419  int slotCount = ckSCSL->ReadUint32();
4420  if (slotCount) {
4421  int slotSize = ckSCSL->ReadUint32();
4422  ckSCSL->SetPos(headerSize); // in case of future header extensions
4423  int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4424  for (int i = 0; i < slotCount; ++i) {
4425  _ScriptPooolEntry e;
4426  e.fileOffset = ckSCSL->ReadUint32();
4427  e.bypass = ckSCSL->ReadUint32() & 1;
4428  if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4429  scriptPoolFileOffsets.push_back(e);
4430  }
4431  }
4432  }
4433  }
4434 
4435  __notify_progress(pProgress, 1.0f); // notify done
4436  }
4437 
4439  for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4440  RegionList::iterator iter = pRegions->begin();
4441  RegionList::iterator end = pRegions->end();
4442  for (; iter != end; ++iter) {
4443  gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4444  int low = pRegion->KeyRange.low > 0 ? pRegion->KeyRange.low : 0;
4445  int high = pRegion->KeyRange.high > 127 ? 127 : pRegion->KeyRange.high;
4446  for (int iKey = low; iKey <= high; iKey++) {
4447  RegionKeyTable[iKey] = pRegion;
4448  }
4449  }
4450  }
4451 
4453  for (int i = 0 ; pMidiRules[i] ; i++) {
4454  delete pMidiRules[i];
4455  }
4456  delete[] pMidiRules;
4457  if (pScriptRefs) delete pScriptRefs;
4458  }
4459 
4471  // first update base classes' chunks
4472  DLS::Instrument::UpdateChunks(pProgress);
4473 
4474  // update Regions' chunks
4475  {
4476  RegionList::iterator iter = pRegions->begin();
4477  RegionList::iterator end = pRegions->end();
4478  for (; iter != end; ++iter)
4479  (*iter)->UpdateChunks(pProgress);
4480  }
4481 
4482  // make sure 'lart' RIFF list chunk exists
4484  if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4485  // make sure '3ewg' RIFF chunk exists
4486  RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4487  if (!_3ewg) {
4488  File* pFile = (File*) GetParent();
4489 
4490  // 3ewg is bigger in gig3, as it includes the iMIDI rules
4491  int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4492  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4493  memset(_3ewg->LoadChunkData(), 0, size);
4494  }
4495  // update '3ewg' RIFF chunk
4496  uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4497  store16(&pData[0], EffectSend);
4498  store32(&pData[2], Attenuation);
4499  store16(&pData[6], FineTune);
4500  store16(&pData[8], PitchbendRange);
4501  const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4502  DimensionKeyRange.low << 1;
4503  pData[10] = dimkeystart;
4504  pData[11] = DimensionKeyRange.high;
4505 
4506  if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4507  pData[32] = 0;
4508  pData[33] = 0;
4509  } else {
4510  for (int i = 0 ; pMidiRules[i] ; i++) {
4511  pMidiRules[i]->UpdateChunks(pData);
4512  }
4513  }
4514 
4515  // own gig format extensions
4516  if (ScriptSlotCount()) {
4517  // make sure we have converted the original loaded script file
4518  // offsets into valid Script object pointers
4519  LoadScripts();
4520 
4522  if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4523  const int slotCount = pScriptRefs->size();
4524  const int headerSize = 3 * sizeof(uint32_t);
4525  const int slotSize = 2 * sizeof(uint32_t);
4526  const int totalChunkSize = headerSize + slotCount * slotSize;
4527  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4528  if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4529  else ckSCSL->Resize(totalChunkSize);
4530  uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4531  int pos = 0;
4532  store32(&pData[pos], headerSize);
4533  pos += sizeof(uint32_t);
4534  store32(&pData[pos], slotCount);
4535  pos += sizeof(uint32_t);
4536  store32(&pData[pos], slotSize);
4537  pos += sizeof(uint32_t);
4538  for (int i = 0; i < slotCount; ++i) {
4539  // arbitrary value, the actual file offset will be updated in
4540  // UpdateScriptFileOffsets() after the file has been resized
4541  int bogusFileOffset = 0;
4542  store32(&pData[pos], bogusFileOffset);
4543  pos += sizeof(uint32_t);
4544  store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4545  pos += sizeof(uint32_t);
4546  }
4547  } else {
4548  // no script slots, so get rid of any LS custom RIFF chunks (if any)
4550  if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4551  }
4552  }
4553 
4555  // own gig format extensions
4556  if (pScriptRefs && pScriptRefs->size() > 0) {
4558  RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4559  const int slotCount = pScriptRefs->size();
4560  const int headerSize = 3 * sizeof(uint32_t);
4561  ckSCSL->SetPos(headerSize);
4562  for (int i = 0; i < slotCount; ++i) {
4563  uint32_t fileOffset =
4564  (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4565  (*pScriptRefs)[i].script->pChunk->GetPos() -
4567  ckSCSL->WriteUint32(&fileOffset);
4568  // jump over flags entry (containing the bypass flag)
4569  ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4570  }
4571  }
4572  }
4573 
4581  Region* Instrument::GetRegion(unsigned int Key) {
4582  if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4583  return RegionKeyTable[Key];
4584 
4585  /*for (int i = 0; i < Regions; i++) {
4586  if (Key <= pRegions[i]->KeyRange.high &&
4587  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
4588  }
4589  return NULL;*/
4590  }
4591 
4600  if (!pRegions) return NULL;
4601  RegionsIterator = pRegions->begin();
4602  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4603  }
4604 
4614  if (!pRegions) return NULL;
4615  RegionsIterator++;
4616  return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4617  }
4618 
4620  // create new Region object (and its RIFF chunks)
4622  if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4623  RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4624  Region* pNewRegion = new Region(this, rgn);
4625  pRegions->push_back(pNewRegion);
4626  Regions = pRegions->size();
4627  // update Region key table for fast lookup
4629  // done
4630  return pNewRegion;
4631  }
4632 
4634  if (!pRegions) return;
4636  // update Region key table for fast lookup
4638  }
4639 
4668  if (dst && GetParent() != dst->GetParent())
4669  throw Exception(
4670  "gig::Instrument::MoveTo() can only be used for moving within "
4671  "the same gig file."
4672  );
4673 
4674  File* pFile = (File*) GetParent();
4675 
4676  // move this instrument within the instrument list
4677  {
4678  DLS::File::InstrumentList& list = *pFile->pInstruments;
4679 
4680  DLS::File::InstrumentList::iterator itFrom =
4681  std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4682 
4683  DLS::File::InstrumentList::iterator itTo =
4684  std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4685 
4686  list.splice(itTo, list, itFrom);
4687  }
4688 
4689  // move the instrument's actual list RIFF chunk appropriately
4690  RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4691  lstCkInstruments->MoveSubChunk(
4692  this->pCkInstrument,
4693  (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4694  );
4695  }
4696 
4708  return pMidiRules[i];
4709  }
4710 
4717  delete pMidiRules[0];
4719  pMidiRules[0] = r;
4720  pMidiRules[1] = 0;
4721  return r;
4722  }
4723 
4730  delete pMidiRules[0];
4731  MidiRuleLegato* r = new MidiRuleLegato;
4732  pMidiRules[0] = r;
4733  pMidiRules[1] = 0;
4734  return r;
4735  }
4736 
4743  delete pMidiRules[0];
4745  pMidiRules[0] = r;
4746  pMidiRules[1] = 0;
4747  return r;
4748  }
4749 
4756  delete pMidiRules[i];
4757  pMidiRules[i] = 0;
4758  }
4759 
4761  if (pScriptRefs) return;
4762  pScriptRefs = new std::vector<_ScriptPooolRef>;
4763  if (scriptPoolFileOffsets.empty()) return;
4764  File* pFile = (File*) GetParent();
4765  for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4766  uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4767  for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4768  ScriptGroup* group = pFile->GetScriptGroup(i);
4769  for (uint s = 0; group->GetScript(s); ++s) {
4770  Script* script = group->GetScript(s);
4771  if (script->pChunk) {
4772  uint32_t offset = script->pChunk->GetFilePos() -
4773  script->pChunk->GetPos() -
4775  if (offset == soughtOffset)
4776  {
4777  _ScriptPooolRef ref;
4778  ref.script = script;
4779  ref.bypass = scriptPoolFileOffsets[k].bypass;
4780  pScriptRefs->push_back(ref);
4781  break;
4782  }
4783  }
4784  }
4785  }
4786  }
4787  // we don't need that anymore
4788  scriptPoolFileOffsets.clear();
4789  }
4790 
4804  LoadScripts();
4805  if (index >= pScriptRefs->size()) return NULL;
4806  return pScriptRefs->at(index).script;
4807  }
4808 
4844  void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4845  LoadScripts();
4846  _ScriptPooolRef ref = { pScript, bypass };
4847  pScriptRefs->push_back(ref);
4848  }
4849 
4864  void Instrument::SwapScriptSlots(uint index1, uint index2) {
4865  LoadScripts();
4866  if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4867  return;
4868  _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4869  (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4870  (*pScriptRefs)[index2] = tmp;
4871  }
4872 
4879  void Instrument::RemoveScriptSlot(uint index) {
4880  LoadScripts();
4881  if (index >= pScriptRefs->size()) return;
4882  pScriptRefs->erase( pScriptRefs->begin() + index );
4883  }
4884 
4898  LoadScripts();
4899  for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4900  if ((*pScriptRefs)[i].script == pScript) {
4901  pScriptRefs->erase( pScriptRefs->begin() + i );
4902  }
4903  }
4904  }
4905 
4921  return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4922  }
4923 
4941  if (index >= ScriptSlotCount()) return false;
4942  return pScriptRefs ? pScriptRefs->at(index).bypass
4943  : scriptPoolFileOffsets.at(index).bypass;
4944 
4945  }
4946 
4960  void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4961  if (index >= ScriptSlotCount()) return;
4962  if (pScriptRefs)
4963  pScriptRefs->at(index).bypass = bBypass;
4964  else
4965  scriptPoolFileOffsets.at(index).bypass = bBypass;
4966  }
4967 
4978  CopyAssign(orig, NULL);
4979  }
4980 
4989  void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4990  // handle base class
4991  // (without copying DLS region stuff)
4993 
4994  // handle own member variables
4995  Attenuation = orig->Attenuation;
4996  EffectSend = orig->EffectSend;
4997  FineTune = orig->FineTune;
5001  scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5002  pScriptRefs = orig->pScriptRefs;
5003 
5004  // free old midi rules
5005  for (int i = 0 ; pMidiRules[i] ; i++) {
5006  delete pMidiRules[i];
5007  }
5008  //TODO: MIDI rule copying
5009  pMidiRules[0] = NULL;
5010 
5011  // delete all old regions
5012  while (Regions) DeleteRegion(GetFirstRegion());
5013  // create new regions and copy them from original
5014  {
5015  RegionList::const_iterator it = orig->pRegions->begin();
5016  for (int i = 0; i < orig->Regions; ++i, ++it) {
5017  Region* dstRgn = AddRegion();
5018  //NOTE: Region does semi-deep copy !
5019  dstRgn->CopyAssign(
5020  static_cast<gig::Region*>(*it),
5021  mSamples
5022  );
5023  }
5024  }
5025 
5027  }
5028 
5029 
5030 // *************** Group ***************
5031 // *
5032 
5039  Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5040  pFile = file;
5041  pNameChunk = ck3gnm;
5042  ::LoadString(pNameChunk, Name);
5043  }
5044 
5046  // remove the chunk associated with this group (if any)
5047  if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5048  }
5049 
5060  void Group::UpdateChunks(progress_t* pProgress) {
5061  // make sure <3gri> and <3gnl> list chunks exist
5062  RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5063  if (!_3gri) {
5064  _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5065  pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5066  }
5067  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5068  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5069 
5070  if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5071  // v3 has a fixed list of 128 strings, find a free one
5072  for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5073  if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5074  pNameChunk = ck;
5075  break;
5076  }
5077  }
5078  }
5079 
5080  // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5081  ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5082  }
5083 
5096  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5097  for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5098  if (pSample->GetGroup() == this) return pSample;
5099  }
5100  return NULL;
5101  }
5102 
5114  // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5115  for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5116  if (pSample->GetGroup() == this) return pSample;
5117  }
5118  return NULL;
5119  }
5120 
5124  void Group::AddSample(Sample* pSample) {
5125  pSample->pGroup = this;
5126  }
5127 
5135  // get "that" other group first
5136  Group* pOtherGroup = NULL;
5137  for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5138  if (pOtherGroup != this) break;
5139  }
5140  if (!pOtherGroup) throw Exception(
5141  "Could not move samples to another group, since there is no "
5142  "other Group. This is a bug, report it!"
5143  );
5144  // now move all samples of this group to the other group
5145  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5146  pOtherGroup->AddSample(pSample);
5147  }
5148  }
5149 
5150 
5151 
5152 // *************** File ***************
5153 // *
5154 
5157  0, 2, 19980628 & 0xffff, 19980628 >> 16
5158  };
5159 
5162  0, 3, 20030331 & 0xffff, 20030331 >> 16
5163  };
5164 
5165  static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5166  { CHUNK_ID_IARL, 256 },
5167  { CHUNK_ID_IART, 128 },
5168  { CHUNK_ID_ICMS, 128 },
5169  { CHUNK_ID_ICMT, 1024 },
5170  { CHUNK_ID_ICOP, 128 },
5171  { CHUNK_ID_ICRD, 128 },
5172  { CHUNK_ID_IENG, 128 },
5173  { CHUNK_ID_IGNR, 128 },
5174  { CHUNK_ID_IKEY, 128 },
5175  { CHUNK_ID_IMED, 128 },
5176  { CHUNK_ID_INAM, 128 },
5177  { CHUNK_ID_IPRD, 128 },
5178  { CHUNK_ID_ISBJ, 128 },
5179  { CHUNK_ID_ISFT, 128 },
5180  { CHUNK_ID_ISRC, 128 },
5181  { CHUNK_ID_ISRF, 128 },
5182  { CHUNK_ID_ITCH, 128 },
5183  { 0, 0 }
5184  };
5185 
5187  bAutoLoad = true;
5188  *pVersion = VERSION_3;
5189  pGroups = NULL;
5190  pScriptGroups = NULL;
5191  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5192  pInfo->ArchivalLocation = String(256, ' ');
5193 
5194  // add some mandatory chunks to get the file chunks in right
5195  // order (INFO chunk will be moved to first position later)
5199 
5200  GenerateDLSID();
5201  }
5202 
5204  bAutoLoad = true;
5205  pGroups = NULL;
5206  pScriptGroups = NULL;
5207  pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5208  }
5209 
5211  if (pGroups) {
5212  std::list<Group*>::iterator iter = pGroups->begin();
5213  std::list<Group*>::iterator end = pGroups->end();
5214  while (iter != end) {
5215  delete *iter;
5216  ++iter;
5217  }
5218  delete pGroups;
5219  }
5220  if (pScriptGroups) {
5221  std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5222  std::list<ScriptGroup*>::iterator end = pScriptGroups->end();
5223  while (iter != end) {
5224  delete *iter;
5225  ++iter;
5226  }
5227  delete pScriptGroups;
5228  }
5229  }
5230 
5232  if (!pSamples) LoadSamples(pProgress);
5233  if (!pSamples) return NULL;
5234  SamplesIterator = pSamples->begin();
5235  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5236  }
5237 
5239  if (!pSamples) return NULL;
5240  SamplesIterator++;
5241  return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5242  }
5243 
5249  Sample* File::GetSample(uint index) {
5250  if (!pSamples) LoadSamples();
5251  if (!pSamples) return NULL;
5252  DLS::File::SampleList::iterator it = pSamples->begin();
5253  for (int i = 0; i < index; ++i) {
5254  ++it;
5255  if (it == pSamples->end()) return NULL;
5256  }
5257  if (it == pSamples->end()) return NULL;
5258  return static_cast<gig::Sample*>( *it );
5259  }
5260 
5269  if (!pSamples) LoadSamples();
5272  // create new Sample object and its respective 'wave' list chunk
5273  RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5274  Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5275 
5276  // add mandatory chunks to get the chunks in right order
5277  wave->AddSubChunk(CHUNK_ID_FMT, 16);
5278  wave->AddSubList(LIST_TYPE_INFO);
5279 
5280  pSamples->push_back(pSample);
5281  return pSample;
5282  }
5283 
5293  void File::DeleteSample(Sample* pSample) {
5294  if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5295  SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5296  if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5297  if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5298  pSamples->erase(iter);
5299  delete pSample;
5300 
5301  SampleList::iterator tmp = SamplesIterator;
5302  // remove all references to the sample
5303  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5304  instrument = GetNextInstrument()) {
5305  for (Region* region = instrument->GetFirstRegion() ; region ;
5306  region = instrument->GetNextRegion()) {
5307 
5308  if (region->GetSample() == pSample) region->SetSample(NULL);
5309 
5310  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5311  gig::DimensionRegion *d = region->pDimensionRegions[i];
5312  if (d->pSample == pSample) d->pSample = NULL;
5313  }
5314  }
5315  }
5316  SamplesIterator = tmp; // restore iterator
5317  }
5318 
5320  LoadSamples(NULL);
5321  }
5322 
5323  void File::LoadSamples(progress_t* pProgress) {
5324  // Groups must be loaded before samples, because samples will try
5325  // to resolve the group they belong to
5326  if (!pGroups) LoadGroups();
5327 
5328  if (!pSamples) pSamples = new SampleList;
5329 
5330  RIFF::File* file = pRIFF;
5331 
5332  // just for progress calculation
5333  int iSampleIndex = 0;
5334  int iTotalSamples = WavePoolCount;
5335 
5336  // check if samples should be loaded from extension files
5337  int lastFileNo = 0;
5338  for (int i = 0 ; i < WavePoolCount ; i++) {
5339  if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5340  }
5341  String name(pRIFF->GetFileName());
5342  int nameLen = name.length();
5343  char suffix[6];
5344  if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5345 
5346  for (int fileNo = 0 ; ; ) {
5347  RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5348  if (wvpl) {
5349  unsigned long wvplFileOffset = wvpl->GetFilePos();
5350  RIFF::List* wave = wvpl->GetFirstSubList();
5351  while (wave) {
5352  if (wave->GetListType() == LIST_TYPE_WAVE) {
5353  // notify current progress
5354  const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5355  __notify_progress(pProgress, subprogress);
5356 
5357  unsigned long waveFileOffset = wave->GetFilePos();
5358  pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5359 
5360  iSampleIndex++;
5361  }
5362  wave = wvpl->GetNextSubList();
5363  }
5364 
5365  if (fileNo == lastFileNo) break;
5366 
5367  // open extension file (*.gx01, *.gx02, ...)
5368  fileNo++;
5369  sprintf(suffix, ".gx%02d", fileNo);
5370  name.replace(nameLen, 5, suffix);
5371  file = new RIFF::File(name);
5372  ExtensionFiles.push_back(file);
5373  } else break;
5374  }
5375 
5376  __notify_progress(pProgress, 1.0); // notify done
5377  }
5378 
5380  if (!pInstruments) LoadInstruments();
5381  if (!pInstruments) return NULL;
5382  InstrumentsIterator = pInstruments->begin();
5383  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5384  }
5385 
5387  if (!pInstruments) return NULL;
5389  return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
5390  }
5391 
5399  Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
5400  if (!pInstruments) {
5401  // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
5402 
5403  // sample loading subtask
5404  progress_t subprogress;
5405  __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5406  __notify_progress(&subprogress, 0.0f);
5407  if (GetAutoLoad())
5408  GetFirstSample(&subprogress); // now force all samples to be loaded
5409  __notify_progress(&subprogress, 1.0f);
5410 
5411  // instrument loading subtask
5412  if (pProgress && pProgress->callback) {
5413  subprogress.__range_min = subprogress.__range_max;
5414  subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
5415  }
5416  __notify_progress(&subprogress, 0.0f);
5417  LoadInstruments(&subprogress);
5418  __notify_progress(&subprogress, 1.0f);
5419  }
5420  if (!pInstruments) return NULL;
5421  InstrumentsIterator = pInstruments->begin();
5422  for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
5423  if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
5425  }
5426  return NULL;
5427  }
5428 
5437  if (!pInstruments) LoadInstruments();
5439  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5440  RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5441 
5442  // add mandatory chunks to get the chunks in right order
5443  lstInstr->AddSubList(LIST_TYPE_INFO);
5444  lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5445 
5446  Instrument* pInstrument = new Instrument(this, lstInstr);
5447  pInstrument->GenerateDLSID();
5448 
5449  lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5450 
5451  // this string is needed for the gig to be loadable in GSt:
5452  pInstrument->pInfo->Software = "Endless Wave";
5453 
5454  pInstruments->push_back(pInstrument);
5455  return pInstrument;
5456  }
5457 
5474  Instrument* instr = AddInstrument();
5475  instr->CopyAssign(orig);
5476  return instr;
5477  }
5478 
5490  void File::AddContentOf(File* pFile) {
5491  static int iCallCount = -1;
5492  iCallCount++;
5493  std::map<Group*,Group*> mGroups;
5494  std::map<Sample*,Sample*> mSamples;
5495 
5496  // clone sample groups
5497  for (int i = 0; pFile->GetGroup(i); ++i) {
5498  Group* g = AddGroup();
5499  g->Name =
5500  "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5501  mGroups[pFile->GetGroup(i)] = g;
5502  }
5503 
5504  // clone samples (not waveform data here yet)
5505  for (int i = 0; pFile->GetSample(i); ++i) {
5506  Sample* s = AddSample();
5507  s->CopyAssignMeta(pFile->GetSample(i));
5508  mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5509  mSamples[pFile->GetSample(i)] = s;
5510  }
5511 
5512  //BUG: For some reason this method only works with this additional
5513  // Save() call in between here.
5514  //
5515  // Important: The correct one of the 2 Save() methods has to be called
5516  // here, depending on whether the file is completely new or has been
5517  // saved to disk already, otherwise it will result in data corruption.
5518  if (pRIFF->IsNew())
5519  Save(GetFileName());
5520  else
5521  Save();
5522 
5523  // clone instruments
5524  // (passing the crosslink table here for the cloned samples)
5525  for (int i = 0; pFile->GetInstrument(i); ++i) {
5526  Instrument* instr = AddInstrument();
5527  instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5528  }
5529 
5530  // Mandatory: file needs to be saved to disk at this point, so this
5531  // file has the correct size and data layout for writing the samples'
5532  // waveform data to disk.
5533  Save();
5534 
5535  // clone samples' waveform data
5536  // (using direct read & write disk streaming)
5537  for (int i = 0; pFile->GetSample(i); ++i) {
5538  mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5539  }
5540  }
5541 
5550  void File::DeleteInstrument(Instrument* pInstrument) {
5551  if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
5552  InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
5553  if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
5554  pInstruments->erase(iter);
5555  delete pInstrument;
5556  }
5557 
5559  LoadInstruments(NULL);
5560  }
5561 
5564  RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5565  if (lstInstruments) {
5566  int iInstrumentIndex = 0;
5567  RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
5568  while (lstInstr) {
5569  if (lstInstr->GetListType() == LIST_TYPE_INS) {
5570  // notify current progress
5571  const float localProgress = (float) iInstrumentIndex / (float) Instruments;
5572  __notify_progress(pProgress, localProgress);
5573 
5574  // divide local progress into subprogress for loading current Instrument
5575  progress_t subprogress;
5576  __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
5577 
5578  pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
5579 
5580  iInstrumentIndex++;
5581  }
5582  lstInstr = lstInstruments->GetNextSubList();
5583  }
5584  __notify_progress(pProgress, 1.0); // notify done
5585  }
5586  }
5587 
5591  void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5593  if (!_3crc) return;
5594 
5595  // get the index of the sample
5596  int iWaveIndex = -1;
5597  File::SampleList::iterator iter = pSamples->begin();
5598  File::SampleList::iterator end = pSamples->end();
5599  for (int index = 0; iter != end; ++iter, ++index) {
5600  if (*iter == pSample) {
5601  iWaveIndex = index;
5602  break;
5603  }
5604  }
5605  if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5606 
5607  // write the CRC-32 checksum to disk
5608  _3crc->SetPos(iWaveIndex * 8);
5609  uint32_t tmp = 1;
5610  _3crc->WriteUint32(&tmp); // unknown, always 1?
5611  _3crc->WriteUint32(&crc);
5612  }
5613 
5615  if (!pGroups) LoadGroups();
5616  // there must always be at least one group
5617  GroupsIterator = pGroups->begin();
5618  return *GroupsIterator;
5619  }
5620 
5622  if (!pGroups) return NULL;
5623  ++GroupsIterator;
5624  return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5625  }
5626 
5633  Group* File::GetGroup(uint index) {
5634  if (!pGroups) LoadGroups();
5635  GroupsIterator = pGroups->begin();
5636  for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5637  if (i == index) return *GroupsIterator;
5638  ++GroupsIterator;
5639  }
5640  return NULL;
5641  }
5642 
5654  if (!pGroups) LoadGroups();
5655  GroupsIterator = pGroups->begin();
5656  for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5657  if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5658  return NULL;
5659  }
5660 
5662  if (!pGroups) LoadGroups();
5663  // there must always be at least one group
5665  Group* pGroup = new Group(this, NULL);
5666  pGroups->push_back(pGroup);
5667  return pGroup;
5668  }
5669 
5679  void File::DeleteGroup(Group* pGroup) {
5680  if (!pGroups) LoadGroups();
5681  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5682  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5683  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5684  // delete all members of this group
5685  for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5686  DeleteSample(pSample);
5687  }
5688  // now delete this group object
5689  pGroups->erase(iter);
5690  delete pGroup;
5691  }
5692 
5704  if (!pGroups) LoadGroups();
5705  std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5706  if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5707  if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5708  // move all members of this group to another group
5709  pGroup->MoveAll();
5710  pGroups->erase(iter);
5711  delete pGroup;
5712  }
5713 
5715  if (!pGroups) pGroups = new std::list<Group*>;
5716  // try to read defined groups from file
5718  if (lst3gri) {
5719  RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5720  if (lst3gnl) {
5721  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5722  while (ck) {
5723  if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5724  if (pVersion && pVersion->major == 3 &&
5725  strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5726 
5727  pGroups->push_back(new Group(this, ck));
5728  }
5729  ck = lst3gnl->GetNextSubChunk();
5730  }
5731  }
5732  }
5733  // if there were no group(s), create at least the mandatory default group
5734  if (!pGroups->size()) {
5735  Group* pGroup = new Group(this, NULL);
5736  pGroup->Name = "Default Group";
5737  pGroups->push_back(pGroup);
5738  }
5739  }
5740 
5749  if (!pScriptGroups) LoadScriptGroups();
5750  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5751  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5752  if (i == index) return *it;
5753  return NULL;
5754  }
5755 
5765  if (!pScriptGroups) LoadScriptGroups();
5766  std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5767  for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5768  if ((*it)->Name == name) return *it;
5769  return NULL;
5770  }
5771 
5781  if (!pScriptGroups) LoadScriptGroups();
5782  ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5783  pScriptGroups->push_back(pScriptGroup);
5784  return pScriptGroup;
5785  }
5786 
5799  void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5800  if (!pScriptGroups) LoadScriptGroups();
5801  std::list<ScriptGroup*>::iterator iter =
5802  find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5803  if (iter == pScriptGroups->end())
5804  throw gig::Exception("Could not delete script group, could not find given script group");
5805  pScriptGroups->erase(iter);
5806  for (int i = 0; pScriptGroup->GetScript(i); ++i)
5807  pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5808  if (pScriptGroup->pList)
5809  pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5810  delete pScriptGroup;
5811  }
5812 
5814  if (pScriptGroups) return;
5815  pScriptGroups = new std::list<ScriptGroup*>;
5817  if (lstLS) {
5818  for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5819  lst = lstLS->GetNextSubList())
5820  {
5821  if (lst->GetListType() == LIST_TYPE_RTIS) {
5822  pScriptGroups->push_back(new ScriptGroup(this, lst));
5823  }
5824  }
5825  }
5826  }
5827 
5839  void File::UpdateChunks(progress_t* pProgress) {
5840  bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5841 
5843 
5844  // update own gig format extension chunks
5845  // (not part of the GigaStudio 4 format)
5846  //
5847  // This must be performed before writing the chunks for instruments,
5848  // because the instruments' script slots will write the file offsets
5849  // of the respective instrument script chunk as reference.
5850  if (pScriptGroups) {
5852  if (pScriptGroups->empty()) {
5853  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5854  } else {
5855  if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5856 
5857  // Update instrument script (group) chunks.
5858 
5859  for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5860  it != pScriptGroups->end(); ++it)
5861  {
5862  (*it)->UpdateChunks(pProgress);
5863  }
5864  }
5865  }
5866 
5867  // first update base class's chunks
5868  DLS::File::UpdateChunks(pProgress);
5869 
5870  if (newFile) {
5871  // INFO was added by Resource::UpdateChunks - make sure it
5872  // is placed first in file
5874  RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5875  if (first != info) {
5876  pRIFF->MoveSubChunk(info, first);
5877  }
5878  }
5879 
5880  // update group's chunks
5881  if (pGroups) {
5882  // make sure '3gri' and '3gnl' list chunks exist
5883  // (before updating the Group chunks)
5885  if (!_3gri) {
5886  _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5888  }
5889  RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5890  if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5891 
5892  // v3: make sure the file has 128 3gnm chunks
5893  // (before updating the Group chunks)
5894  if (pVersion && pVersion->major == 3) {
5895  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5896  for (int i = 0 ; i < 128 ; i++) {
5897  if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5898  if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5899  }
5900  }
5901 
5902  std::list<Group*>::iterator iter = pGroups->begin();
5903  std::list<Group*>::iterator end = pGroups->end();
5904  for (; iter != end; ++iter) {
5905  (*iter)->UpdateChunks(pProgress);
5906  }
5907  }
5908 
5909  // update einf chunk
5910 
5911  // The einf chunk contains statistics about the gig file, such
5912  // as the number of regions and samples used by each
5913  // instrument. It is divided in equally sized parts, where the
5914  // first part contains information about the whole gig file,
5915  // and the rest of the parts map to each instrument in the
5916  // file.
5917  //
5918  // At the end of each part there is a bit map of each sample
5919  // in the file, where a set bit means that the sample is used
5920  // by the file/instrument.
5921  //
5922  // Note that there are several fields with unknown use. These
5923  // are set to zero.
5924 
5925  int sublen = pSamples->size() / 8 + 49;
5926  int einfSize = (Instruments + 1) * sublen;
5927 
5929  if (einf) {
5930  if (einf->GetSize() != einfSize) {
5931  einf->Resize(einfSize);
5932  memset(einf->LoadChunkData(), 0, einfSize);
5933  }
5934  } else if (newFile) {
5935  einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5936  }
5937  if (einf) {
5938  uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5939 
5940  std::map<gig::Sample*,int> sampleMap;
5941  int sampleIdx = 0;
5942  for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5943  sampleMap[pSample] = sampleIdx++;
5944  }
5945 
5946  int totnbusedsamples = 0;
5947  int totnbusedchannels = 0;
5948  int totnbregions = 0;
5949  int totnbdimregions = 0;
5950  int totnbloops = 0;
5951  int instrumentIdx = 0;
5952 
5953  memset(&pData[48], 0, sublen - 48);
5954 
5955  for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5956  instrument = GetNextInstrument()) {
5957  int nbusedsamples = 0;
5958  int nbusedchannels = 0;
5959  int nbdimregions = 0;
5960  int nbloops = 0;
5961 
5962  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5963 
5964  for (Region* region = instrument->GetFirstRegion() ; region ;
5965  region = instrument->GetNextRegion()) {
5966  for (int i = 0 ; i < region->DimensionRegions ; i++) {
5967  gig::DimensionRegion *d = region->pDimensionRegions[i];
5968  if (d->pSample) {
5969  int sampleIdx = sampleMap[d->pSample];
5970  int byte = 48 + sampleIdx / 8;
5971  int bit = 1 << (sampleIdx & 7);
5972  if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5973  pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5974  nbusedsamples++;
5975  nbusedchannels += d->pSample->Channels;
5976 
5977  if ((pData[byte] & bit) == 0) {
5978  pData[byte] |= bit;
5979  totnbusedsamples++;
5980  totnbusedchannels += d->pSample->Channels;
5981  }
5982  }
5983  }
5984  if (d->SampleLoops) nbloops++;
5985  }
5986  nbdimregions += region->DimensionRegions;
5987  }
5988  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5989  // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5990  store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5991  store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5992  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5993  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5994  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5995  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5996  // next 8 bytes unknown
5997  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5998  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5999  // next 4 bytes unknown
6000 
6001  totnbregions += instrument->Regions;
6002  totnbdimregions += nbdimregions;
6003  totnbloops += nbloops;
6004  instrumentIdx++;
6005  }
6006  // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6007  // store32(&pData[0], sublen);
6008  store32(&pData[4], totnbusedchannels);
6009  store32(&pData[8], totnbusedsamples);
6010  store32(&pData[12], Instruments);
6011  store32(&pData[16], totnbregions);
6012  store32(&pData[20], totnbdimregions);
6013  store32(&pData[24], totnbloops);
6014  // next 8 bytes unknown
6015  // next 4 bytes unknown, not always 0
6016  store32(&pData[40], pSamples->size());
6017  // next 4 bytes unknown
6018  }
6019 
6020  // update 3crc chunk
6021 
6022  // The 3crc chunk contains CRC-32 checksums for the
6023  // samples. The actual checksum values will be filled in
6024  // later, by Sample::Write.
6025 
6027  if (_3crc) {
6028  _3crc->Resize(pSamples->size() * 8);
6029  } else if (newFile) {
6030  _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6031  _3crc->LoadChunkData();
6032 
6033  // the order of einf and 3crc is not the same in v2 and v3
6034  if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6035  }
6036  }
6037 
6040 
6041  for (Instrument* instrument = GetFirstInstrument(); instrument;
6042  instrument = GetNextInstrument())
6043  {
6044  instrument->UpdateScriptFileOffsets();
6045  }
6046  }
6047 
6063  void File::SetAutoLoad(bool b) {
6064  bAutoLoad = b;
6065  }
6066 
6072  return bAutoLoad;
6073  }
6074 
6075 
6076 
6077 // *************** Exception ***************
6078 // *
6079 
6080  Exception::Exception(String Message) : DLS::Exception(Message) {
6081  }
6082 
6084  std::cout << "gig::Exception: " << Message << std::endl;
6085  }
6086 
6087 
6088 // *************** functions ***************
6089 // *
6090 
6097  return PACKAGE;
6098  }
6099 
6105  return VERSION;
6106  }
6107 
6108 } // 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:4438
void SetScriptAsText(const String &text)
Replaces the current script with the new script source code text given by text.
Definition: gig.cpp:4131
void AddContentOf(File *pFile)
Add content of another existing file.
Definition: gig.cpp:5490
#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:5134
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:4452
Encapsulates articulation informations of a dimension region.
Definition: gig.h:366
void LoadScripts()
Definition: gig.cpp:4760
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:3641
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:4581
void AddSample(Sample *pSample)
Move Sample given by pSample from another Group to this Group.
Definition: gig.cpp:5124
String GetScriptAsText()
Returns the current script (i.e.
Definition: gig.cpp:4118
MidiRuleAlternator * AddMidiRuleAlternator()
Adds the alternator MIDI rule to the instrument.
Definition: gig.cpp:4742
Sample * AddSample()
Add a new sample.
Definition: gig.cpp:5268
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:3176
stream_whence_t
File stream position dependent to these relations.
Definition: RIFF.h:159
void LoadScripts()
Definition: gig.cpp:4316
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:3821
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:5210
#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:4286
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:5436
virtual void LoadScriptGroups()
Definition: gig.cpp:5813
Script * GetScript(uint index)
Get instrument script.
Definition: gig.cpp:4267
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:5661
#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:4244
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:4844
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:2744
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:5379
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:2833
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:3091
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:2060
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:4755
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:4716
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:3712
void UpdateScriptFileOffsets()
Definition: gig.cpp:4554
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:3068
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:4599
String libraryVersion()
Returns version of this C++ library.
Definition: gig.cpp:6104
#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:4200
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:4145
InstrumentList::iterator InstrumentsIterator
Definition: DLS.h:527
Instrument(File *pFile, RIFF::List *insList, progress_t *pProgress=NULL)
Definition: gig.cpp:4333
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:2806
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:5621
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:2815
#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:6063
MidiRule * GetMidiRule(int i)
Returns a MIDI rule of the instrument.
Definition: gig.cpp:4707
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:5186
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:4897
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:5319
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:5614
Group * GetGroup(uint index)
Returns the group with the given index.
Definition: gig.cpp:5633
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:5473
std::string String
Definition: gig.h:71
uint ScriptSlotCount() const
Instrument&#39;s amount of script slots.
Definition: gig.cpp:4920
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:3378
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:5558
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:6038
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:2740
#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:4619
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:4080
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:4729
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:6080
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:4879
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:3288
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:3937
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:3986
#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:5386
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:5703
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:5293
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:2909
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:4940
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:4633
#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:4223
ScriptGroup * AddScriptGroup()
Add new instrument script group.
Definition: gig.cpp:5780
#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:5748
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:5591
Sample * GetNextSample()
Returns the next Sample of the Group.
Definition: gig.cpp:5113
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:3502
Sample * GetFirstSample(progress_t *pProgress=NULL)
Returns a pointer to the first Sample object of the file, NULL otherwise.
Definition: gig.cpp:5231
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:5550
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:5060
uint16_t major
Definition: DLS.h:112
RegionList::iterator RegionsIterator
Definition: DLS.h:483
int GetDimensionRegionIndexByValue(const uint DimValues[8])
Definition: gig.cpp:3761
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:6071
void UpdateChunks(uint8_t *pData) const
Definition: gig.cpp:4046
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:3869
#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:4864
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:3688
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:4196
void SetVelocityResponseCurveScaling(uint8_t scaling)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2776
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:5839
#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:4211
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:2824
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:5039
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:5238
unsigned long ulWavePoolOffset
Definition: DLS.h:419
virtual ~Script()
Definition: gig.cpp:4112
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:4470
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:6083
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:5249
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:2764
RIFF::List * pWaveList
Definition: DLS.h:416
Sample * GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t *pProgress=NULL)
Definition: gig.cpp:3845
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:3003
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:5399
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:4183
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:5045
void SetReleaseVelocityResponseDepth(uint8_t depth)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2797
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:5095
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:3681
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:4960
void DeleteGroup(Group *pGroup)
Delete a group and its samples.
Definition: gig.cpp:5679
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:4977
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:6096
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:5714
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:4667
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:4803
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:3084
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:4303
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:2788
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:2736
std::list< RIFF::File * > ExtensionFiles
Definition: DLS.h:523
Sample * GetSample()
Returns pointer address to the Sample referenced with this region.
Definition: gig.cpp:3840
void SetVelocityResponseCurve(curve_type_t curve)
Updates the respective member variable and the lookup table / cache that depends on this value...
Definition: gig.cpp:2752
#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:5799
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:4613
#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