/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Diff of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 929 by schoenebeck, Tue Oct 24 22:24:45 2006 UTC revision 2557 by schoenebeck, Sat May 17 23:31:20 2014 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2006 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2014 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
34  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 254  namespace { Line 256  namespace {
256  }  }
257    
258    
259    
260    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
261    // *
262    
263        static uint32_t* __initCRCTable() {
264            static uint32_t res[256];
265    
266            for (int i = 0 ; i < 256 ; i++) {
267                uint32_t c = i;
268                for (int j = 0 ; j < 8 ; j++) {
269                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
270                }
271                res[i] = c;
272            }
273            return res;
274        }
275    
276        static const uint32_t* __CRCTable = __initCRCTable();
277    
278        /**
279         * Initialize a CRC variable.
280         *
281         * @param crc - variable to be initialized
282         */
283        inline static void __resetCRC(uint32_t& crc) {
284            crc = 0xffffffff;
285        }
286    
287        /**
288         * Used to calculate checksums of the sample data in a gig file. The
289         * checksums are stored in the 3crc chunk of the gig file and
290         * automatically updated when a sample is written with Sample::Write().
291         *
292         * One should call __resetCRC() to initialize the CRC variable to be
293         * used before calling this function the first time.
294         *
295         * After initializing the CRC variable one can call this function
296         * arbitrary times, i.e. to split the overall CRC calculation into
297         * steps.
298         *
299         * Once the whole data was processed by __calculateCRC(), one should
300         * call __encodeCRC() to get the final CRC result.
301         *
302         * @param buf     - pointer to data the CRC shall be calculated of
303         * @param bufSize - size of the data to be processed
304         * @param crc     - variable the CRC sum shall be stored to
305         */
306        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
307            for (int i = 0 ; i < bufSize ; i++) {
308                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
309            }
310        }
311    
312        /**
313         * Returns the final CRC result.
314         *
315         * @param crc - variable previously passed to __calculateCRC()
316         */
317        inline static uint32_t __encodeCRC(const uint32_t& crc) {
318            return crc ^ 0xffffffff;
319        }
320    
321    
322    
323    // *************** Other Internal functions  ***************
324    // *
325    
326        static split_type_t __resolveSplitType(dimension_t dimension) {
327            return (
328                dimension == dimension_layer ||
329                dimension == dimension_samplechannel ||
330                dimension == dimension_releasetrigger ||
331                dimension == dimension_keyboard ||
332                dimension == dimension_roundrobin ||
333                dimension == dimension_random ||
334                dimension == dimension_smartmidi ||
335                dimension == dimension_roundrobinkeyboard
336            ) ? split_type_bit : split_type_normal;
337        }
338    
339        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
340            return (dimension_definition.split_type == split_type_normal)
341            ? int(128.0 / dimension_definition.zones) : 0;
342        }
343    
344    
345    
346  // *************** Sample ***************  // *************** Sample ***************
347  // *  // *
348    
# Line 279  namespace { Line 368  namespace {
368       *                         is located, 0 otherwise       *                         is located, 0 otherwise
369       */       */
370      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
371          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
372                { CHUNK_ID_INAM, 64 },
373                { 0, 0 }
374            };
375            pInfo->SetFixedStringLengths(fixedStringLengths);
376          Instances++;          Instances++;
377          FileNo = fileNo;          FileNo = fileNo;
378    
379            __resetCRC(crc);
380    
381          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
382          if (pCk3gix) {          if (pCk3gix) {
383              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
384              // caution: sample groups in .gig files are indexed (1..n) whereas Groups in libgig (0..n-1)              pGroup = pFile->GetGroup(iSampleGroup);
             pGroup = pFile->GetGroup(iSampleGroup - 1);  
385          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
386              // not assigned to a group by default              // by default assigned to that mandatory "Default Group"
387              pGroup = NULL;              pGroup = pFile->GetGroup(0);
388          }          }
389    
390          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 315  namespace { Line 409  namespace {
409              Manufacturer  = 0;              Manufacturer  = 0;
410              Product       = 0;              Product       = 0;
411              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
412              MIDIUnityNote = 64;              MIDIUnityNote = 60;
413              FineTune      = 0;              FineTune      = 0;
414                SMPTEFormat   = smpte_format_no_offset;
415              SMPTEOffset   = 0;              SMPTEOffset   = 0;
416              Loops         = 0;              Loops         = 0;
417              LoopID        = 0;              LoopID        = 0;
418                LoopType      = loop_type_normal;
419              LoopStart     = 0;              LoopStart     = 0;
420              LoopEnd       = 0;              LoopEnd       = 0;
421              LoopFraction  = 0;              LoopFraction  = 0;
# Line 359  namespace { Line 455  namespace {
455      }      }
456    
457      /**      /**
458         * Make a (semi) deep copy of the Sample object given by @a orig (without
459         * the actual waveform data) and assign it to this object.
460         *
461         * Discussion: copying .gig samples is a bit tricky. It requires three
462         * steps:
463         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
464         *    its new sample waveform data size.
465         * 2. Saving the file (done by File::Save()) so that it gains correct size
466         *    and layout for writing the actual wave form data directly to disc
467         *    in next step.
468         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
469         *
470         * @param orig - original Sample object to be copied from
471         */
472        void Sample::CopyAssignMeta(const Sample* orig) {
473            // handle base classes
474            DLS::Sample::CopyAssignCore(orig);
475            
476            // handle actual own attributes of this class
477            Manufacturer = orig->Manufacturer;
478            Product = orig->Product;
479            SamplePeriod = orig->SamplePeriod;
480            MIDIUnityNote = orig->MIDIUnityNote;
481            FineTune = orig->FineTune;
482            SMPTEFormat = orig->SMPTEFormat;
483            SMPTEOffset = orig->SMPTEOffset;
484            Loops = orig->Loops;
485            LoopID = orig->LoopID;
486            LoopType = orig->LoopType;
487            LoopStart = orig->LoopStart;
488            LoopEnd = orig->LoopEnd;
489            LoopSize = orig->LoopSize;
490            LoopFraction = orig->LoopFraction;
491            LoopPlayCount = orig->LoopPlayCount;
492            
493            // schedule resizing this sample to the given sample's size
494            Resize(orig->GetSize());
495        }
496    
497        /**
498         * Should be called after CopyAssignMeta() and File::Save() sequence.
499         * Read more about it in the discussion of CopyAssignMeta(). This method
500         * copies the actual waveform data by disk streaming.
501         *
502         * @e CAUTION: this method is currently not thread safe! During this
503         * operation the sample must not be used for other purposes by other
504         * threads!
505         *
506         * @param orig - original Sample object to be copied from
507         */
508        void Sample::CopyAssignWave(const Sample* orig) {
509            const int iReadAtOnce = 32*1024;
510            char* buf = new char[iReadAtOnce * orig->FrameSize];
511            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
512            unsigned long restorePos = pOrig->GetPos();
513            pOrig->SetPos(0);
514            SetPos(0);
515            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
516                               n = pOrig->Read(buf, iReadAtOnce))
517            {
518                Write(buf, n);
519            }
520            pOrig->SetPos(restorePos);
521            delete [] buf;
522        }
523    
524        /**
525       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
526       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
527       *       *
528       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
529       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
530       *       *
531       * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
532       *                        was provided yet       *                        was provided yet
533       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
534       */       */
# Line 375  namespace { Line 538  namespace {
538    
539          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
540          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
541          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
542                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
543                memset(pCkSmpl->LoadChunkData(), 0, 60);
544            }
545          // update 'smpl' chunk          // update 'smpl' chunk
546          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
547          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
548          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
549          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
550          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
551          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
552          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
553          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
554          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
555          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
556    
557          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
558    
559          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
560          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
561          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
562          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
563          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
564          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
565    
566          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
567          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
568          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
569          // determine appropriate sample group index (to be stored in chunk)          // determine appropriate sample group index (to be stored in chunk)
570          uint16_t iSampleGroup = 0; // no sample group by default          uint16_t iSampleGroup = 0; // 0 refers to default sample group
571          File* pFile = static_cast<File*>(pParent);          File* pFile = static_cast<File*>(pParent);
572          if (pFile->pGroups) {          if (pFile->pGroups) {
573              std::list<Group*>::iterator iter = pFile->pGroups->begin();              std::list<Group*>::iterator iter = pFile->pGroups->begin();
574              std::list<Group*>::iterator end  = pFile->pGroups->end();              std::list<Group*>::iterator end  = pFile->pGroups->end();
575              // caution: sample groups in .gig files are indexed (1..n) whereas Groups in libgig (0..n-1)              for (int i = 0; iter != end; i++, iter++) {
             for (int i = 1; iter != end; i++, iter++) {  
576                  if (*iter == pGroup) {                  if (*iter == pGroup) {
577                      iSampleGroup = i;                      iSampleGroup = i;
578                      break; // found                      break; // found
# Line 416  namespace { Line 581  namespace {
581          }          }
582          // update '3gix' chunk          // update '3gix' chunk
583          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
584          memcpy(&pData[0], &iSampleGroup, 2);          store16(&pData[0], iSampleGroup);
585    
586            // if the library user toggled the "Compressed" attribute from true to
587            // false, then the EWAV chunk associated with compressed samples needs
588            // to be deleted
589            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
590            if (ewav && !Compressed) {
591                pWaveList->DeleteSubChunk(ewav);
592            }
593      }      }
594    
595      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 580  namespace { Line 753  namespace {
753          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
754          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
755          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
756            SetPos(0); // reset read position to begin of sample
757          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
758          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
759          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 617  namespace { Line 791  namespace {
791          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
792          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
793          RAMCache.Size   = 0;          RAMCache.Size   = 0;
794            RAMCache.NullExtensionSize = 0;
795      }      }
796    
797      /** @brief Resize sample.      /** @brief Resize sample.
# Line 637  namespace { Line 812  namespace {
812       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
813       * current sample's boundary!       * current sample's boundary!
814       *       *
815       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
816       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
817       * other formats will fail!       * other formats will fail!
818       *       *
819       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
820       *                   greater than zero)       *                   greater than zero)
821       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
822       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
823       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
824       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 709  namespace { Line 884  namespace {
884      /**      /**
885       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
886       */       */
887      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
888          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
889          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
890      }      }
# Line 811  namespace { Line 986  namespace {
986                                  }                                  }
987    
988                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
989                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
990                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
991                              }                              }
992                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
993                          break;                          break;
# Line 1101  namespace { Line 1277  namespace {
1277       *       *
1278       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1279       *       *
1280         * For 16 bit samples, the data in the source buffer should be
1281         * int16_t (using native endianness). For 24 bit, the buffer
1282         * should contain three bytes per sample, little-endian.
1283         *
1284       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1285       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1286       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1109  namespace { Line 1289  namespace {
1289       */       */
1290      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1291          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1292          return DLS::Sample::Write(pBuffer, SampleCount);  
1293            // if this is the first write in this sample, reset the
1294            // checksum calculator
1295            if (pCkData->GetPos() == 0) {
1296                __resetCRC(crc);
1297            }
1298            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1299            unsigned long res;
1300            if (BitDepth == 24) {
1301                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1302            } else { // 16 bit
1303                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1304                                    : pCkData->Write(pBuffer, SampleCount, 2);
1305            }
1306            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1307    
1308            // if this is the last write, update the checksum chunk in the
1309            // file
1310            if (pCkData->GetPos() == pCkData->GetSize()) {
1311                File* pFile = static_cast<File*>(GetParent());
1312                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1313            }
1314            return res;
1315      }      }
1316    
1317      /**      /**
# Line 1154  namespace { Line 1356  namespace {
1356          }          }
1357      }      }
1358    
1359        /**
1360         * Returns pointer to the Group this Sample belongs to. In the .gig
1361         * format a sample always belongs to one group. If it wasn't explicitly
1362         * assigned to a certain group, it will be automatically assigned to a
1363         * default group.
1364         *
1365         * @returns Sample's Group (never NULL)
1366         */
1367        Group* Sample::GetGroup() const {
1368            return pGroup;
1369        }
1370    
1371      Sample::~Sample() {      Sample::~Sample() {
1372          Instances--;          Instances--;
1373          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1173  namespace { Line 1387  namespace {
1387      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1388      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1389    
1390      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1391          Instances++;          Instances++;
1392    
1393          pSample = NULL;          pSample = NULL;
1394            pRegion = pParent;
1395    
1396            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1397            else memset(&Crossfade, 0, 4);
1398    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1399          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1400    
1401          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1292  namespace { Line 1509  namespace {
1509                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1510              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1511              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1512                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1513              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1514              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1515              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1328  namespace { Line 1545  namespace {
1545                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1546                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1547              }              }
1548                if (_3ewa->RemainingBytes() >= 8) {
1549                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1550                } else {
1551                    memset(DimensionUpperLimits, 0, 8);
1552                }
1553          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1554              // use default values              // use default values
1555              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1337  namespace { Line 1559  namespace {
1559              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1560              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1561              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1562              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1563              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1564              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1565              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1566              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1567              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1354  namespace { Line 1576  namespace {
1576              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1577              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1578              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1579              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1580              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1581              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1582              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1583              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1584              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1585              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1586              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1587              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1588              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1589              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1590              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1591              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1592              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1593              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1408  namespace { Line 1630  namespace {
1630              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1631              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1632              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1633                memset(DimensionUpperLimits, 127, 8);
1634          }          }
1635    
1636          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1637                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1638                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1639    
1640          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1641          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1642                                        ReleaseVelocityResponseDepth
1643                                    );
1644    
1645            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1646                                                          VCFVelocityDynamicRange,
1647                                                          VCFVelocityScale,
1648                                                          VCFCutoffController);
1649    
1650          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1651          // velocity response curves for release time are not used even          VelocityTable = 0;
1652          // if specified, instead another curve is chosen.      }
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_nonlinear;  
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1653    
1654          curveType = VCFVelocityCurve;      /*
1655          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1656         * another DimensionRegion
1657         */
1658        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1659            Instances++;
1660            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1661            *this = src; // default memberwise shallow copy of all parameters
1662            pParentList = _3ewl; // restore the chunk pointer
1663    
1664            // deep copy of owned structures
1665            if (src.VelocityTable) {
1666                VelocityTable = new uint8_t[128];
1667                for (int k = 0 ; k < 128 ; k++)
1668                    VelocityTable[k] = src.VelocityTable[k];
1669            }
1670            if (src.pSampleLoops) {
1671                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1672                for (int k = 0 ; k < src.SampleLoops ; k++)
1673                    pSampleLoops[k] = src.pSampleLoops[k];
1674            }
1675        }
1676        
1677        /**
1678         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1679         * and assign it to this object.
1680         *
1681         * Note that all sample pointers referenced by @a orig are simply copied as
1682         * memory address. Thus the respective samples are shared, not duplicated!
1683         *
1684         * @param orig - original DimensionRegion object to be copied from
1685         */
1686        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1687            CopyAssign(orig, NULL);
1688        }
1689    
1690          // even stranger GSt: two of the velocity response curves for      /**
1691          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1692          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1693          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1694              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1695              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1696              depth = 5;       *                   this file's samples
1697         */
1698        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1699            // delete all allocated data first
1700            if (VelocityTable) delete [] VelocityTable;
1701            if (pSampleLoops) delete [] pSampleLoops;
1702            
1703            // backup parent list pointer
1704            RIFF::List* p = pParentList;
1705            
1706            gig::Sample* pOriginalSample = pSample;
1707            gig::Region* pOriginalRegion = pRegion;
1708            
1709            //NOTE: copy code copied from assignment constructor above, see comment there as well
1710            
1711            *this = *orig; // default memberwise shallow copy of all parameters
1712            
1713            // restore members that shall not be altered
1714            pParentList = p; // restore the chunk pointer
1715            pRegion = pOriginalRegion;
1716            
1717            // only take the raw sample reference reference if the
1718            // two DimensionRegion objects are part of the same file
1719            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1720                pSample = pOriginalSample;
1721            }
1722            
1723            if (mSamples && mSamples->count(orig->pSample)) {
1724                pSample = mSamples->find(orig->pSample)->second;
1725            }
1726    
1727            // deep copy of owned structures
1728            if (orig->VelocityTable) {
1729                VelocityTable = new uint8_t[128];
1730                for (int k = 0 ; k < 128 ; k++)
1731                    VelocityTable[k] = orig->VelocityTable[k];
1732            }
1733            if (orig->pSampleLoops) {
1734                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1735                for (int k = 0 ; k < orig->SampleLoops ; k++)
1736                    pSampleLoops[k] = orig->pSampleLoops[k];
1737          }          }
1738          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1739    
1740        /**
1741         * Updates the respective member variable and updates @c SampleAttenuation
1742         * which depends on this value.
1743         */
1744        void DimensionRegion::SetGain(int32_t gain) {
1745            DLS::Sampler::SetGain(gain);
1746          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1747      }      }
1748    
1749      /**      /**
# Line 1456  namespace { Line 1757  namespace {
1757          // first update base class's chunk          // first update base class's chunk
1758          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1759    
1760            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1761            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1762            pData[12] = Crossfade.in_start;
1763            pData[13] = Crossfade.in_end;
1764            pData[14] = Crossfade.out_start;
1765            pData[15] = Crossfade.out_end;
1766    
1767          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1768          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1769          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1770          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1771                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1772                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1773            }
1774            pData = (uint8_t*) _3ewa->LoadChunkData();
1775    
1776          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1777    
1778          const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ?          const uint32_t chunksize = _3ewa->GetNewSize();
1779          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1780    
1781          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1782          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1783    
1784          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1785          memcpy(&pData[8], &eg3attack, 4);          store32(&pData[8], eg3attack);
1786    
1787          // next 2 bytes unknown          // next 2 bytes unknown
1788    
1789          memcpy(&pData[14], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1790    
1791          // next 2 bytes unknown          // next 2 bytes unknown
1792    
1793          memcpy(&pData[18], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1794    
1795          // next 2 bytes unknown          // next 2 bytes unknown
1796    
1797          memcpy(&pData[22], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1798    
1799          // next 2 bytes unknown          // next 2 bytes unknown
1800    
1801          memcpy(&pData[26], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1802    
1803          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1804          memcpy(&pData[28], &eg1attack, 4);          store32(&pData[28], eg1attack);
1805    
1806          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1807          memcpy(&pData[32], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1808    
1809          // next 2 bytes unknown          // next 2 bytes unknown
1810    
1811          memcpy(&pData[38], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1812    
1813          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1814          memcpy(&pData[40], &eg1release, 4);          store32(&pData[40], eg1release);
1815    
1816          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1817          memcpy(&pData[44], &eg1ctl, 1);          pData[44] = eg1ctl;
1818    
1819          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1820              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1821              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1822              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1823              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1824          memcpy(&pData[45], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1825    
1826          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1827          memcpy(&pData[46], &eg2ctl, 1);          pData[46] = eg2ctl;
1828    
1829          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1830              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1831              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1832              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1833              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1834          memcpy(&pData[47], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1835    
1836          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1837          memcpy(&pData[48], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1838    
1839          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1840          memcpy(&pData[52], &eg2attack, 4);          store32(&pData[52], eg2attack);
1841    
1842          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1843          memcpy(&pData[56], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1844    
1845          // next 2 bytes unknown          // next 2 bytes unknown
1846    
1847          memcpy(&pData[62], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1848    
1849          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1850          memcpy(&pData[64], &eg2release, 4);          store32(&pData[64], eg2release);
1851    
1852          // next 2 bytes unknown          // next 2 bytes unknown
1853    
1854          memcpy(&pData[70], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1855    
1856          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1857          memcpy(&pData[72], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1858    
1859          // next 2 bytes unknown          // next 2 bytes unknown
1860    
1861          memcpy(&pData[78], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1862    
1863          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1864          memcpy(&pData[80], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1865    
1866          // next 2 bytes unknown          // next 2 bytes unknown
1867    
1868          memcpy(&pData[86], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1869    
1870          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1871          memcpy(&pData[88], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1872    
1873          // next 2 bytes unknown          // next 2 bytes unknown
1874    
1875          memcpy(&pData[94], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1876    
1877          {          {
1878              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1578  namespace { Line 1890  namespace {
1890                  default:                  default:
1891                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1892              }              }
1893              memcpy(&pData[96], &velocityresponse, 1);              pData[96] = velocityresponse;
1894          }          }
1895    
1896          {          {
# Line 1597  namespace { Line 1909  namespace {
1909                  default:                  default:
1910                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1911              }              }
1912              memcpy(&pData[97], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1913          }          }
1914    
1915          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1916    
1917          memcpy(&pData[99], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1918    
1919          // next 4 bytes unknown          // next 4 bytes unknown
1920    
1921          memcpy(&pData[104], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1922    
1923          // next 2 bytes unknown          // next 2 bytes unknown
1924    
# Line 1625  namespace { Line 1937  namespace {
1937                  default:                  default:
1938                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1939              }              }
1940              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1941          }          }
1942    
1943          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1944          memcpy(&pData[109], &pan, 1);          pData[109] = pan;
1945    
1946          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1947          memcpy(&pData[110], &selfmask, 1);          pData[110] = selfmask;
1948    
1949          // next byte unknown          // next byte unknown
1950    
# Line 1641  namespace { Line 1953  namespace {
1953              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1954              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1955              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1956              memcpy(&pData[112], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1957          }          }
1958    
1959          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1960          memcpy(&pData[113], &attenctl, 1);          pData[113] = attenctl;
1961    
1962          {          {
1963              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1964              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1965              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1966              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1967              memcpy(&pData[114], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1968          }          }
1969    
1970          {          {
# Line 1661  namespace { Line 1973  namespace {
1973              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1974              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1975                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1976              memcpy(&pData[115], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1977          }          }
1978    
1979          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1980                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1981          memcpy(&pData[116], &eg3depth, 1);          store16(&pData[116], eg3depth);
1982    
1983          // next 2 bytes unknown          // next 2 bytes unknown
1984    
1985          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1986          memcpy(&pData[120], &channeloffset, 1);          pData[120] = channeloffset;
1987    
1988          {          {
1989              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1990              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1991              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1992              memcpy(&pData[121], &regoptions, 1);              pData[121] = regoptions;
1993          }          }
1994    
1995          // next 2 bytes unknown          // next 2 bytes unknown
1996    
1997          memcpy(&pData[124], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1998    
1999          // next 3 bytes unknown          // next 3 bytes unknown
2000    
2001          memcpy(&pData[128], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
2002    
2003          // next 2 bytes unknown          // next 2 bytes unknown
2004    
2005          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2006          memcpy(&pData[131], &eg1hold, 1);          pData[131] = eg1hold;
2007    
2008          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2009                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2010          memcpy(&pData[132], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2011    
2012          memcpy(&pData[133], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2013    
2014          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2015                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2016          memcpy(&pData[134], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2017    
2018          // next byte unknown          // next byte unknown
2019    
2020          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2021                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2022          memcpy(&pData[136], &vcfresonance, 1);          pData[136] = vcfresonance;
2023    
2024          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2025                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2026          memcpy(&pData[137], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2027    
2028          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2029                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2030          memcpy(&pData[138], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2031    
2032          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2033          memcpy(&pData[139], &vcftype, 1);          pData[139] = vcftype;
2034    
2035            if (chunksize >= 148) {
2036                memcpy(&pData[140], DimensionUpperLimits, 8);
2037            }
2038        }
2039    
2040        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2041            curve_type_t curveType = releaseVelocityResponseCurve;
2042            uint8_t depth = releaseVelocityResponseDepth;
2043            // this models a strange behaviour or bug in GSt: two of the
2044            // velocity response curves for release time are not used even
2045            // if specified, instead another curve is chosen.
2046            if ((curveType == curve_type_nonlinear && depth == 0) ||
2047                (curveType == curve_type_special   && depth == 4)) {
2048                curveType = curve_type_nonlinear;
2049                depth = 3;
2050            }
2051            return GetVelocityTable(curveType, depth, 0);
2052        }
2053    
2054        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2055                                                        uint8_t vcfVelocityDynamicRange,
2056                                                        uint8_t vcfVelocityScale,
2057                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2058        {
2059            curve_type_t curveType = vcfVelocityCurve;
2060            uint8_t depth = vcfVelocityDynamicRange;
2061            // even stranger GSt: two of the velocity response curves for
2062            // filter cutoff are not used, instead another special curve
2063            // is chosen. This curve is not used anywhere else.
2064            if ((curveType == curve_type_nonlinear && depth == 0) ||
2065                (curveType == curve_type_special   && depth == 4)) {
2066                curveType = curve_type_special;
2067                depth = 5;
2068            }
2069            return GetVelocityTable(curveType, depth,
2070                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2071                                        ? vcfVelocityScale : 0);
2072      }      }
2073    
2074      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
# Line 1736  namespace { Line 2086  namespace {
2086          return table;          return table;
2087      }      }
2088    
2089        Region* DimensionRegion::GetParent() const {
2090            return pRegion;
2091        }
2092    
2093    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2094    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2095    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2096    //#pragma GCC diagnostic push
2097    //#pragma GCC diagnostic error "-Wswitch"
2098    
2099      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2100          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2101          switch (EncodedController) {          switch (EncodedController) {
# Line 1847  namespace { Line 2207  namespace {
2207                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2208                  break;                  break;
2209    
2210                // format extension (these controllers are so far only supported by
2211                // LinuxSampler & gigedit) they will *NOT* work with
2212                // Gigasampler/GigaStudio !
2213                case _lev_ctrl_CC3_EXT:
2214                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2215                    decodedcontroller.controller_number = 3;
2216                    break;
2217                case _lev_ctrl_CC6_EXT:
2218                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2219                    decodedcontroller.controller_number = 6;
2220                    break;
2221                case _lev_ctrl_CC7_EXT:
2222                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2223                    decodedcontroller.controller_number = 7;
2224                    break;
2225                case _lev_ctrl_CC8_EXT:
2226                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2227                    decodedcontroller.controller_number = 8;
2228                    break;
2229                case _lev_ctrl_CC9_EXT:
2230                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2231                    decodedcontroller.controller_number = 9;
2232                    break;
2233                case _lev_ctrl_CC10_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 10;
2236                    break;
2237                case _lev_ctrl_CC11_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 11;
2240                    break;
2241                case _lev_ctrl_CC14_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 14;
2244                    break;
2245                case _lev_ctrl_CC15_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 15;
2248                    break;
2249                case _lev_ctrl_CC20_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 20;
2252                    break;
2253                case _lev_ctrl_CC21_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 21;
2256                    break;
2257                case _lev_ctrl_CC22_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 22;
2260                    break;
2261                case _lev_ctrl_CC23_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 23;
2264                    break;
2265                case _lev_ctrl_CC24_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 24;
2268                    break;
2269                case _lev_ctrl_CC25_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 25;
2272                    break;
2273                case _lev_ctrl_CC26_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 26;
2276                    break;
2277                case _lev_ctrl_CC27_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 27;
2280                    break;
2281                case _lev_ctrl_CC28_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 28;
2284                    break;
2285                case _lev_ctrl_CC29_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 29;
2288                    break;
2289                case _lev_ctrl_CC30_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 30;
2292                    break;
2293                case _lev_ctrl_CC31_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 31;
2296                    break;
2297                case _lev_ctrl_CC68_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 68;
2300                    break;
2301                case _lev_ctrl_CC69_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 69;
2304                    break;
2305                case _lev_ctrl_CC70_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 70;
2308                    break;
2309                case _lev_ctrl_CC71_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 71;
2312                    break;
2313                case _lev_ctrl_CC72_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 72;
2316                    break;
2317                case _lev_ctrl_CC73_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 73;
2320                    break;
2321                case _lev_ctrl_CC74_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 74;
2324                    break;
2325                case _lev_ctrl_CC75_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 75;
2328                    break;
2329                case _lev_ctrl_CC76_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 76;
2332                    break;
2333                case _lev_ctrl_CC77_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 77;
2336                    break;
2337                case _lev_ctrl_CC78_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 78;
2340                    break;
2341                case _lev_ctrl_CC79_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 79;
2344                    break;
2345                case _lev_ctrl_CC84_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 84;
2348                    break;
2349                case _lev_ctrl_CC85_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 85;
2352                    break;
2353                case _lev_ctrl_CC86_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 86;
2356                    break;
2357                case _lev_ctrl_CC87_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 87;
2360                    break;
2361                case _lev_ctrl_CC89_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 89;
2364                    break;
2365                case _lev_ctrl_CC90_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 90;
2368                    break;
2369                case _lev_ctrl_CC96_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 96;
2372                    break;
2373                case _lev_ctrl_CC97_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 97;
2376                    break;
2377                case _lev_ctrl_CC102_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 102;
2380                    break;
2381                case _lev_ctrl_CC103_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 103;
2384                    break;
2385                case _lev_ctrl_CC104_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 104;
2388                    break;
2389                case _lev_ctrl_CC105_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 105;
2392                    break;
2393                case _lev_ctrl_CC106_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 106;
2396                    break;
2397                case _lev_ctrl_CC107_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 107;
2400                    break;
2401                case _lev_ctrl_CC108_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 108;
2404                    break;
2405                case _lev_ctrl_CC109_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 109;
2408                    break;
2409                case _lev_ctrl_CC110_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 110;
2412                    break;
2413                case _lev_ctrl_CC111_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 111;
2416                    break;
2417                case _lev_ctrl_CC112_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 112;
2420                    break;
2421                case _lev_ctrl_CC113_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 113;
2424                    break;
2425                case _lev_ctrl_CC114_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 114;
2428                    break;
2429                case _lev_ctrl_CC115_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 115;
2432                    break;
2433                case _lev_ctrl_CC116_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 116;
2436                    break;
2437                case _lev_ctrl_CC117_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 117;
2440                    break;
2441                case _lev_ctrl_CC118_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 118;
2444                    break;
2445                case _lev_ctrl_CC119_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 119;
2448                    break;
2449    
2450              // unknown controller type              // unknown controller type
2451              default:              default:
2452                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2453          }          }
2454          return decodedcontroller;          return decodedcontroller;
2455      }      }
2456        
2457    // see above (diagnostic push not supported prior GCC 4.6)
2458    //#pragma GCC diagnostic pop
2459    
2460      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2461          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1940  namespace { Line 2543  namespace {
2543                      case 95:                      case 95:
2544                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2545                          break;                          break;
2546    
2547                        // format extension (these controllers are so far only
2548                        // supported by LinuxSampler & gigedit) they will *NOT*
2549                        // work with Gigasampler/GigaStudio !
2550                        case 3:
2551                            encodedcontroller = _lev_ctrl_CC3_EXT;
2552                            break;
2553                        case 6:
2554                            encodedcontroller = _lev_ctrl_CC6_EXT;
2555                            break;
2556                        case 7:
2557                            encodedcontroller = _lev_ctrl_CC7_EXT;
2558                            break;
2559                        case 8:
2560                            encodedcontroller = _lev_ctrl_CC8_EXT;
2561                            break;
2562                        case 9:
2563                            encodedcontroller = _lev_ctrl_CC9_EXT;
2564                            break;
2565                        case 10:
2566                            encodedcontroller = _lev_ctrl_CC10_EXT;
2567                            break;
2568                        case 11:
2569                            encodedcontroller = _lev_ctrl_CC11_EXT;
2570                            break;
2571                        case 14:
2572                            encodedcontroller = _lev_ctrl_CC14_EXT;
2573                            break;
2574                        case 15:
2575                            encodedcontroller = _lev_ctrl_CC15_EXT;
2576                            break;
2577                        case 20:
2578                            encodedcontroller = _lev_ctrl_CC20_EXT;
2579                            break;
2580                        case 21:
2581                            encodedcontroller = _lev_ctrl_CC21_EXT;
2582                            break;
2583                        case 22:
2584                            encodedcontroller = _lev_ctrl_CC22_EXT;
2585                            break;
2586                        case 23:
2587                            encodedcontroller = _lev_ctrl_CC23_EXT;
2588                            break;
2589                        case 24:
2590                            encodedcontroller = _lev_ctrl_CC24_EXT;
2591                            break;
2592                        case 25:
2593                            encodedcontroller = _lev_ctrl_CC25_EXT;
2594                            break;
2595                        case 26:
2596                            encodedcontroller = _lev_ctrl_CC26_EXT;
2597                            break;
2598                        case 27:
2599                            encodedcontroller = _lev_ctrl_CC27_EXT;
2600                            break;
2601                        case 28:
2602                            encodedcontroller = _lev_ctrl_CC28_EXT;
2603                            break;
2604                        case 29:
2605                            encodedcontroller = _lev_ctrl_CC29_EXT;
2606                            break;
2607                        case 30:
2608                            encodedcontroller = _lev_ctrl_CC30_EXT;
2609                            break;
2610                        case 31:
2611                            encodedcontroller = _lev_ctrl_CC31_EXT;
2612                            break;
2613                        case 68:
2614                            encodedcontroller = _lev_ctrl_CC68_EXT;
2615                            break;
2616                        case 69:
2617                            encodedcontroller = _lev_ctrl_CC69_EXT;
2618                            break;
2619                        case 70:
2620                            encodedcontroller = _lev_ctrl_CC70_EXT;
2621                            break;
2622                        case 71:
2623                            encodedcontroller = _lev_ctrl_CC71_EXT;
2624                            break;
2625                        case 72:
2626                            encodedcontroller = _lev_ctrl_CC72_EXT;
2627                            break;
2628                        case 73:
2629                            encodedcontroller = _lev_ctrl_CC73_EXT;
2630                            break;
2631                        case 74:
2632                            encodedcontroller = _lev_ctrl_CC74_EXT;
2633                            break;
2634                        case 75:
2635                            encodedcontroller = _lev_ctrl_CC75_EXT;
2636                            break;
2637                        case 76:
2638                            encodedcontroller = _lev_ctrl_CC76_EXT;
2639                            break;
2640                        case 77:
2641                            encodedcontroller = _lev_ctrl_CC77_EXT;
2642                            break;
2643                        case 78:
2644                            encodedcontroller = _lev_ctrl_CC78_EXT;
2645                            break;
2646                        case 79:
2647                            encodedcontroller = _lev_ctrl_CC79_EXT;
2648                            break;
2649                        case 84:
2650                            encodedcontroller = _lev_ctrl_CC84_EXT;
2651                            break;
2652                        case 85:
2653                            encodedcontroller = _lev_ctrl_CC85_EXT;
2654                            break;
2655                        case 86:
2656                            encodedcontroller = _lev_ctrl_CC86_EXT;
2657                            break;
2658                        case 87:
2659                            encodedcontroller = _lev_ctrl_CC87_EXT;
2660                            break;
2661                        case 89:
2662                            encodedcontroller = _lev_ctrl_CC89_EXT;
2663                            break;
2664                        case 90:
2665                            encodedcontroller = _lev_ctrl_CC90_EXT;
2666                            break;
2667                        case 96:
2668                            encodedcontroller = _lev_ctrl_CC96_EXT;
2669                            break;
2670                        case 97:
2671                            encodedcontroller = _lev_ctrl_CC97_EXT;
2672                            break;
2673                        case 102:
2674                            encodedcontroller = _lev_ctrl_CC102_EXT;
2675                            break;
2676                        case 103:
2677                            encodedcontroller = _lev_ctrl_CC103_EXT;
2678                            break;
2679                        case 104:
2680                            encodedcontroller = _lev_ctrl_CC104_EXT;
2681                            break;
2682                        case 105:
2683                            encodedcontroller = _lev_ctrl_CC105_EXT;
2684                            break;
2685                        case 106:
2686                            encodedcontroller = _lev_ctrl_CC106_EXT;
2687                            break;
2688                        case 107:
2689                            encodedcontroller = _lev_ctrl_CC107_EXT;
2690                            break;
2691                        case 108:
2692                            encodedcontroller = _lev_ctrl_CC108_EXT;
2693                            break;
2694                        case 109:
2695                            encodedcontroller = _lev_ctrl_CC109_EXT;
2696                            break;
2697                        case 110:
2698                            encodedcontroller = _lev_ctrl_CC110_EXT;
2699                            break;
2700                        case 111:
2701                            encodedcontroller = _lev_ctrl_CC111_EXT;
2702                            break;
2703                        case 112:
2704                            encodedcontroller = _lev_ctrl_CC112_EXT;
2705                            break;
2706                        case 113:
2707                            encodedcontroller = _lev_ctrl_CC113_EXT;
2708                            break;
2709                        case 114:
2710                            encodedcontroller = _lev_ctrl_CC114_EXT;
2711                            break;
2712                        case 115:
2713                            encodedcontroller = _lev_ctrl_CC115_EXT;
2714                            break;
2715                        case 116:
2716                            encodedcontroller = _lev_ctrl_CC116_EXT;
2717                            break;
2718                        case 117:
2719                            encodedcontroller = _lev_ctrl_CC117_EXT;
2720                            break;
2721                        case 118:
2722                            encodedcontroller = _lev_ctrl_CC118_EXT;
2723                            break;
2724                        case 119:
2725                            encodedcontroller = _lev_ctrl_CC119_EXT;
2726                            break;
2727    
2728                      default:                      default:
2729                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2730                  }                  }
2731                    break;
2732              default:              default:
2733                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2734          }          }
# Line 1988  namespace { Line 2774  namespace {
2774          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2775      }      }
2776    
2777        /**
2778         * Updates the respective member variable and the lookup table / cache
2779         * that depends on this value.
2780         */
2781        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2782            pVelocityAttenuationTable =
2783                GetVelocityTable(
2784                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2785                );
2786            VelocityResponseCurve = curve;
2787        }
2788    
2789        /**
2790         * Updates the respective member variable and the lookup table / cache
2791         * that depends on this value.
2792         */
2793        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2794            pVelocityAttenuationTable =
2795                GetVelocityTable(
2796                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2797                );
2798            VelocityResponseDepth = depth;
2799        }
2800    
2801        /**
2802         * Updates the respective member variable and the lookup table / cache
2803         * that depends on this value.
2804         */
2805        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2806            pVelocityAttenuationTable =
2807                GetVelocityTable(
2808                    VelocityResponseCurve, VelocityResponseDepth, scaling
2809                );
2810            VelocityResponseCurveScaling = scaling;
2811        }
2812    
2813        /**
2814         * Updates the respective member variable and the lookup table / cache
2815         * that depends on this value.
2816         */
2817        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2818            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2819            ReleaseVelocityResponseCurve = curve;
2820        }
2821    
2822        /**
2823         * Updates the respective member variable and the lookup table / cache
2824         * that depends on this value.
2825         */
2826        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2827            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2828            ReleaseVelocityResponseDepth = depth;
2829        }
2830    
2831        /**
2832         * Updates the respective member variable and the lookup table / cache
2833         * that depends on this value.
2834         */
2835        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2836            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2837            VCFCutoffController = controller;
2838        }
2839    
2840        /**
2841         * Updates the respective member variable and the lookup table / cache
2842         * that depends on this value.
2843         */
2844        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2845            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2846            VCFVelocityCurve = curve;
2847        }
2848    
2849        /**
2850         * Updates the respective member variable and the lookup table / cache
2851         * that depends on this value.
2852         */
2853        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2854            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2855            VCFVelocityDynamicRange = range;
2856        }
2857    
2858        /**
2859         * Updates the respective member variable and the lookup table / cache
2860         * that depends on this value.
2861         */
2862        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2863            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2864            VCFVelocityScale = scaling;
2865        }
2866    
2867      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2868    
2869          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2060  namespace { Line 2936  namespace {
2936  // *  // *
2937    
2938      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
         pInfo->UseFixedLengthStrings = true;  
   
2939          // Initialization          // Initialization
2940          Dimensions = 0;          Dimensions = 0;
2941          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2073  namespace { Line 2947  namespace {
2947    
2948          // Actual Loading          // Actual Loading
2949    
2950            if (!file->GetAutoLoad()) return;
2951    
2952          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2953    
2954          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2081  namespace { Line 2957  namespace {
2957              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2958                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2959                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2960                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2961                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2962                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2963                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2964                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2095  namespace { Line 2971  namespace {
2971                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2972                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2973                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2974                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2975                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_keyboard ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2976                      Dimensions++;                      Dimensions++;
2977    
2978                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2124  namespace { Line 2992  namespace {
2992              else              else
2993                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2994    
2995              // load sample references              // load sample references (if auto loading is enabled)
2996              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2997                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2998                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2999                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3000                    }
3001                    GetSample(); // load global region sample reference
3002                }
3003            } else {
3004                DimensionRegions = 0;
3005                for (int i = 0 ; i < 8 ; i++) {
3006                    pDimensionDefinitions[i].dimension  = dimension_none;
3007                    pDimensionDefinitions[i].bits       = 0;
3008                    pDimensionDefinitions[i].zones      = 0;
3009              }              }
             GetSample(); // load global region sample reference  
3010          }          }
3011    
3012          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2137  namespace { Line 3014  namespace {
3014              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3015              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3016              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3017              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3018              DimensionRegions = 1;              DimensionRegions = 1;
3019          }          }
3020      }      }
# Line 2152  namespace { Line 3029  namespace {
3029       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3030       */       */
3031      void Region::UpdateChunks() {      void Region::UpdateChunks() {
3032            // in the gig format we don't care about the Region's sample reference
3033            // but we still have to provide some existing one to not corrupt the
3034            // file, so to avoid the latter we simply always assign the sample of
3035            // the first dimension region of this region
3036            pSample = pDimensionRegions[0]->pSample;
3037    
3038          // first update base class's chunks          // first update base class's chunks
3039          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
3040    
# Line 2161  namespace { Line 3044  namespace {
3044          }          }
3045    
3046          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3047          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3048          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3049            const int iMaxDimensionRegions = version3 ? 256 : 32;
3050    
3051          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3052          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3053          if (!_3lnk) {          if (!_3lnk) {
3054              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3055              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3056                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3057    
3058                // move 3prg to last position
3059                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
3060          }          }
3061    
3062          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3063          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3064          memcpy(&pData[0], &DimensionRegions, 4);          store32(&pData[0], DimensionRegions);
3065            int shift = 0;
3066          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3067              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3068              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3069              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3070                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3071              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3072              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
3073    
3074                shift += pDimensionDefinitions[i].bits;
3075          }          }
3076    
3077          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3078          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3079          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3080              int iWaveIndex = -1;              int iWaveIndex = -1;
3081              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2196  namespace { Line 3088  namespace {
3088                          break;                          break;
3089                      }                      }
3090                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3091              }              }
3092              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3093          }          }
3094      }      }
3095    
# Line 2209  namespace { Line 3100  namespace {
3100              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3101              while (_3ewl) {              while (_3ewl) {
3102                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3103                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3104                      dimensionRegionNr++;                      dimensionRegionNr++;
3105                  }                  }
3106                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2218  namespace { Line 3109  namespace {
3109          }          }
3110      }      }
3111    
3112        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3113            // update KeyRange struct and make sure regions are in correct order
3114            DLS::Region::SetKeyRange(Low, High);
3115            // update Region key table for fast lookup
3116            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3117        }
3118    
3119      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3120          // get velocity dimension's index          // get velocity dimension's index
3121          int veldim = -1;          int veldim = -1;
# Line 2238  namespace { Line 3136  namespace {
3136          int dim[8] = { 0 };          int dim[8] = { 0 };
3137          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3138    
3139              if (pDimensionRegions[i]->VelocityUpperLimit) {              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3140                    pDimensionRegions[i]->VelocityUpperLimit) {
3141                  // create the velocity table                  // create the velocity table
3142                  uint8_t* table = pDimensionRegions[i]->VelocityTable;                  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3143                  if (!table) {                  if (!table) {
# Line 2247  namespace { Line 3146  namespace {
3146                  }                  }
3147                  int tableidx = 0;                  int tableidx = 0;
3148                  int velocityZone = 0;                  int velocityZone = 0;
3149                  for (int k = i ; k < end ; k += step) {                  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3150                      DimensionRegion *d = pDimensionRegions[k];                      for (int k = i ; k < end ; k += step) {
3151                      for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;                          DimensionRegion *d = pDimensionRegions[k];
3152                      velocityZone++;                          for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3153                            velocityZone++;
3154                        }
3155                    } else { // gig2
3156                        for (int k = i ; k < end ; k += step) {
3157                            DimensionRegion *d = pDimensionRegions[k];
3158                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3159                            velocityZone++;
3160                        }
3161                  }                  }
3162              } else {              } else {
3163                  if (pDimensionRegions[i]->VelocityTable) {                  if (pDimensionRegions[i]->VelocityTable) {
# Line 2295  namespace { Line 3202  namespace {
3202       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3203       */       */
3204      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3205            // some initial sanity checks of the given dimension definition
3206            if (pDimDef->zones < 2)
3207                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3208            if (pDimDef->bits < 1)
3209                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3210            if (pDimDef->dimension == dimension_samplechannel) {
3211                if (pDimDef->zones != 2)
3212                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3213                if (pDimDef->bits != 1)
3214                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3215            }
3216    
3217          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3218          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3219          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2314  namespace { Line 3233  namespace {
3233              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3234                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3235    
3236            // pos is where the new dimension should be placed, normally
3237            // last in list, except for the samplechannel dimension which
3238            // has to be first in list
3239            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3240            int bitpos = 0;
3241            for (int i = 0 ; i < pos ; i++)
3242                bitpos += pDimensionDefinitions[i].bits;
3243    
3244            // make room for the new dimension
3245            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3246            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3247                for (int j = Dimensions ; j > pos ; j--) {
3248                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3249                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3250                }
3251            }
3252    
3253          // assign definition of new dimension          // assign definition of new dimension
3254          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3255    
3256          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
3257          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
3258              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
3259              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
3260              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
3261              DimensionRegions++;  
3262            // create new dimension region(s) for this new dimension, and make
3263            // sure that the dimension regions are placed correctly in both the
3264            // RIFF list and the pDimensionRegions array
3265            RIFF::Chunk* moveTo = NULL;
3266            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3267            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3268                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3269                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3270                }
3271                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3272                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3273                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3274                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3275                        // create a new dimension region and copy all parameter values from
3276                        // an existing dimension region
3277                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3278                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3279    
3280                        DimensionRegions++;
3281                    }
3282                }
3283                moveTo = pDimensionRegions[i]->pParentList;
3284            }
3285    
3286            // initialize the upper limits for this dimension
3287            int mask = (1 << bitpos) - 1;
3288            for (int z = 0 ; z < pDimDef->zones ; z++) {
3289                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3290                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3291                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3292                                      (z << bitpos) |
3293                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3294                }
3295          }          }
3296    
3297          Dimensions++;          Dimensions++;
# Line 2365  namespace { Line 3334  namespace {
3334          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3335              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3336    
3337            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3338    
3339          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3340          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3341          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2373  namespace { Line 3344  namespace {
3344                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3345                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3346                                      iLowerBit;                                      iLowerBit;
3347    
3348                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3349                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3350                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3351                      DimensionRegions--;                      DimensionRegions--;
# Line 2393  namespace { Line 3366  namespace {
3366              }              }
3367          }          }
3368    
3369            // remove the this dimension from the upper limits arrays
3370            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3371                DimensionRegion* d = pDimensionRegions[j];
3372                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3373                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3374                }
3375                d->DimensionUpperLimits[Dimensions - 1] = 127;
3376            }
3377    
3378          // 'remove' dimension definition          // 'remove' dimension definition
3379          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3380              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2407  namespace { Line 3389  namespace {
3389          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3390      }      }
3391    
3392        /** @brief Delete one split zone of a dimension (decrement zone amount).
3393         *
3394         * Instead of deleting an entire dimensions, this method will only delete
3395         * one particular split zone given by @a zone of the Region's dimension
3396         * given by @a type. So this method will simply decrement the amount of
3397         * zones by one of the dimension in question. To be able to do that, the
3398         * respective dimension must exist on this Region and it must have at least
3399         * 3 zones. All DimensionRegion objects associated with the zone will be
3400         * deleted.
3401         *
3402         * @param type - identifies the dimension where a zone shall be deleted
3403         * @param zone - index of the dimension split zone that shall be deleted
3404         * @throws gig::Exception if requested zone could not be deleted
3405         */
3406        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3407            dimension_def_t* oldDef = GetDimensionDefinition(type);
3408            if (!oldDef)
3409                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3410            if (oldDef->zones <= 2)
3411                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3412            if (zone < 0 || zone >= oldDef->zones)
3413                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3414    
3415            const int newZoneSize = oldDef->zones - 1;
3416    
3417            // create a temporary Region which just acts as a temporary copy
3418            // container and will be deleted at the end of this function and will
3419            // also not be visible through the API during this process
3420            gig::Region* tempRgn = NULL;
3421            {
3422                // adding these temporary chunks is probably not even necessary
3423                Instrument* instr = static_cast<Instrument*>(GetParent());
3424                RIFF::List* pCkInstrument = instr->pCkInstrument;
3425                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3426                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3427                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3428                tempRgn = new Region(instr, rgn);
3429            }
3430    
3431            // copy this region's dimensions (with already the dimension split size
3432            // requested by the arguments of this method call) to the temporary
3433            // region, and don't use Region::CopyAssign() here for this task, since
3434            // it would also alter fast lookup helper variables here and there
3435            dimension_def_t newDef;
3436            for (int i = 0; i < Dimensions; ++i) {
3437                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3438                // is this the dimension requested by the method arguments? ...
3439                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3440                    def.zones = newZoneSize;
3441                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3442                    newDef = def;
3443                }
3444                tempRgn->AddDimension(&def);
3445            }
3446    
3447            // find the dimension index in the tempRegion which is the dimension
3448            // type passed to this method (paranoidly expecting different order)
3449            int tempReducedDimensionIndex = -1;
3450            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3451                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3452                    tempReducedDimensionIndex = d;
3453                    break;
3454                }
3455            }
3456    
3457            // copy dimension regions from this region to the temporary region
3458            for (int iDst = 0; iDst < 256; ++iDst) {
3459                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3460                if (!dstDimRgn) continue;
3461                std::map<dimension_t,int> dimCase;
3462                bool isValidZone = true;
3463                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3464                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3465                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3466                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3467                    baseBits += dstBits;
3468                    // there are also DimensionRegion objects of unused zones, skip them
3469                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3470                        isValidZone = false;
3471                        break;
3472                    }
3473                }
3474                if (!isValidZone) continue;
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3478                if (dimCase[type] >= zone) dimCase[type]++;
3479                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3480                dstDimRgn->CopyAssign(srcDimRgn);
3481                // if this is the upper most zone of the dimension passed to this
3482                // method, then correct (raise) its upper limit to 127
3483                if (newDef.split_type == split_type_normal && isLastZone)
3484                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3485            }
3486    
3487            // now tempRegion's dimensions and DimensionRegions basically reflect
3488            // what we wanted to get for this actual Region here, so we now just
3489            // delete and recreate the dimension in question with the new amount
3490            // zones and then copy back from tempRegion      
3491            DeleteDimension(oldDef);
3492            AddDimension(&newDef);
3493            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3494                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3495                if (!srcDimRgn) continue;
3496                std::map<dimension_t,int> dimCase;
3497                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3498                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3499                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3500                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3501                    baseBits += srcBits;
3502                }
3503                // a bit paranoid: cope with the chance that the dimensions would
3504                // have different order in source and destination regions
3505                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3506                if (!dstDimRgn) continue;
3507                dstDimRgn->CopyAssign(srcDimRgn);
3508            }
3509    
3510            // delete temporary region
3511            delete tempRgn;
3512    
3513            UpdateVelocityTable();
3514        }
3515    
3516        /** @brief Divide split zone of a dimension in two (increment zone amount).
3517         *
3518         * This will increment the amount of zones for the dimension (given by
3519         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3520         * in the middle of its zone range in two. So the two zones resulting from
3521         * the zone being splitted, will be an equivalent copy regarding all their
3522         * articulation informations and sample reference. The two zones will only
3523         * differ in their zone's upper limit
3524         * (DimensionRegion::DimensionUpperLimits).
3525         *
3526         * @param type - identifies the dimension where a zone shall be splitted
3527         * @param zone - index of the dimension split zone that shall be splitted
3528         * @throws gig::Exception if requested zone could not be splitted
3529         */
3530        void Region::SplitDimensionZone(dimension_t type, int zone) {
3531            dimension_def_t* oldDef = GetDimensionDefinition(type);
3532            if (!oldDef)
3533                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3534            if (zone < 0 || zone >= oldDef->zones)
3535                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3536    
3537            const int newZoneSize = oldDef->zones + 1;
3538    
3539            // create a temporary Region which just acts as a temporary copy
3540            // container and will be deleted at the end of this function and will
3541            // also not be visible through the API during this process
3542            gig::Region* tempRgn = NULL;
3543            {
3544                // adding these temporary chunks is probably not even necessary
3545                Instrument* instr = static_cast<Instrument*>(GetParent());
3546                RIFF::List* pCkInstrument = instr->pCkInstrument;
3547                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3548                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3549                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3550                tempRgn = new Region(instr, rgn);
3551            }
3552    
3553            // copy this region's dimensions (with already the dimension split size
3554            // requested by the arguments of this method call) to the temporary
3555            // region, and don't use Region::CopyAssign() here for this task, since
3556            // it would also alter fast lookup helper variables here and there
3557            dimension_def_t newDef;
3558            for (int i = 0; i < Dimensions; ++i) {
3559                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3560                // is this the dimension requested by the method arguments? ...
3561                if (def.dimension == type) { // ... if yes, increment zone amount by one
3562                    def.zones = newZoneSize;
3563                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3564                    newDef = def;
3565                }
3566                tempRgn->AddDimension(&def);
3567            }
3568    
3569            // find the dimension index in the tempRegion which is the dimension
3570            // type passed to this method (paranoidly expecting different order)
3571            int tempIncreasedDimensionIndex = -1;
3572            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3573                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3574                    tempIncreasedDimensionIndex = d;
3575                    break;
3576                }
3577            }
3578    
3579            // copy dimension regions from this region to the temporary region
3580            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3581                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3582                if (!srcDimRgn) continue;
3583                std::map<dimension_t,int> dimCase;
3584                bool isValidZone = true;
3585                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3586                    const int srcBits = pDimensionDefinitions[d].bits;
3587                    dimCase[pDimensionDefinitions[d].dimension] =
3588                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3589                    // there are also DimensionRegion objects for unused zones, skip them
3590                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3591                        isValidZone = false;
3592                        break;
3593                    }
3594                    baseBits += srcBits;
3595                }
3596                if (!isValidZone) continue;
3597                // a bit paranoid: cope with the chance that the dimensions would
3598                // have different order in source and destination regions            
3599                if (dimCase[type] > zone) dimCase[type]++;
3600                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3601                dstDimRgn->CopyAssign(srcDimRgn);
3602                // if this is the requested zone to be splitted, then also copy
3603                // the source DimensionRegion to the newly created target zone
3604                // and set the old zones upper limit lower
3605                if (dimCase[type] == zone) {
3606                    // lower old zones upper limit
3607                    if (newDef.split_type == split_type_normal) {
3608                        const int high =
3609                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3610                        int low = 0;
3611                        if (zone > 0) {
3612                            std::map<dimension_t,int> lowerCase = dimCase;
3613                            lowerCase[type]--;
3614                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3615                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3616                        }
3617                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3618                    }
3619                    // fill the newly created zone of the divided zone as well
3620                    dimCase[type]++;
3621                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3622                    dstDimRgn->CopyAssign(srcDimRgn);
3623                }
3624            }
3625    
3626            // now tempRegion's dimensions and DimensionRegions basically reflect
3627            // what we wanted to get for this actual Region here, so we now just
3628            // delete and recreate the dimension in question with the new amount
3629            // zones and then copy back from tempRegion      
3630            DeleteDimension(oldDef);
3631            AddDimension(&newDef);
3632            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3633                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3634                if (!srcDimRgn) continue;
3635                std::map<dimension_t,int> dimCase;
3636                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3637                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3638                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3639                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3640                    baseBits += srcBits;
3641                }
3642                // a bit paranoid: cope with the chance that the dimensions would
3643                // have different order in source and destination regions
3644                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3645                if (!dstDimRgn) continue;
3646                dstDimRgn->CopyAssign(srcDimRgn);
3647            }
3648    
3649            // delete temporary region
3650            delete tempRgn;
3651    
3652            UpdateVelocityTable();
3653        }
3654    
3655        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3656            uint8_t bits[8] = {};
3657            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3658                 it != DimCase.end(); ++it)
3659            {
3660                for (int d = 0; d < Dimensions; ++d) {
3661                    if (pDimensionDefinitions[d].dimension == it->first) {
3662                        bits[d] = it->second;
3663                        goto nextDimCaseSlice;
3664                    }
3665                }
3666                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3667                nextDimCaseSlice:
3668                ; // noop
3669            }
3670            return GetDimensionRegionByBit(bits);
3671        }
3672    
3673        /**
3674         * Searches in the current Region for a dimension of the given dimension
3675         * type and returns the precise configuration of that dimension in this
3676         * Region.
3677         *
3678         * @param type - dimension type of the sought dimension
3679         * @returns dimension definition or NULL if there is no dimension with
3680         *          sought type in this Region.
3681         */
3682        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3683            for (int i = 0; i < Dimensions; ++i)
3684                if (pDimensionDefinitions[i].dimension == type)
3685                    return &pDimensionDefinitions[i];
3686            return NULL;
3687        }
3688    
3689      Region::~Region() {      Region::~Region() {
3690          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3691              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2445  namespace { Line 3724  namespace {
3724              } else {              } else {
3725                  switch (pDimensionDefinitions[i].split_type) {                  switch (pDimensionDefinitions[i].split_type) {
3726                      case split_type_normal:                      case split_type_normal:
3727                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3728                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3729                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3730                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3731                                }
3732                            } else {
3733                                // gig2: evenly sized zones
3734                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3735                            }
3736                          break;                          break;
3737                      case split_type_bit: // the value is already the sought dimension bit number                      case split_type_bit: // the value is already the sought dimension bit number
3738                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
# Line 2459  namespace { Line 3746  namespace {
3746          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3747          if (veldim != -1) {          if (veldim != -1) {
3748              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3749              if (dimreg->VelocityUpperLimit) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3750                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim]];
3751              else // normal split type              else // normal split type
3752                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
# Line 2518  namespace { Line 3805  namespace {
3805          }          }
3806          return NULL;          return NULL;
3807      }      }
3808        
3809        /**
3810         * Make a (semi) deep copy of the Region object given by @a orig
3811         * and assign it to this object.
3812         *
3813         * Note that all sample pointers referenced by @a orig are simply copied as
3814         * memory address. Thus the respective samples are shared, not duplicated!
3815         *
3816         * @param orig - original Region object to be copied from
3817         */
3818        void Region::CopyAssign(const Region* orig) {
3819            CopyAssign(orig, NULL);
3820        }
3821        
3822        /**
3823         * Make a (semi) deep copy of the Region object given by @a orig and
3824         * assign it to this object
3825         *
3826         * @param mSamples - crosslink map between the foreign file's samples and
3827         *                   this file's samples
3828         */
3829        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3830            // handle base classes
3831            DLS::Region::CopyAssign(orig);
3832            
3833            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3834                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3835            }
3836            
3837            // handle own member variables
3838            for (int i = Dimensions - 1; i >= 0; --i) {
3839                DeleteDimension(&pDimensionDefinitions[i]);
3840            }
3841            Layers = 0; // just to be sure
3842            for (int i = 0; i < orig->Dimensions; i++) {
3843                // we need to copy the dim definition here, to avoid the compiler
3844                // complaining about const-ness issue
3845                dimension_def_t def = orig->pDimensionDefinitions[i];
3846                AddDimension(&def);
3847            }
3848            for (int i = 0; i < 256; i++) {
3849                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3850                    pDimensionRegions[i]->CopyAssign(
3851                        orig->pDimensionRegions[i],
3852                        mSamples
3853                    );
3854                }
3855            }
3856            Layers = orig->Layers;
3857        }
3858    
3859    
3860    // *************** MidiRule ***************
3861    // *
3862    
3863        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3864            _3ewg->SetPos(36);
3865            Triggers = _3ewg->ReadUint8();
3866            _3ewg->SetPos(40);
3867            ControllerNumber = _3ewg->ReadUint8();
3868            _3ewg->SetPos(46);
3869            for (int i = 0 ; i < Triggers ; i++) {
3870                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3871                pTriggers[i].Descending = _3ewg->ReadUint8();
3872                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3873                pTriggers[i].Key = _3ewg->ReadUint8();
3874                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3875                pTriggers[i].Velocity = _3ewg->ReadUint8();
3876                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3877                _3ewg->ReadUint8();
3878            }
3879        }
3880    
3881        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3882            ControllerNumber(0),
3883            Triggers(0) {
3884        }
3885    
3886        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3887            pData[32] = 4;
3888            pData[33] = 16;
3889            pData[36] = Triggers;
3890            pData[40] = ControllerNumber;
3891            for (int i = 0 ; i < Triggers ; i++) {
3892                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3893                pData[47 + i * 8] = pTriggers[i].Descending;
3894                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3895                pData[49 + i * 8] = pTriggers[i].Key;
3896                pData[50 + i * 8] = pTriggers[i].NoteOff;
3897                pData[51 + i * 8] = pTriggers[i].Velocity;
3898                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3899            }
3900        }
3901    
3902        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3903            _3ewg->SetPos(36);
3904            LegatoSamples = _3ewg->ReadUint8(); // always 12
3905            _3ewg->SetPos(40);
3906            BypassUseController = _3ewg->ReadUint8();
3907            BypassKey = _3ewg->ReadUint8();
3908            BypassController = _3ewg->ReadUint8();
3909            ThresholdTime = _3ewg->ReadUint16();
3910            _3ewg->ReadInt16();
3911            ReleaseTime = _3ewg->ReadUint16();
3912            _3ewg->ReadInt16();
3913            KeyRange.low = _3ewg->ReadUint8();
3914            KeyRange.high = _3ewg->ReadUint8();
3915            _3ewg->SetPos(64);
3916            ReleaseTriggerKey = _3ewg->ReadUint8();
3917            AltSustain1Key = _3ewg->ReadUint8();
3918            AltSustain2Key = _3ewg->ReadUint8();
3919        }
3920    
3921        MidiRuleLegato::MidiRuleLegato() :
3922            LegatoSamples(12),
3923            BypassUseController(false),
3924            BypassKey(0),
3925            BypassController(1),
3926            ThresholdTime(20),
3927            ReleaseTime(20),
3928            ReleaseTriggerKey(0),
3929            AltSustain1Key(0),
3930            AltSustain2Key(0)
3931        {
3932            KeyRange.low = KeyRange.high = 0;
3933        }
3934    
3935        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3936            pData[32] = 0;
3937            pData[33] = 16;
3938            pData[36] = LegatoSamples;
3939            pData[40] = BypassUseController;
3940            pData[41] = BypassKey;
3941            pData[42] = BypassController;
3942            store16(&pData[43], ThresholdTime);
3943            store16(&pData[47], ReleaseTime);
3944            pData[51] = KeyRange.low;
3945            pData[52] = KeyRange.high;
3946            pData[64] = ReleaseTriggerKey;
3947            pData[65] = AltSustain1Key;
3948            pData[66] = AltSustain2Key;
3949        }
3950    
3951        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3952            _3ewg->SetPos(36);
3953            Articulations = _3ewg->ReadUint8();
3954            int flags = _3ewg->ReadUint8();
3955            Polyphonic = flags & 8;
3956            Chained = flags & 4;
3957            Selector = (flags & 2) ? selector_controller :
3958                (flags & 1) ? selector_key_switch : selector_none;
3959            Patterns = _3ewg->ReadUint8();
3960            _3ewg->ReadUint8(); // chosen row
3961            _3ewg->ReadUint8(); // unknown
3962            _3ewg->ReadUint8(); // unknown
3963            _3ewg->ReadUint8(); // unknown
3964            KeySwitchRange.low = _3ewg->ReadUint8();
3965            KeySwitchRange.high = _3ewg->ReadUint8();
3966            Controller = _3ewg->ReadUint8();
3967            PlayRange.low = _3ewg->ReadUint8();
3968            PlayRange.high = _3ewg->ReadUint8();
3969    
3970            int n = std::min(int(Articulations), 32);
3971            for (int i = 0 ; i < n ; i++) {
3972                _3ewg->ReadString(pArticulations[i], 32);
3973            }
3974            _3ewg->SetPos(1072);
3975            n = std::min(int(Patterns), 32);
3976            for (int i = 0 ; i < n ; i++) {
3977                _3ewg->ReadString(pPatterns[i].Name, 16);
3978                pPatterns[i].Size = _3ewg->ReadUint8();
3979                _3ewg->Read(&pPatterns[i][0], 1, 32);
3980            }
3981        }
3982    
3983        MidiRuleAlternator::MidiRuleAlternator() :
3984            Articulations(0),
3985            Patterns(0),
3986            Selector(selector_none),
3987            Controller(0),
3988            Polyphonic(false),
3989            Chained(false)
3990        {
3991            PlayRange.low = PlayRange.high = 0;
3992            KeySwitchRange.low = KeySwitchRange.high = 0;
3993        }
3994    
3995        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3996            pData[32] = 3;
3997            pData[33] = 16;
3998            pData[36] = Articulations;
3999            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4000                (Selector == selector_controller ? 2 :
4001                 (Selector == selector_key_switch ? 1 : 0));
4002            pData[38] = Patterns;
4003    
4004            pData[43] = KeySwitchRange.low;
4005            pData[44] = KeySwitchRange.high;
4006            pData[45] = Controller;
4007            pData[46] = PlayRange.low;
4008            pData[47] = PlayRange.high;
4009    
4010            char* str = reinterpret_cast<char*>(pData);
4011            int pos = 48;
4012            int n = std::min(int(Articulations), 32);
4013            for (int i = 0 ; i < n ; i++, pos += 32) {
4014                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4015            }
4016    
4017            pos = 1072;
4018            n = std::min(int(Patterns), 32);
4019            for (int i = 0 ; i < n ; i++, pos += 49) {
4020                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4021                pData[pos + 16] = pPatterns[i].Size;
4022                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4023            }
4024        }
4025    
4026  // *************** Instrument ***************  // *************** Instrument ***************
4027  // *  // *
4028    
4029      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4030          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
4031                { CHUNK_ID_INAM, 64 },
4032                { CHUNK_ID_ISFT, 12 },
4033                { 0, 0 }
4034            };
4035            pInfo->SetFixedStringLengths(fixedStringLengths);
4036    
4037          // Initialization          // Initialization
4038          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4039            EffectSend = 0;
4040            Attenuation = 0;
4041            FineTune = 0;
4042            PitchbendRange = 0;
4043            PianoReleaseMode = false;
4044            DimensionKeyRange.low = 0;
4045            DimensionKeyRange.high = 0;
4046            pMidiRules = new MidiRule*[3];
4047            pMidiRules[0] = NULL;
4048    
4049          // Loading          // Loading
4050          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2543  namespace { Line 4059  namespace {
4059                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4060                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4061                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4062    
4063                    if (_3ewg->GetSize() > 32) {
4064                        // read MIDI rules
4065                        int i = 0;
4066                        _3ewg->SetPos(32);
4067                        uint8_t id1 = _3ewg->ReadUint8();
4068                        uint8_t id2 = _3ewg->ReadUint8();
4069    
4070                        if (id2 == 16) {
4071                            if (id1 == 4) {
4072                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4073                            } else if (id1 == 0) {
4074                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4075                            } else if (id1 == 3) {
4076                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4077                            } else {
4078                                pMidiRules[i++] = new MidiRuleUnknown;
4079                            }
4080                        }
4081                        else if (id1 != 0 || id2 != 0) {
4082                            pMidiRules[i++] = new MidiRuleUnknown;
4083                        }
4084                        //TODO: all the other types of rules
4085    
4086                        pMidiRules[i] = NULL;
4087                    }
4088              }              }
4089          }          }
4090    
4091          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
4092          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
4093          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4094              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4095              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
4096                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
4097                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4098                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4099                            pRegions->push_back(new Region(this, rgn));
4100                        }
4101                        rgn = lrgn->GetNextSubList();
4102                  }                  }
4103                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
4104                    UpdateRegionKeyTable();
4105              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4106          }          }
4107    
4108          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4109      }      }
4110    
4111      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4112            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4113          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
4114          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
4115          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2576  namespace { Line 4121  namespace {
4121      }      }
4122    
4123      Instrument::~Instrument() {      Instrument::~Instrument() {
4124            for (int i = 0 ; pMidiRules[i] ; i++) {
4125                delete pMidiRules[i];
4126            }
4127            delete[] pMidiRules;
4128      }      }
4129    
4130      /**      /**
# Line 2604  namespace { Line 4153  namespace {
4153          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4154          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4155          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4156          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4157                File* pFile = (File*) GetParent();
4158    
4159                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4160                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4161                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4162                memset(_3ewg->LoadChunkData(), 0, size);
4163            }
4164          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4165          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4166          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
4167          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
4168          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
4169          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
4170          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4171                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4172          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
4173          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
4174    
4175            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4176                pData[32] = 0;
4177                pData[33] = 0;
4178            } else {
4179                for (int i = 0 ; pMidiRules[i] ; i++) {
4180                    pMidiRules[i]->UpdateChunks(pData);
4181                }
4182            }
4183      }      }
4184    
4185      /**      /**
# Line 2625  namespace { Line 4190  namespace {
4190       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4191       */       */
4192      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4193          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4194          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4195    
4196          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2683  namespace { Line 4248  namespace {
4248          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4249      }      }
4250    
4251        /**
4252         * Returns a MIDI rule of the instrument.
4253         *
4254         * The list of MIDI rules, at least in gig v3, always contains at
4255         * most two rules. The second rule can only be the DEF filter
4256         * (which currently isn't supported by libgig).
4257         *
4258         * @param i - MIDI rule number
4259         * @returns   pointer address to MIDI rule number i or NULL if there is none
4260         */
4261        MidiRule* Instrument::GetMidiRule(int i) {
4262            return pMidiRules[i];
4263        }
4264    
4265        /**
4266         * Adds the "controller trigger" MIDI rule to the instrument.
4267         *
4268         * @returns the new MIDI rule
4269         */
4270        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4271            delete pMidiRules[0];
4272            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4273            pMidiRules[0] = r;
4274            pMidiRules[1] = 0;
4275            return r;
4276        }
4277    
4278        /**
4279         * Adds the legato MIDI rule to the instrument.
4280         *
4281         * @returns the new MIDI rule
4282         */
4283        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4284            delete pMidiRules[0];
4285            MidiRuleLegato* r = new MidiRuleLegato;
4286            pMidiRules[0] = r;
4287            pMidiRules[1] = 0;
4288            return r;
4289        }
4290    
4291        /**
4292         * Adds the alternator MIDI rule to the instrument.
4293         *
4294         * @returns the new MIDI rule
4295         */
4296        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4297            delete pMidiRules[0];
4298            MidiRuleAlternator* r = new MidiRuleAlternator;
4299            pMidiRules[0] = r;
4300            pMidiRules[1] = 0;
4301            return r;
4302        }
4303    
4304        /**
4305         * Deletes a MIDI rule from the instrument.
4306         *
4307         * @param i - MIDI rule number
4308         */
4309        void Instrument::DeleteMidiRule(int i) {
4310            delete pMidiRules[i];
4311            pMidiRules[i] = 0;
4312        }
4313    
4314        /**
4315         * Make a (semi) deep copy of the Instrument object given by @a orig
4316         * and assign it to this object.
4317         *
4318         * Note that all sample pointers referenced by @a orig are simply copied as
4319         * memory address. Thus the respective samples are shared, not duplicated!
4320         *
4321         * @param orig - original Instrument object to be copied from
4322         */
4323        void Instrument::CopyAssign(const Instrument* orig) {
4324            CopyAssign(orig, NULL);
4325        }
4326            
4327        /**
4328         * Make a (semi) deep copy of the Instrument object given by @a orig
4329         * and assign it to this object.
4330         *
4331         * @param orig - original Instrument object to be copied from
4332         * @param mSamples - crosslink map between the foreign file's samples and
4333         *                   this file's samples
4334         */
4335        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4336            // handle base class
4337            // (without copying DLS region stuff)
4338            DLS::Instrument::CopyAssignCore(orig);
4339            
4340            // handle own member variables
4341            Attenuation = orig->Attenuation;
4342            EffectSend = orig->EffectSend;
4343            FineTune = orig->FineTune;
4344            PitchbendRange = orig->PitchbendRange;
4345            PianoReleaseMode = orig->PianoReleaseMode;
4346            DimensionKeyRange = orig->DimensionKeyRange;
4347            
4348            // free old midi rules
4349            for (int i = 0 ; pMidiRules[i] ; i++) {
4350                delete pMidiRules[i];
4351            }
4352            //TODO: MIDI rule copying
4353            pMidiRules[0] = NULL;
4354            
4355            // delete all old regions
4356            while (Regions) DeleteRegion(GetFirstRegion());
4357            // create new regions and copy them from original
4358            {
4359                RegionList::const_iterator it = orig->pRegions->begin();
4360                for (int i = 0; i < orig->Regions; ++i, ++it) {
4361                    Region* dstRgn = AddRegion();
4362                    //NOTE: Region does semi-deep copy !
4363                    dstRgn->CopyAssign(
4364                        static_cast<gig::Region*>(*it),
4365                        mSamples
4366                    );
4367                }
4368            }
4369    
4370            UpdateRegionKeyTable();
4371        }
4372    
4373    
4374  // *************** Group ***************  // *************** Group ***************
# Line 2690  namespace { Line 4376  namespace {
4376    
4377      /** @brief Constructor.      /** @brief Constructor.
4378       *       *
4379       * @param file   - pointer to the RIFF::File object of this .gig file       * @param file   - pointer to the gig::File object
4380       * @param ck3gnm - pointer to 3gnm chunk associated with this group       * @param ck3gnm - pointer to 3gnm chunk associated with this group or
4381         *                 NULL if this is a new Group
4382       */       */
4383      Group::Group(RIFF::File* file, RIFF::Chunk* ck3gnm) {      Group::Group(File* file, RIFF::Chunk* ck3gnm) {
4384          pFile      = file;          pFile      = file;
4385          pNameChunk = ck3gnm;          pNameChunk = ck3gnm;
4386          ::LoadString(pNameChunk, Name);          ::LoadString(pNameChunk, Name);
4387      }      }
4388    
4389      Group::~Group() {      Group::~Group() {
4390            // remove the chunk associated with this group (if any)
4391            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4392      }      }
4393    
4394      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
4395       *       *
4396       * Apply current Group field values to the respective. You have to call       * Apply current Group field values to the respective chunks. You have
4397       * File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
4398         *
4399         * Usually there is absolutely no need to call this method explicitly.
4400         * It will be called automatically when File::Save() was called.
4401       */       */
4402      void Group::UpdateChunks() {      void Group::UpdateChunks() {
4403          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
4404          RIFF::List* _3gri = pFile->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
4405          if (!_3gri) _3gri = pFile->AddSubList(LIST_TYPE_3GRI);          if (!_3gri) {
4406                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
4407                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4408            }
4409          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4410          if (!_3gnl) _3gnl = pFile->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4411    
4412            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
4413                // v3 has a fixed list of 128 strings, find a free one
4414                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
4415                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
4416                        pNameChunk = ck;
4417                        break;
4418                    }
4419                }
4420            }
4421    
4422          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
4423          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
4424      }      }
4425    
4426        /**
4427         * Returns the first Sample of this Group. You have to call this method
4428         * once before you use GetNextSample().
4429         *
4430         * <b>Notice:</b> this method might block for a long time, in case the
4431         * samples of this .gig file were not scanned yet
4432         *
4433         * @returns  pointer address to first Sample or NULL if there is none
4434         *           applied to this Group
4435         * @see      GetNextSample()
4436         */
4437        Sample* Group::GetFirstSample() {
4438            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4439            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
4440                if (pSample->GetGroup() == this) return pSample;
4441            }
4442            return NULL;
4443        }
4444    
4445        /**
4446         * Returns the next Sample of the Group. You have to call
4447         * GetFirstSample() once before you can use this method. By calling this
4448         * method multiple times it iterates through the Samples assigned to
4449         * this Group.
4450         *
4451         * @returns  pointer address to the next Sample of this Group or NULL if
4452         *           end reached
4453         * @see      GetFirstSample()
4454         */
4455        Sample* Group::GetNextSample() {
4456            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4457            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
4458                if (pSample->GetGroup() == this) return pSample;
4459            }
4460            return NULL;
4461        }
4462    
4463        /**
4464         * Move Sample given by \a pSample from another Group to this Group.
4465         */
4466        void Group::AddSample(Sample* pSample) {
4467            pSample->pGroup = this;
4468        }
4469    
4470        /**
4471         * Move all members of this group to another group (preferably the 1st
4472         * one except this). This method is called explicitly by
4473         * File::DeleteGroup() thus when a Group was deleted. This code was
4474         * intentionally not placed in the destructor!
4475         */
4476        void Group::MoveAll() {
4477            // get "that" other group first
4478            Group* pOtherGroup = NULL;
4479            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
4480                if (pOtherGroup != this) break;
4481            }
4482            if (!pOtherGroup) throw Exception(
4483                "Could not move samples to another group, since there is no "
4484                "other Group. This is a bug, report it!"
4485            );
4486            // now move all samples of this group to the other group
4487            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4488                pOtherGroup->AddSample(pSample);
4489            }
4490        }
4491    
4492    
4493    
4494  // *************** File ***************  // *************** File ***************
4495  // *  // *
4496    
4497        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
4498        const DLS::version_t File::VERSION_2 = {
4499            0, 2, 19980628 & 0xffff, 19980628 >> 16
4500        };
4501    
4502        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
4503        const DLS::version_t File::VERSION_3 = {
4504            0, 3, 20030331 & 0xffff, 20030331 >> 16
4505        };
4506    
4507        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
4508            { CHUNK_ID_IARL, 256 },
4509            { CHUNK_ID_IART, 128 },
4510            { CHUNK_ID_ICMS, 128 },
4511            { CHUNK_ID_ICMT, 1024 },
4512            { CHUNK_ID_ICOP, 128 },
4513            { CHUNK_ID_ICRD, 128 },
4514            { CHUNK_ID_IENG, 128 },
4515            { CHUNK_ID_IGNR, 128 },
4516            { CHUNK_ID_IKEY, 128 },
4517            { CHUNK_ID_IMED, 128 },
4518            { CHUNK_ID_INAM, 128 },
4519            { CHUNK_ID_IPRD, 128 },
4520            { CHUNK_ID_ISBJ, 128 },
4521            { CHUNK_ID_ISFT, 128 },
4522            { CHUNK_ID_ISRC, 128 },
4523            { CHUNK_ID_ISRF, 128 },
4524            { CHUNK_ID_ITCH, 128 },
4525            { 0, 0 }
4526        };
4527    
4528      File::File() : DLS::File() {      File::File() : DLS::File() {
4529            bAutoLoad = true;
4530            *pVersion = VERSION_3;
4531          pGroups = NULL;          pGroups = NULL;
4532          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4533            pInfo->ArchivalLocation = String(256, ' ');
4534    
4535            // add some mandatory chunks to get the file chunks in right
4536            // order (INFO chunk will be moved to first position later)
4537            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
4538            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
4539            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
4540    
4541            GenerateDLSID();
4542      }      }
4543    
4544      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
4545            bAutoLoad = true;
4546          pGroups = NULL;          pGroups = NULL;
4547          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4548      }      }
4549    
4550      File::~File() {      File::~File() {
# Line 2756  namespace { Line 4571  namespace {
4571          SamplesIterator++;          SamplesIterator++;
4572          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
4573      }      }
4574        
4575        /**
4576         * Returns Sample object of @a index.
4577         *
4578         * @returns sample object or NULL if index is out of bounds
4579         */
4580        Sample* File::GetSample(uint index) {
4581            if (!pSamples) LoadSamples();
4582            if (!pSamples) return NULL;
4583            DLS::File::SampleList::iterator it = pSamples->begin();
4584            for (int i = 0; i < index; ++i) {
4585                ++it;
4586                if (it == pSamples->end()) return NULL;
4587            }
4588            if (it == pSamples->end()) return NULL;
4589            return static_cast<gig::Sample*>( *it );
4590        }
4591    
4592      /** @brief Add a new sample.      /** @brief Add a new sample.
4593       *       *
# Line 2771  namespace { Line 4603  namespace {
4603         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
4604         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
4605         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
4606    
4607           // add mandatory chunks to get the chunks in right order
4608           wave->AddSubChunk(CHUNK_ID_FMT, 16);
4609           wave->AddSubList(LIST_TYPE_INFO);
4610    
4611         pSamples->push_back(pSample);         pSamples->push_back(pSample);
4612         return pSample;         return pSample;
4613      }      }
4614    
4615      /** @brief Delete a sample.      /** @brief Delete a sample.
4616       *       *
4617       * This will delete the given Sample object from the gig file. You have       * This will delete the given Sample object from the gig file. Any
4618       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
4619         * removed. You have to call Save() to make this persistent to the file.
4620       *       *
4621       * @param pSample - sample to delete       * @param pSample - sample to delete
4622       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2787  namespace { Line 4625  namespace {
4625          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
4626          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
4627          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
4628            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
4629          pSamples->erase(iter);          pSamples->erase(iter);
4630          delete pSample;          delete pSample;
4631    
4632            SampleList::iterator tmp = SamplesIterator;
4633            // remove all references to the sample
4634            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4635                 instrument = GetNextInstrument()) {
4636                for (Region* region = instrument->GetFirstRegion() ; region ;
4637                     region = instrument->GetNextRegion()) {
4638    
4639                    if (region->GetSample() == pSample) region->SetSample(NULL);
4640    
4641                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
4642                        gig::DimensionRegion *d = region->pDimensionRegions[i];
4643                        if (d->pSample == pSample) d->pSample = NULL;
4644                    }
4645                }
4646            }
4647            SamplesIterator = tmp; // restore iterator
4648      }      }
4649    
4650      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2796  namespace { Line 4652  namespace {
4652      }      }
4653    
4654      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
4655            // Groups must be loaded before samples, because samples will try
4656            // to resolve the group they belong to
4657            if (!pGroups) LoadGroups();
4658    
4659          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
4660    
4661          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
# Line 2875  namespace { Line 4735  namespace {
4735              progress_t subprogress;              progress_t subprogress;
4736              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
4737              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
4738              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
4739                    GetFirstSample(&subprogress); // now force all samples to be loaded
4740              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
4741    
4742              // instrument loading subtask              // instrument loading subtask
# Line 2908  namespace { Line 4769  namespace {
4769         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
4770         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4771         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4772    
4773           // add mandatory chunks to get the chunks in right order
4774           lstInstr->AddSubList(LIST_TYPE_INFO);
4775           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4776    
4777         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
4778           pInstrument->GenerateDLSID();
4779    
4780           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4781    
4782           // this string is needed for the gig to be loadable in GSt:
4783           pInstrument->pInfo->Software = "Endless Wave";
4784    
4785         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4786         return pInstrument;         return pInstrument;
4787      }      }
4788        
4789        /** @brief Add a duplicate of an existing instrument.
4790         *
4791         * Duplicates the instrument definition given by @a orig and adds it
4792         * to this file. This allows in an instrument editor application to
4793         * easily create variations of an instrument, which will be stored in
4794         * the same .gig file, sharing i.e. the same samples.
4795         *
4796         * Note that all sample pointers referenced by @a orig are simply copied as
4797         * memory address. Thus the respective samples are shared, not duplicated!
4798         *
4799         * You have to call Save() to make this persistent to the file.
4800         *
4801         * @param orig - original instrument to be copied
4802         * @returns duplicated copy of the given instrument
4803         */
4804        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4805            Instrument* instr = AddInstrument();
4806            instr->CopyAssign(orig);
4807            return instr;
4808        }
4809        
4810        /** @brief Add content of another existing file.
4811         *
4812         * Duplicates the samples, groups and instruments of the original file
4813         * given by @a pFile and adds them to @c this File. In case @c this File is
4814         * a new one that you haven't saved before, then you have to call
4815         * SetFileName() before calling AddContentOf(), because this method will
4816         * automatically save this file during operation, which is required for
4817         * writing the sample waveform data by disk streaming.
4818         *
4819         * @param pFile - original file whose's content shall be copied from
4820         */
4821        void File::AddContentOf(File* pFile) {
4822            static int iCallCount = -1;
4823            iCallCount++;
4824            std::map<Group*,Group*> mGroups;
4825            std::map<Sample*,Sample*> mSamples;
4826            
4827            // clone sample groups
4828            for (int i = 0; pFile->GetGroup(i); ++i) {
4829                Group* g = AddGroup();
4830                g->Name =
4831                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4832                mGroups[pFile->GetGroup(i)] = g;
4833            }
4834            
4835            // clone samples (not waveform data here yet)
4836            for (int i = 0; pFile->GetSample(i); ++i) {
4837                Sample* s = AddSample();
4838                s->CopyAssignMeta(pFile->GetSample(i));
4839                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4840                mSamples[pFile->GetSample(i)] = s;
4841            }
4842            
4843            //BUG: For some reason this method only works with this additional
4844            //     Save() call in between here.
4845            //
4846            // Important: The correct one of the 2 Save() methods has to be called
4847            // here, depending on whether the file is completely new or has been
4848            // saved to disk already, otherwise it will result in data corruption.
4849            if (pRIFF->IsNew())
4850                Save(GetFileName());
4851            else
4852                Save();
4853            
4854            // clone instruments
4855            // (passing the crosslink table here for the cloned samples)
4856            for (int i = 0; pFile->GetInstrument(i); ++i) {
4857                Instrument* instr = AddInstrument();
4858                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4859            }
4860            
4861            // Mandatory: file needs to be saved to disk at this point, so this
4862            // file has the correct size and data layout for writing the samples'
4863            // waveform data to disk.
4864            Save();
4865            
4866            // clone samples' waveform data
4867            // (using direct read & write disk streaming)
4868            for (int i = 0; pFile->GetSample(i); ++i) {
4869                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4870            }
4871        }
4872    
4873      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4874       *       *
# Line 2919  namespace { Line 4876  namespace {
4876       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
4877       *       *
4878       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
4879       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
4880       */       */
4881      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
4882          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
# Line 2959  namespace { Line 4916  namespace {
4916          }          }
4917      }      }
4918    
4919        /// Updates the 3crc chunk with the checksum of a sample. The
4920        /// update is done directly to disk, as this method is called
4921        /// after File::Save()
4922        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4923            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4924            if (!_3crc) return;
4925    
4926            // get the index of the sample
4927            int iWaveIndex = -1;
4928            File::SampleList::iterator iter = pSamples->begin();
4929            File::SampleList::iterator end  = pSamples->end();
4930            for (int index = 0; iter != end; ++iter, ++index) {
4931                if (*iter == pSample) {
4932                    iWaveIndex = index;
4933                    break;
4934                }
4935            }
4936            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4937    
4938            // write the CRC-32 checksum to disk
4939            _3crc->SetPos(iWaveIndex * 8);
4940            uint32_t tmp = 1;
4941            _3crc->WriteUint32(&tmp); // unknown, always 1?
4942            _3crc->WriteUint32(&crc);
4943        }
4944    
4945      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
4946          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
4947          if (!pGroups) return NULL;          // there must always be at least one group
4948          GroupsIterator = pGroups->begin();          GroupsIterator = pGroups->begin();
4949          return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;          return *GroupsIterator;
4950      }      }
4951    
4952      Group* File::GetNextGroup() {      Group* File::GetNextGroup() {
# Line 2980  namespace { Line 4963  namespace {
4963       */       */
4964      Group* File::GetGroup(uint index) {      Group* File::GetGroup(uint index) {
4965          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
         if (!pGroups) return NULL;  
4966          GroupsIterator = pGroups->begin();          GroupsIterator = pGroups->begin();
4967          for (uint i = 0; GroupsIterator != pGroups->end(); i++) {          for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4968              if (i == index) return *GroupsIterator;              if (i == index) return *GroupsIterator;
# Line 2989  namespace { Line 4971  namespace {
4971          return NULL;          return NULL;
4972      }      }
4973    
4974        /**
4975         * Returns the group with the given group name.
4976         *
4977         * Note: group names don't have to be unique in the gig format! So there
4978         * can be multiple groups with the same name. This method will simply
4979         * return the first group found with the given name.
4980         *
4981         * @param name - name of the sought group
4982         * @returns sought group or NULL if there's no group with that name
4983         */
4984        Group* File::GetGroup(String name) {
4985            if (!pGroups) LoadGroups();
4986            GroupsIterator = pGroups->begin();
4987            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
4988                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
4989            return NULL;
4990        }
4991    
4992      Group* File::AddGroup() {      Group* File::AddGroup() {
4993          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
4994          if (!pGroups) pGroups = new std::list<Group*>;          // there must always be at least one group
4995          __ensureMandatoryChunksExist();          __ensureMandatoryChunksExist();
4996          Group* pGroup = new Group(pRIFF, NULL);          Group* pGroup = new Group(this, NULL);
4997          pGroups->push_back(pGroup);          pGroups->push_back(pGroup);
4998          return pGroup;          return pGroup;
4999      }      }
5000    
5001        /** @brief Delete a group and its samples.
5002         *
5003         * This will delete the given Group object and all the samples that
5004         * belong to this group from the gig file. You have to call Save() to
5005         * make this persistent to the file.
5006         *
5007         * @param pGroup - group to delete
5008         * @throws gig::Exception if given group could not be found
5009         */
5010      void File::DeleteGroup(Group* pGroup) {      void File::DeleteGroup(Group* pGroup) {
5011          if (!pGroups) throw gig::Exception("Could not delete group as there are no groups");          if (!pGroups) LoadGroups();
5012            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5013            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5014            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5015            // delete all members of this group
5016            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5017                DeleteSample(pSample);
5018            }
5019            // now delete this group object
5020            pGroups->erase(iter);
5021            delete pGroup;
5022        }
5023    
5024        /** @brief Delete a group.
5025         *
5026         * This will delete the given Group object from the gig file. All the
5027         * samples that belong to this group will not be deleted, but instead
5028         * be moved to another group. You have to call Save() to make this
5029         * persistent to the file.
5030         *
5031         * @param pGroup - group to delete
5032         * @throws gig::Exception if given group could not be found
5033         */
5034        void File::DeleteGroupOnly(Group* pGroup) {
5035            if (!pGroups) LoadGroups();
5036          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5037          if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");          if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5038            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5039            // move all members of this group to another group
5040            pGroup->MoveAll();
5041          pGroups->erase(iter);          pGroups->erase(iter);
5042          delete pGroup;          delete pGroup;
5043      }      }
5044    
5045      void File::LoadGroups() {      void File::LoadGroups() {
5046          if (!pGroups) pGroups = new std::list<Group*>;          if (!pGroups) pGroups = new std::list<Group*>;
5047            // try to read defined groups from file
5048          RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5049          if (!lst3gri) return;          if (lst3gri) {
5050          RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);              RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5051          if (!lst3gnl) return;              if (lst3gnl) {
5052          {                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5053              RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  while (ck) {
5054              while (ck) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5055                  if (ck->GetChunkID() == CHUNK_ID_3GNM) {                          if (pVersion && pVersion->major == 3 &&
5056                      pGroups->push_back(new Group(pRIFF, ck));                              strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5057    
5058                            pGroups->push_back(new Group(this, ck));
5059                        }
5060                        ck = lst3gnl->GetNextSubChunk();
5061                  }                  }
                 ck = lst3gnl->GetNextSubChunk();  
5062              }              }
5063          }          }
5064            // if there were no group(s), create at least the mandatory default group
5065            if (!pGroups->size()) {
5066                Group* pGroup = new Group(this, NULL);
5067                pGroup->Name = "Default Group";
5068                pGroups->push_back(pGroup);
5069            }
5070        }
5071    
5072        /**
5073         * Apply all the gig file's current instruments, samples, groups and settings
5074         * to the respective RIFF chunks. You have to call Save() to make changes
5075         * persistent.
5076         *
5077         * Usually there is absolutely no need to call this method explicitly.
5078         * It will be called automatically when File::Save() was called.
5079         *
5080         * @throws Exception - on errors
5081         */
5082        void File::UpdateChunks() {
5083            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5084    
5085            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5086    
5087            // first update base class's chunks
5088            DLS::File::UpdateChunks();
5089    
5090            if (newFile) {
5091                // INFO was added by Resource::UpdateChunks - make sure it
5092                // is placed first in file
5093                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
5094                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5095                if (first != info) {
5096                    pRIFF->MoveSubChunk(info, first);
5097                }
5098            }
5099    
5100            // update group's chunks
5101            if (pGroups) {
5102                // make sure '3gri' and '3gnl' list chunks exist
5103                // (before updating the Group chunks)
5104                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5105                if (!_3gri) {
5106                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5107                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5108                }
5109                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5110                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5111    
5112                // v3: make sure the file has 128 3gnm chunks
5113                // (before updating the Group chunks)
5114                if (pVersion && pVersion->major == 3) {
5115                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5116                    for (int i = 0 ; i < 128 ; i++) {
5117                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5118                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5119                    }
5120                }
5121    
5122                std::list<Group*>::iterator iter = pGroups->begin();
5123                std::list<Group*>::iterator end  = pGroups->end();
5124                for (; iter != end; ++iter) {
5125                    (*iter)->UpdateChunks();
5126                }
5127            }
5128    
5129            // update einf chunk
5130    
5131            // The einf chunk contains statistics about the gig file, such
5132            // as the number of regions and samples used by each
5133            // instrument. It is divided in equally sized parts, where the
5134            // first part contains information about the whole gig file,
5135            // and the rest of the parts map to each instrument in the
5136            // file.
5137            //
5138            // At the end of each part there is a bit map of each sample
5139            // in the file, where a set bit means that the sample is used
5140            // by the file/instrument.
5141            //
5142            // Note that there are several fields with unknown use. These
5143            // are set to zero.
5144    
5145            int sublen = pSamples->size() / 8 + 49;
5146            int einfSize = (Instruments + 1) * sublen;
5147    
5148            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5149            if (einf) {
5150                if (einf->GetSize() != einfSize) {
5151                    einf->Resize(einfSize);
5152                    memset(einf->LoadChunkData(), 0, einfSize);
5153                }
5154            } else if (newFile) {
5155                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5156            }
5157            if (einf) {
5158                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5159    
5160                std::map<gig::Sample*,int> sampleMap;
5161                int sampleIdx = 0;
5162                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5163                    sampleMap[pSample] = sampleIdx++;
5164                }
5165    
5166                int totnbusedsamples = 0;
5167                int totnbusedchannels = 0;
5168                int totnbregions = 0;
5169                int totnbdimregions = 0;
5170                int totnbloops = 0;
5171                int instrumentIdx = 0;
5172    
5173                memset(&pData[48], 0, sublen - 48);
5174    
5175                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5176                     instrument = GetNextInstrument()) {
5177                    int nbusedsamples = 0;
5178                    int nbusedchannels = 0;
5179                    int nbdimregions = 0;
5180                    int nbloops = 0;
5181    
5182                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5183    
5184                    for (Region* region = instrument->GetFirstRegion() ; region ;
5185                         region = instrument->GetNextRegion()) {
5186                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
5187                            gig::DimensionRegion *d = region->pDimensionRegions[i];
5188                            if (d->pSample) {
5189                                int sampleIdx = sampleMap[d->pSample];
5190                                int byte = 48 + sampleIdx / 8;
5191                                int bit = 1 << (sampleIdx & 7);
5192                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5193                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5194                                    nbusedsamples++;
5195                                    nbusedchannels += d->pSample->Channels;
5196    
5197                                    if ((pData[byte] & bit) == 0) {
5198                                        pData[byte] |= bit;
5199                                        totnbusedsamples++;
5200                                        totnbusedchannels += d->pSample->Channels;
5201                                    }
5202                                }
5203                            }
5204                            if (d->SampleLoops) nbloops++;
5205                        }
5206                        nbdimregions += region->DimensionRegions;
5207                    }
5208                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5209                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5210                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5211                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5212                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5213                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5214                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5215                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5216                    // next 8 bytes unknown
5217                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5218                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5219                    // next 4 bytes unknown
5220    
5221                    totnbregions += instrument->Regions;
5222                    totnbdimregions += nbdimregions;
5223                    totnbloops += nbloops;
5224                    instrumentIdx++;
5225                }
5226                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5227                // store32(&pData[0], sublen);
5228                store32(&pData[4], totnbusedchannels);
5229                store32(&pData[8], totnbusedsamples);
5230                store32(&pData[12], Instruments);
5231                store32(&pData[16], totnbregions);
5232                store32(&pData[20], totnbdimregions);
5233                store32(&pData[24], totnbloops);
5234                // next 8 bytes unknown
5235                // next 4 bytes unknown, not always 0
5236                store32(&pData[40], pSamples->size());
5237                // next 4 bytes unknown
5238            }
5239    
5240            // update 3crc chunk
5241    
5242            // The 3crc chunk contains CRC-32 checksums for the
5243            // samples. The actual checksum values will be filled in
5244            // later, by Sample::Write.
5245    
5246            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5247            if (_3crc) {
5248                _3crc->Resize(pSamples->size() * 8);
5249            } else if (newFile) {
5250                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5251                _3crc->LoadChunkData();
5252    
5253                // the order of einf and 3crc is not the same in v2 and v3
5254                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5255            }
5256        }
5257    
5258        /**
5259         * Enable / disable automatic loading. By default this properyt is
5260         * enabled and all informations are loaded automatically. However
5261         * loading all Regions, DimensionRegions and especially samples might
5262         * take a long time for large .gig files, and sometimes one might only
5263         * be interested in retrieving very superficial informations like the
5264         * amount of instruments and their names. In this case one might disable
5265         * automatic loading to avoid very slow response times.
5266         *
5267         * @e CAUTION: by disabling this property many pointers (i.e. sample
5268         * references) and informations will have invalid or even undefined
5269         * data! This feature is currently only intended for retrieving very
5270         * superficial informations in a very fast way. Don't use it to retrieve
5271         * details like synthesis informations or even to modify .gig files!
5272         */
5273        void File::SetAutoLoad(bool b) {
5274            bAutoLoad = b;
5275        }
5276    
5277        /**
5278         * Returns whether automatic loading is enabled.
5279         * @see SetAutoLoad()
5280         */
5281        bool File::GetAutoLoad() {
5282            return bAutoLoad;
5283      }      }
5284    
5285    

Legend:
Removed from v.929  
changed lines
  Added in v.2557

  ViewVC Help
Powered by ViewVC