/[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 930 by schoenebeck, Sun Oct 29 17:57:20 2006 UTC revision 2540 by schoenebeck, Wed Apr 23 16:39:43 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    
# Line 254  namespace { Line 255  namespace {
255  }  }
256    
257    
258    
259    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
260    // *
261    
262        static uint32_t* __initCRCTable() {
263            static uint32_t res[256];
264    
265            for (int i = 0 ; i < 256 ; i++) {
266                uint32_t c = i;
267                for (int j = 0 ; j < 8 ; j++) {
268                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269                }
270                res[i] = c;
271            }
272            return res;
273        }
274    
275        static const uint32_t* __CRCTable = __initCRCTable();
276    
277        /**
278         * Initialize a CRC variable.
279         *
280         * @param crc - variable to be initialized
281         */
282        inline static void __resetCRC(uint32_t& crc) {
283            crc = 0xffffffff;
284        }
285    
286        /**
287         * Used to calculate checksums of the sample data in a gig file. The
288         * checksums are stored in the 3crc chunk of the gig file and
289         * automatically updated when a sample is written with Sample::Write().
290         *
291         * One should call __resetCRC() to initialize the CRC variable to be
292         * used before calling this function the first time.
293         *
294         * After initializing the CRC variable one can call this function
295         * arbitrary times, i.e. to split the overall CRC calculation into
296         * steps.
297         *
298         * Once the whole data was processed by __calculateCRC(), one should
299         * call __encodeCRC() to get the final CRC result.
300         *
301         * @param buf     - pointer to data the CRC shall be calculated of
302         * @param bufSize - size of the data to be processed
303         * @param crc     - variable the CRC sum shall be stored to
304         */
305        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306            for (int i = 0 ; i < bufSize ; i++) {
307                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308            }
309        }
310    
311        /**
312         * Returns the final CRC result.
313         *
314         * @param crc - variable previously passed to __calculateCRC()
315         */
316        inline static uint32_t __encodeCRC(const uint32_t& crc) {
317            return crc ^ 0xffffffff;
318        }
319    
320    
321    
322    // *************** Other Internal functions  ***************
323    // *
324    
325        static split_type_t __resolveSplitType(dimension_t dimension) {
326            return (
327                dimension == dimension_layer ||
328                dimension == dimension_samplechannel ||
329                dimension == dimension_releasetrigger ||
330                dimension == dimension_keyboard ||
331                dimension == dimension_roundrobin ||
332                dimension == dimension_random ||
333                dimension == dimension_smartmidi ||
334                dimension == dimension_roundrobinkeyboard
335            ) ? split_type_bit : split_type_normal;
336        }
337    
338        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
339            return (dimension_definition.split_type == split_type_normal)
340            ? int(128.0 / dimension_definition.zones) : 0;
341        }
342    
343    
344    
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
# Line 279  namespace { Line 367  namespace {
367       *                         is located, 0 otherwise       *                         is located, 0 otherwise
368       */       */
369      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) {
370          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
371                { CHUNK_ID_INAM, 64 },
372                { 0, 0 }
373            };
374            pInfo->SetFixedStringLengths(fixedStringLengths);
375          Instances++;          Instances++;
376          FileNo = fileNo;          FileNo = fileNo;
377    
378            __resetCRC(crc);
379    
380          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381          if (pCk3gix) {          if (pCk3gix) {
382              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 314  namespace { Line 408  namespace {
408              Manufacturer  = 0;              Manufacturer  = 0;
409              Product       = 0;              Product       = 0;
410              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
411              MIDIUnityNote = 64;              MIDIUnityNote = 60;
412              FineTune      = 0;              FineTune      = 0;
413                SMPTEFormat   = smpte_format_no_offset;
414              SMPTEOffset   = 0;              SMPTEOffset   = 0;
415              Loops         = 0;              Loops         = 0;
416              LoopID        = 0;              LoopID        = 0;
417                LoopType      = loop_type_normal;
418              LoopStart     = 0;              LoopStart     = 0;
419              LoopEnd       = 0;              LoopEnd       = 0;
420              LoopFraction  = 0;              LoopFraction  = 0;
# Line 358  namespace { Line 454  namespace {
454      }      }
455    
456      /**      /**
457         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518            }
519            pOrig->SetPos(restorePos);
520            delete [] buf;
521        }
522    
523        /**
524       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
525       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
526       *       *
527       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
528       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
529       *       *
530       * @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
531       *                        was provided yet       *                        was provided yet
532       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
533       */       */
# Line 374  namespace { Line 537  namespace {
537    
538          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
539          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
540          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
541                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
542                memset(pCkSmpl->LoadChunkData(), 0, 60);
543            }
544          // update 'smpl' chunk          // update 'smpl' chunk
545          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
546          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
547          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
548          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
549          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
550          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
551          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
552          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
553          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
554          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
555    
556          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
557    
558          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
559          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
560          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
561          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
562          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
563          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
564    
565          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
566          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
# Line 414  namespace { Line 580  namespace {
580          }          }
581          // update '3gix' chunk          // update '3gix' chunk
582          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
583          memcpy(&pData[0], &iSampleGroup, 2);          store16(&pData[0], iSampleGroup);
584    
585            // if the library user toggled the "Compressed" attribute from true to
586            // false, then the EWAV chunk associated with compressed samples needs
587            // to be deleted
588            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
589            if (ewav && !Compressed) {
590                pWaveList->DeleteSubChunk(ewav);
591            }
592      }      }
593    
594      /// 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 578  namespace { Line 752  namespace {
752          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
753          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
754          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
755            SetPos(0); // reset read position to begin of sample
756          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
757          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
758          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 615  namespace { Line 790  namespace {
790          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
791          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
792          RAMCache.Size   = 0;          RAMCache.Size   = 0;
793            RAMCache.NullExtensionSize = 0;
794      }      }
795    
796      /** @brief Resize sample.      /** @brief Resize sample.
# Line 635  namespace { Line 811  namespace {
811       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
812       * current sample's boundary!       * current sample's boundary!
813       *       *
814       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
815       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
816       * other formats will fail!       * other formats will fail!
817       *       *
818       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
819       *                   greater than zero)       *                   greater than zero)
820       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
821       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
822       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
823       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 707  namespace { Line 883  namespace {
883      /**      /**
884       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
885       */       */
886      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
887          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
888          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
889      }      }
# Line 809  namespace { Line 985  namespace {
985                                  }                                  }
986    
987                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
988                                  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!
989                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
990                              }                              }
991                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
992                          break;                          break;
# Line 1099  namespace { Line 1276  namespace {
1276       *       *
1277       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1278       *       *
1279         * For 16 bit samples, the data in the source buffer should be
1280         * int16_t (using native endianness). For 24 bit, the buffer
1281         * should contain three bytes per sample, little-endian.
1282         *
1283       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1284       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1285       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1107  namespace { Line 1288  namespace {
1288       */       */
1289      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1290          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)");
1291          return DLS::Sample::Write(pBuffer, SampleCount);  
1292            // if this is the first write in this sample, reset the
1293            // checksum calculator
1294            if (pCkData->GetPos() == 0) {
1295                __resetCRC(crc);
1296            }
1297            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1298            unsigned long res;
1299            if (BitDepth == 24) {
1300                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1301            } else { // 16 bit
1302                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1303                                    : pCkData->Write(pBuffer, SampleCount, 2);
1304            }
1305            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1306    
1307            // if this is the last write, update the checksum chunk in the
1308            // file
1309            if (pCkData->GetPos() == pCkData->GetSize()) {
1310                File* pFile = static_cast<File*>(GetParent());
1311                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1312            }
1313            return res;
1314      }      }
1315    
1316      /**      /**
# Line 1183  namespace { Line 1386  namespace {
1386      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1387      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1388    
1389      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1390          Instances++;          Instances++;
1391    
1392          pSample = NULL;          pSample = NULL;
1393            pRegion = pParent;
1394    
1395            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1396            else memset(&Crossfade, 0, 4);
1397    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1398          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1399    
1400          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1302  namespace { Line 1508  namespace {
1508                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1509              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1510              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1511                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1512              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1513              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1514              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1338  namespace { Line 1544  namespace {
1544                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1545                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1546              }              }
1547                if (_3ewa->RemainingBytes() >= 8) {
1548                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1549                } else {
1550                    memset(DimensionUpperLimits, 0, 8);
1551                }
1552          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1553              // use default values              // use default values
1554              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1347  namespace { Line 1558  namespace {
1558              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1559              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1560              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1561              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1562              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1563              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1564              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1565              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1566              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1364  namespace { Line 1575  namespace {
1575              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1576              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1577              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1578              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1579              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1580              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1581              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1582              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1583              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1584              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1585              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1586              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1587              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1588              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1589              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1590              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1591              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1592              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1418  namespace { Line 1629  namespace {
1629              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1630              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1631              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1632                memset(DimensionUpperLimits, 127, 8);
1633          }          }
1634    
1635          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1636                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1637                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1638    
1639          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1640          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1641                                        ReleaseVelocityResponseDepth
1642                                    );
1643    
1644            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1645                                                          VCFVelocityDynamicRange,
1646                                                          VCFVelocityScale,
1647                                                          VCFCutoffController);
1648    
1649          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1650          // velocity response curves for release time are not used even          VelocityTable = 0;
1651          // 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);  
1652    
1653          curveType = VCFVelocityCurve;      /*
1654          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1655         * another DimensionRegion
1656         */
1657        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1658            Instances++;
1659            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1660            *this = src; // default memberwise shallow copy of all parameters
1661            pParentList = _3ewl; // restore the chunk pointer
1662    
1663            // deep copy of owned structures
1664            if (src.VelocityTable) {
1665                VelocityTable = new uint8_t[128];
1666                for (int k = 0 ; k < 128 ; k++)
1667                    VelocityTable[k] = src.VelocityTable[k];
1668            }
1669            if (src.pSampleLoops) {
1670                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1671                for (int k = 0 ; k < src.SampleLoops ; k++)
1672                    pSampleLoops[k] = src.pSampleLoops[k];
1673            }
1674        }
1675        
1676        /**
1677         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1678         * and assign it to this object.
1679         *
1680         * Note that all sample pointers referenced by @a orig are simply copied as
1681         * memory address. Thus the respective samples are shared, not duplicated!
1682         *
1683         * @param orig - original DimensionRegion object to be copied from
1684         */
1685        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1686            CopyAssign(orig, NULL);
1687        }
1688    
1689          // even stranger GSt: two of the velocity response curves for      /**
1690          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1691          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1692          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1693              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1694              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1695              depth = 5;       *                   this file's samples
1696         */
1697        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1698            // delete all allocated data first
1699            if (VelocityTable) delete [] VelocityTable;
1700            if (pSampleLoops) delete [] pSampleLoops;
1701            
1702            // backup parent list pointer
1703            RIFF::List* p = pParentList;
1704            
1705            gig::Sample* pOriginalSample = pSample;
1706            gig::Region* pOriginalRegion = pRegion;
1707            
1708            //NOTE: copy code copied from assignment constructor above, see comment there as well
1709            
1710            *this = *orig; // default memberwise shallow copy of all parameters
1711            pParentList = p; // restore the chunk pointer
1712            
1713            // only take the raw sample reference & parent region reference if the
1714            // two DimensionRegion objects are part of the same file
1715            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1716                pRegion = pOriginalRegion;
1717                pSample = pOriginalSample;
1718            }
1719            
1720            if (mSamples && mSamples->count(orig->pSample)) {
1721                pSample = mSamples->find(orig->pSample)->second;
1722            }
1723    
1724            // deep copy of owned structures
1725            if (orig->VelocityTable) {
1726                VelocityTable = new uint8_t[128];
1727                for (int k = 0 ; k < 128 ; k++)
1728                    VelocityTable[k] = orig->VelocityTable[k];
1729            }
1730            if (orig->pSampleLoops) {
1731                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1732                for (int k = 0 ; k < orig->SampleLoops ; k++)
1733                    pSampleLoops[k] = orig->pSampleLoops[k];
1734          }          }
1735          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1736    
1737        /**
1738         * Updates the respective member variable and updates @c SampleAttenuation
1739         * which depends on this value.
1740         */
1741        void DimensionRegion::SetGain(int32_t gain) {
1742            DLS::Sampler::SetGain(gain);
1743          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1744      }      }
1745    
1746      /**      /**
# Line 1466  namespace { Line 1754  namespace {
1754          // first update base class's chunk          // first update base class's chunk
1755          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1756    
1757            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1758            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1759            pData[12] = Crossfade.in_start;
1760            pData[13] = Crossfade.in_end;
1761            pData[14] = Crossfade.out_start;
1762            pData[15] = Crossfade.out_end;
1763    
1764          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1765          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1766          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1767          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1768                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1769                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1770            }
1771            pData = (uint8_t*) _3ewa->LoadChunkData();
1772    
1773          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1774    
1775          const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ?          const uint32_t chunksize = _3ewa->GetNewSize();
1776          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1777    
1778          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1779          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1780    
1781          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1782          memcpy(&pData[8], &eg3attack, 4);          store32(&pData[8], eg3attack);
1783    
1784          // next 2 bytes unknown          // next 2 bytes unknown
1785    
1786          memcpy(&pData[14], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1787    
1788          // next 2 bytes unknown          // next 2 bytes unknown
1789    
1790          memcpy(&pData[18], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1791    
1792          // next 2 bytes unknown          // next 2 bytes unknown
1793    
1794          memcpy(&pData[22], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1795    
1796          // next 2 bytes unknown          // next 2 bytes unknown
1797    
1798          memcpy(&pData[26], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1799    
1800          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1801          memcpy(&pData[28], &eg1attack, 4);          store32(&pData[28], eg1attack);
1802    
1803          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1804          memcpy(&pData[32], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1805    
1806          // next 2 bytes unknown          // next 2 bytes unknown
1807    
1808          memcpy(&pData[38], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1809    
1810          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1811          memcpy(&pData[40], &eg1release, 4);          store32(&pData[40], eg1release);
1812    
1813          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1814          memcpy(&pData[44], &eg1ctl, 1);          pData[44] = eg1ctl;
1815    
1816          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1817              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1818              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1819              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1820              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1821          memcpy(&pData[45], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1822    
1823          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1824          memcpy(&pData[46], &eg2ctl, 1);          pData[46] = eg2ctl;
1825    
1826          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1827              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1828              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1829              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1830              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1831          memcpy(&pData[47], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1832    
1833          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1834          memcpy(&pData[48], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1835    
1836          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1837          memcpy(&pData[52], &eg2attack, 4);          store32(&pData[52], eg2attack);
1838    
1839          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1840          memcpy(&pData[56], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1841    
1842          // next 2 bytes unknown          // next 2 bytes unknown
1843    
1844          memcpy(&pData[62], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1845    
1846          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1847          memcpy(&pData[64], &eg2release, 4);          store32(&pData[64], eg2release);
1848    
1849          // next 2 bytes unknown          // next 2 bytes unknown
1850    
1851          memcpy(&pData[70], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1852    
1853          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1854          memcpy(&pData[72], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1855    
1856          // next 2 bytes unknown          // next 2 bytes unknown
1857    
1858          memcpy(&pData[78], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1859    
1860          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);
1861          memcpy(&pData[80], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1862    
1863          // next 2 bytes unknown          // next 2 bytes unknown
1864    
1865          memcpy(&pData[86], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1866    
1867          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);
1868          memcpy(&pData[88], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1869    
1870          // next 2 bytes unknown          // next 2 bytes unknown
1871    
1872          memcpy(&pData[94], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1873    
1874          {          {
1875              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 1588  namespace { Line 1887  namespace {
1887                  default:                  default:
1888                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1889              }              }
1890              memcpy(&pData[96], &velocityresponse, 1);              pData[96] = velocityresponse;
1891          }          }
1892    
1893          {          {
# Line 1607  namespace { Line 1906  namespace {
1906                  default:                  default:
1907                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1908              }              }
1909              memcpy(&pData[97], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1910          }          }
1911    
1912          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1913    
1914          memcpy(&pData[99], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1915    
1916          // next 4 bytes unknown          // next 4 bytes unknown
1917    
1918          memcpy(&pData[104], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1919    
1920          // next 2 bytes unknown          // next 2 bytes unknown
1921    
# Line 1635  namespace { Line 1934  namespace {
1934                  default:                  default:
1935                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1936              }              }
1937              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1938          }          }
1939    
1940          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
1941          memcpy(&pData[109], &pan, 1);          pData[109] = pan;
1942    
1943          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1944          memcpy(&pData[110], &selfmask, 1);          pData[110] = selfmask;
1945    
1946          // next byte unknown          // next byte unknown
1947    
# Line 1651  namespace { Line 1950  namespace {
1950              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1951              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1952              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1953              memcpy(&pData[112], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1954          }          }
1955    
1956          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1957          memcpy(&pData[113], &attenctl, 1);          pData[113] = attenctl;
1958    
1959          {          {
1960              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1961              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1962              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1963              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1964              memcpy(&pData[114], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1965          }          }
1966    
1967          {          {
# Line 1671  namespace { Line 1970  namespace {
1970              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1971              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1972                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1973              memcpy(&pData[115], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1974          }          }
1975    
1976          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1977                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1978          memcpy(&pData[116], &eg3depth, 1);          store16(&pData[116], eg3depth);
1979    
1980          // next 2 bytes unknown          // next 2 bytes unknown
1981    
1982          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1983          memcpy(&pData[120], &channeloffset, 1);          pData[120] = channeloffset;
1984    
1985          {          {
1986              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1987              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1988              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1989              memcpy(&pData[121], &regoptions, 1);              pData[121] = regoptions;
1990          }          }
1991    
1992          // next 2 bytes unknown          // next 2 bytes unknown
1993    
1994          memcpy(&pData[124], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1995    
1996          // next 3 bytes unknown          // next 3 bytes unknown
1997    
1998          memcpy(&pData[128], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1999    
2000          // next 2 bytes unknown          // next 2 bytes unknown
2001    
2002          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2003          memcpy(&pData[131], &eg1hold, 1);          pData[131] = eg1hold;
2004    
2005          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2006                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2007          memcpy(&pData[132], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2008    
2009          memcpy(&pData[133], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2010    
2011          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2012                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2013          memcpy(&pData[134], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2014    
2015          // next byte unknown          // next byte unknown
2016    
2017          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2018                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2019          memcpy(&pData[136], &vcfresonance, 1);          pData[136] = vcfresonance;
2020    
2021          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2022                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2023          memcpy(&pData[137], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2024    
2025          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2026                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2027          memcpy(&pData[138], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2028    
2029          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2030          memcpy(&pData[139], &vcftype, 1);          pData[139] = vcftype;
2031    
2032            if (chunksize >= 148) {
2033                memcpy(&pData[140], DimensionUpperLimits, 8);
2034            }
2035        }
2036    
2037        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2038            curve_type_t curveType = releaseVelocityResponseCurve;
2039            uint8_t depth = releaseVelocityResponseDepth;
2040            // this models a strange behaviour or bug in GSt: two of the
2041            // velocity response curves for release time are not used even
2042            // if specified, instead another curve is chosen.
2043            if ((curveType == curve_type_nonlinear && depth == 0) ||
2044                (curveType == curve_type_special   && depth == 4)) {
2045                curveType = curve_type_nonlinear;
2046                depth = 3;
2047            }
2048            return GetVelocityTable(curveType, depth, 0);
2049        }
2050    
2051        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2052                                                        uint8_t vcfVelocityDynamicRange,
2053                                                        uint8_t vcfVelocityScale,
2054                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2055        {
2056            curve_type_t curveType = vcfVelocityCurve;
2057            uint8_t depth = vcfVelocityDynamicRange;
2058            // even stranger GSt: two of the velocity response curves for
2059            // filter cutoff are not used, instead another special curve
2060            // is chosen. This curve is not used anywhere else.
2061            if ((curveType == curve_type_nonlinear && depth == 0) ||
2062                (curveType == curve_type_special   && depth == 4)) {
2063                curveType = curve_type_special;
2064                depth = 5;
2065            }
2066            return GetVelocityTable(curveType, depth,
2067                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2068                                        ? vcfVelocityScale : 0);
2069      }      }
2070    
2071      // 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 1746  namespace { Line 2083  namespace {
2083          return table;          return table;
2084      }      }
2085    
2086        Region* DimensionRegion::GetParent() const {
2087            return pRegion;
2088        }
2089    
2090    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2091    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2092    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2093    //#pragma GCC diagnostic push
2094    //#pragma GCC diagnostic error "-Wswitch"
2095    
2096      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2097          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2098          switch (EncodedController) {          switch (EncodedController) {
# Line 1857  namespace { Line 2204  namespace {
2204                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2205                  break;                  break;
2206    
2207                // format extension (these controllers are so far only supported by
2208                // LinuxSampler & gigedit) they will *NOT* work with
2209                // Gigasampler/GigaStudio !
2210                case _lev_ctrl_CC3_EXT:
2211                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2212                    decodedcontroller.controller_number = 3;
2213                    break;
2214                case _lev_ctrl_CC6_EXT:
2215                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2216                    decodedcontroller.controller_number = 6;
2217                    break;
2218                case _lev_ctrl_CC7_EXT:
2219                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2220                    decodedcontroller.controller_number = 7;
2221                    break;
2222                case _lev_ctrl_CC8_EXT:
2223                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2224                    decodedcontroller.controller_number = 8;
2225                    break;
2226                case _lev_ctrl_CC9_EXT:
2227                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2228                    decodedcontroller.controller_number = 9;
2229                    break;
2230                case _lev_ctrl_CC10_EXT:
2231                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2232                    decodedcontroller.controller_number = 10;
2233                    break;
2234                case _lev_ctrl_CC11_EXT:
2235                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2236                    decodedcontroller.controller_number = 11;
2237                    break;
2238                case _lev_ctrl_CC14_EXT:
2239                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2240                    decodedcontroller.controller_number = 14;
2241                    break;
2242                case _lev_ctrl_CC15_EXT:
2243                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2244                    decodedcontroller.controller_number = 15;
2245                    break;
2246                case _lev_ctrl_CC20_EXT:
2247                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2248                    decodedcontroller.controller_number = 20;
2249                    break;
2250                case _lev_ctrl_CC21_EXT:
2251                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2252                    decodedcontroller.controller_number = 21;
2253                    break;
2254                case _lev_ctrl_CC22_EXT:
2255                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2256                    decodedcontroller.controller_number = 22;
2257                    break;
2258                case _lev_ctrl_CC23_EXT:
2259                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2260                    decodedcontroller.controller_number = 23;
2261                    break;
2262                case _lev_ctrl_CC24_EXT:
2263                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2264                    decodedcontroller.controller_number = 24;
2265                    break;
2266                case _lev_ctrl_CC25_EXT:
2267                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2268                    decodedcontroller.controller_number = 25;
2269                    break;
2270                case _lev_ctrl_CC26_EXT:
2271                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2272                    decodedcontroller.controller_number = 26;
2273                    break;
2274                case _lev_ctrl_CC27_EXT:
2275                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2276                    decodedcontroller.controller_number = 27;
2277                    break;
2278                case _lev_ctrl_CC28_EXT:
2279                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2280                    decodedcontroller.controller_number = 28;
2281                    break;
2282                case _lev_ctrl_CC29_EXT:
2283                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2284                    decodedcontroller.controller_number = 29;
2285                    break;
2286                case _lev_ctrl_CC30_EXT:
2287                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2288                    decodedcontroller.controller_number = 30;
2289                    break;
2290                case _lev_ctrl_CC31_EXT:
2291                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2292                    decodedcontroller.controller_number = 31;
2293                    break;
2294                case _lev_ctrl_CC68_EXT:
2295                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2296                    decodedcontroller.controller_number = 68;
2297                    break;
2298                case _lev_ctrl_CC69_EXT:
2299                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2300                    decodedcontroller.controller_number = 69;
2301                    break;
2302                case _lev_ctrl_CC70_EXT:
2303                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2304                    decodedcontroller.controller_number = 70;
2305                    break;
2306                case _lev_ctrl_CC71_EXT:
2307                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2308                    decodedcontroller.controller_number = 71;
2309                    break;
2310                case _lev_ctrl_CC72_EXT:
2311                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2312                    decodedcontroller.controller_number = 72;
2313                    break;
2314                case _lev_ctrl_CC73_EXT:
2315                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2316                    decodedcontroller.controller_number = 73;
2317                    break;
2318                case _lev_ctrl_CC74_EXT:
2319                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2320                    decodedcontroller.controller_number = 74;
2321                    break;
2322                case _lev_ctrl_CC75_EXT:
2323                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2324                    decodedcontroller.controller_number = 75;
2325                    break;
2326                case _lev_ctrl_CC76_EXT:
2327                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2328                    decodedcontroller.controller_number = 76;
2329                    break;
2330                case _lev_ctrl_CC77_EXT:
2331                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2332                    decodedcontroller.controller_number = 77;
2333                    break;
2334                case _lev_ctrl_CC78_EXT:
2335                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2336                    decodedcontroller.controller_number = 78;
2337                    break;
2338                case _lev_ctrl_CC79_EXT:
2339                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2340                    decodedcontroller.controller_number = 79;
2341                    break;
2342                case _lev_ctrl_CC84_EXT:
2343                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2344                    decodedcontroller.controller_number = 84;
2345                    break;
2346                case _lev_ctrl_CC85_EXT:
2347                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2348                    decodedcontroller.controller_number = 85;
2349                    break;
2350                case _lev_ctrl_CC86_EXT:
2351                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2352                    decodedcontroller.controller_number = 86;
2353                    break;
2354                case _lev_ctrl_CC87_EXT:
2355                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2356                    decodedcontroller.controller_number = 87;
2357                    break;
2358                case _lev_ctrl_CC89_EXT:
2359                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2360                    decodedcontroller.controller_number = 89;
2361                    break;
2362                case _lev_ctrl_CC90_EXT:
2363                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2364                    decodedcontroller.controller_number = 90;
2365                    break;
2366                case _lev_ctrl_CC96_EXT:
2367                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2368                    decodedcontroller.controller_number = 96;
2369                    break;
2370                case _lev_ctrl_CC97_EXT:
2371                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2372                    decodedcontroller.controller_number = 97;
2373                    break;
2374                case _lev_ctrl_CC102_EXT:
2375                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2376                    decodedcontroller.controller_number = 102;
2377                    break;
2378                case _lev_ctrl_CC103_EXT:
2379                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2380                    decodedcontroller.controller_number = 103;
2381                    break;
2382                case _lev_ctrl_CC104_EXT:
2383                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2384                    decodedcontroller.controller_number = 104;
2385                    break;
2386                case _lev_ctrl_CC105_EXT:
2387                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2388                    decodedcontroller.controller_number = 105;
2389                    break;
2390                case _lev_ctrl_CC106_EXT:
2391                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2392                    decodedcontroller.controller_number = 106;
2393                    break;
2394                case _lev_ctrl_CC107_EXT:
2395                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2396                    decodedcontroller.controller_number = 107;
2397                    break;
2398                case _lev_ctrl_CC108_EXT:
2399                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2400                    decodedcontroller.controller_number = 108;
2401                    break;
2402                case _lev_ctrl_CC109_EXT:
2403                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2404                    decodedcontroller.controller_number = 109;
2405                    break;
2406                case _lev_ctrl_CC110_EXT:
2407                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2408                    decodedcontroller.controller_number = 110;
2409                    break;
2410                case _lev_ctrl_CC111_EXT:
2411                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2412                    decodedcontroller.controller_number = 111;
2413                    break;
2414                case _lev_ctrl_CC112_EXT:
2415                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2416                    decodedcontroller.controller_number = 112;
2417                    break;
2418                case _lev_ctrl_CC113_EXT:
2419                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2420                    decodedcontroller.controller_number = 113;
2421                    break;
2422                case _lev_ctrl_CC114_EXT:
2423                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2424                    decodedcontroller.controller_number = 114;
2425                    break;
2426                case _lev_ctrl_CC115_EXT:
2427                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2428                    decodedcontroller.controller_number = 115;
2429                    break;
2430                case _lev_ctrl_CC116_EXT:
2431                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2432                    decodedcontroller.controller_number = 116;
2433                    break;
2434                case _lev_ctrl_CC117_EXT:
2435                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2436                    decodedcontroller.controller_number = 117;
2437                    break;
2438                case _lev_ctrl_CC118_EXT:
2439                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2440                    decodedcontroller.controller_number = 118;
2441                    break;
2442                case _lev_ctrl_CC119_EXT:
2443                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2444                    decodedcontroller.controller_number = 119;
2445                    break;
2446    
2447              // unknown controller type              // unknown controller type
2448              default:              default:
2449                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2450          }          }
2451          return decodedcontroller;          return decodedcontroller;
2452      }      }
2453        
2454    // see above (diagnostic push not supported prior GCC 4.6)
2455    //#pragma GCC diagnostic pop
2456    
2457      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2458          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1950  namespace { Line 2540  namespace {
2540                      case 95:                      case 95:
2541                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2542                          break;                          break;
2543    
2544                        // format extension (these controllers are so far only
2545                        // supported by LinuxSampler & gigedit) they will *NOT*
2546                        // work with Gigasampler/GigaStudio !
2547                        case 3:
2548                            encodedcontroller = _lev_ctrl_CC3_EXT;
2549                            break;
2550                        case 6:
2551                            encodedcontroller = _lev_ctrl_CC6_EXT;
2552                            break;
2553                        case 7:
2554                            encodedcontroller = _lev_ctrl_CC7_EXT;
2555                            break;
2556                        case 8:
2557                            encodedcontroller = _lev_ctrl_CC8_EXT;
2558                            break;
2559                        case 9:
2560                            encodedcontroller = _lev_ctrl_CC9_EXT;
2561                            break;
2562                        case 10:
2563                            encodedcontroller = _lev_ctrl_CC10_EXT;
2564                            break;
2565                        case 11:
2566                            encodedcontroller = _lev_ctrl_CC11_EXT;
2567                            break;
2568                        case 14:
2569                            encodedcontroller = _lev_ctrl_CC14_EXT;
2570                            break;
2571                        case 15:
2572                            encodedcontroller = _lev_ctrl_CC15_EXT;
2573                            break;
2574                        case 20:
2575                            encodedcontroller = _lev_ctrl_CC20_EXT;
2576                            break;
2577                        case 21:
2578                            encodedcontroller = _lev_ctrl_CC21_EXT;
2579                            break;
2580                        case 22:
2581                            encodedcontroller = _lev_ctrl_CC22_EXT;
2582                            break;
2583                        case 23:
2584                            encodedcontroller = _lev_ctrl_CC23_EXT;
2585                            break;
2586                        case 24:
2587                            encodedcontroller = _lev_ctrl_CC24_EXT;
2588                            break;
2589                        case 25:
2590                            encodedcontroller = _lev_ctrl_CC25_EXT;
2591                            break;
2592                        case 26:
2593                            encodedcontroller = _lev_ctrl_CC26_EXT;
2594                            break;
2595                        case 27:
2596                            encodedcontroller = _lev_ctrl_CC27_EXT;
2597                            break;
2598                        case 28:
2599                            encodedcontroller = _lev_ctrl_CC28_EXT;
2600                            break;
2601                        case 29:
2602                            encodedcontroller = _lev_ctrl_CC29_EXT;
2603                            break;
2604                        case 30:
2605                            encodedcontroller = _lev_ctrl_CC30_EXT;
2606                            break;
2607                        case 31:
2608                            encodedcontroller = _lev_ctrl_CC31_EXT;
2609                            break;
2610                        case 68:
2611                            encodedcontroller = _lev_ctrl_CC68_EXT;
2612                            break;
2613                        case 69:
2614                            encodedcontroller = _lev_ctrl_CC69_EXT;
2615                            break;
2616                        case 70:
2617                            encodedcontroller = _lev_ctrl_CC70_EXT;
2618                            break;
2619                        case 71:
2620                            encodedcontroller = _lev_ctrl_CC71_EXT;
2621                            break;
2622                        case 72:
2623                            encodedcontroller = _lev_ctrl_CC72_EXT;
2624                            break;
2625                        case 73:
2626                            encodedcontroller = _lev_ctrl_CC73_EXT;
2627                            break;
2628                        case 74:
2629                            encodedcontroller = _lev_ctrl_CC74_EXT;
2630                            break;
2631                        case 75:
2632                            encodedcontroller = _lev_ctrl_CC75_EXT;
2633                            break;
2634                        case 76:
2635                            encodedcontroller = _lev_ctrl_CC76_EXT;
2636                            break;
2637                        case 77:
2638                            encodedcontroller = _lev_ctrl_CC77_EXT;
2639                            break;
2640                        case 78:
2641                            encodedcontroller = _lev_ctrl_CC78_EXT;
2642                            break;
2643                        case 79:
2644                            encodedcontroller = _lev_ctrl_CC79_EXT;
2645                            break;
2646                        case 84:
2647                            encodedcontroller = _lev_ctrl_CC84_EXT;
2648                            break;
2649                        case 85:
2650                            encodedcontroller = _lev_ctrl_CC85_EXT;
2651                            break;
2652                        case 86:
2653                            encodedcontroller = _lev_ctrl_CC86_EXT;
2654                            break;
2655                        case 87:
2656                            encodedcontroller = _lev_ctrl_CC87_EXT;
2657                            break;
2658                        case 89:
2659                            encodedcontroller = _lev_ctrl_CC89_EXT;
2660                            break;
2661                        case 90:
2662                            encodedcontroller = _lev_ctrl_CC90_EXT;
2663                            break;
2664                        case 96:
2665                            encodedcontroller = _lev_ctrl_CC96_EXT;
2666                            break;
2667                        case 97:
2668                            encodedcontroller = _lev_ctrl_CC97_EXT;
2669                            break;
2670                        case 102:
2671                            encodedcontroller = _lev_ctrl_CC102_EXT;
2672                            break;
2673                        case 103:
2674                            encodedcontroller = _lev_ctrl_CC103_EXT;
2675                            break;
2676                        case 104:
2677                            encodedcontroller = _lev_ctrl_CC104_EXT;
2678                            break;
2679                        case 105:
2680                            encodedcontroller = _lev_ctrl_CC105_EXT;
2681                            break;
2682                        case 106:
2683                            encodedcontroller = _lev_ctrl_CC106_EXT;
2684                            break;
2685                        case 107:
2686                            encodedcontroller = _lev_ctrl_CC107_EXT;
2687                            break;
2688                        case 108:
2689                            encodedcontroller = _lev_ctrl_CC108_EXT;
2690                            break;
2691                        case 109:
2692                            encodedcontroller = _lev_ctrl_CC109_EXT;
2693                            break;
2694                        case 110:
2695                            encodedcontroller = _lev_ctrl_CC110_EXT;
2696                            break;
2697                        case 111:
2698                            encodedcontroller = _lev_ctrl_CC111_EXT;
2699                            break;
2700                        case 112:
2701                            encodedcontroller = _lev_ctrl_CC112_EXT;
2702                            break;
2703                        case 113:
2704                            encodedcontroller = _lev_ctrl_CC113_EXT;
2705                            break;
2706                        case 114:
2707                            encodedcontroller = _lev_ctrl_CC114_EXT;
2708                            break;
2709                        case 115:
2710                            encodedcontroller = _lev_ctrl_CC115_EXT;
2711                            break;
2712                        case 116:
2713                            encodedcontroller = _lev_ctrl_CC116_EXT;
2714                            break;
2715                        case 117:
2716                            encodedcontroller = _lev_ctrl_CC117_EXT;
2717                            break;
2718                        case 118:
2719                            encodedcontroller = _lev_ctrl_CC118_EXT;
2720                            break;
2721                        case 119:
2722                            encodedcontroller = _lev_ctrl_CC119_EXT;
2723                            break;
2724    
2725                      default:                      default:
2726                          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");
2727                  }                  }
2728                    break;
2729              default:              default:
2730                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2731          }          }
# Line 1998  namespace { Line 2771  namespace {
2771          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2772      }      }
2773    
2774        /**
2775         * Updates the respective member variable and the lookup table / cache
2776         * that depends on this value.
2777         */
2778        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2779            pVelocityAttenuationTable =
2780                GetVelocityTable(
2781                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2782                );
2783            VelocityResponseCurve = curve;
2784        }
2785    
2786        /**
2787         * Updates the respective member variable and the lookup table / cache
2788         * that depends on this value.
2789         */
2790        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2791            pVelocityAttenuationTable =
2792                GetVelocityTable(
2793                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2794                );
2795            VelocityResponseDepth = depth;
2796        }
2797    
2798        /**
2799         * Updates the respective member variable and the lookup table / cache
2800         * that depends on this value.
2801         */
2802        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2803            pVelocityAttenuationTable =
2804                GetVelocityTable(
2805                    VelocityResponseCurve, VelocityResponseDepth, scaling
2806                );
2807            VelocityResponseCurveScaling = scaling;
2808        }
2809    
2810        /**
2811         * Updates the respective member variable and the lookup table / cache
2812         * that depends on this value.
2813         */
2814        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2815            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2816            ReleaseVelocityResponseCurve = curve;
2817        }
2818    
2819        /**
2820         * Updates the respective member variable and the lookup table / cache
2821         * that depends on this value.
2822         */
2823        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2824            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2825            ReleaseVelocityResponseDepth = depth;
2826        }
2827    
2828        /**
2829         * Updates the respective member variable and the lookup table / cache
2830         * that depends on this value.
2831         */
2832        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2833            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2834            VCFCutoffController = controller;
2835        }
2836    
2837        /**
2838         * Updates the respective member variable and the lookup table / cache
2839         * that depends on this value.
2840         */
2841        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2842            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2843            VCFVelocityCurve = curve;
2844        }
2845    
2846        /**
2847         * Updates the respective member variable and the lookup table / cache
2848         * that depends on this value.
2849         */
2850        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2851            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2852            VCFVelocityDynamicRange = range;
2853        }
2854    
2855        /**
2856         * Updates the respective member variable and the lookup table / cache
2857         * that depends on this value.
2858         */
2859        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2860            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2861            VCFVelocityScale = scaling;
2862        }
2863    
2864      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) {
2865    
2866          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2070  namespace { Line 2933  namespace {
2933  // *  // *
2934    
2935      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;  
   
2936          // Initialization          // Initialization
2937          Dimensions = 0;          Dimensions = 0;
2938          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2083  namespace { Line 2944  namespace {
2944    
2945          // Actual Loading          // Actual Loading
2946    
2947            if (!file->GetAutoLoad()) return;
2948    
2949          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2950    
2951          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2091  namespace { Line 2954  namespace {
2954              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2955                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2956                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2957                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2958                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2959                  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)
2960                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2961                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2105  namespace { Line 2968  namespace {
2968                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2969                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2970                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2971                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2972                                                             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;  
2973                      Dimensions++;                      Dimensions++;
2974    
2975                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2134  namespace { Line 2989  namespace {
2989              else              else
2990                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2991    
2992              // load sample references              // load sample references (if auto loading is enabled)
2993              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2994                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2995                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2996                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2997                    }
2998                    GetSample(); // load global region sample reference
2999                }
3000            } else {
3001                DimensionRegions = 0;
3002                for (int i = 0 ; i < 8 ; i++) {
3003                    pDimensionDefinitions[i].dimension  = dimension_none;
3004                    pDimensionDefinitions[i].bits       = 0;
3005                    pDimensionDefinitions[i].zones      = 0;
3006              }              }
             GetSample(); // load global region sample reference  
3007          }          }
3008    
3009          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2147  namespace { Line 3011  namespace {
3011              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3012              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3013              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3014              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3015              DimensionRegions = 1;              DimensionRegions = 1;
3016          }          }
3017      }      }
# Line 2162  namespace { Line 3026  namespace {
3026       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3027       */       */
3028      void Region::UpdateChunks() {      void Region::UpdateChunks() {
3029            // in the gig format we don't care about the Region's sample reference
3030            // but we still have to provide some existing one to not corrupt the
3031            // file, so to avoid the latter we simply always assign the sample of
3032            // the first dimension region of this region
3033            pSample = pDimensionRegions[0]->pSample;
3034    
3035          // first update base class's chunks          // first update base class's chunks
3036          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
3037    
# Line 2171  namespace { Line 3041  namespace {
3041          }          }
3042    
3043          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3044          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3045          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3046            const int iMaxDimensionRegions = version3 ? 256 : 32;
3047    
3048          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3049          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3050          if (!_3lnk) {          if (!_3lnk) {
3051              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3052              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3053                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3054    
3055                // move 3prg to last position
3056                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
3057          }          }
3058    
3059          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3060          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3061          memcpy(&pData[0], &DimensionRegions, 4);          store32(&pData[0], DimensionRegions);
3062            int shift = 0;
3063          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3064              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3065              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3066              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3067                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3068              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3069              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
3070    
3071                shift += pDimensionDefinitions[i].bits;
3072          }          }
3073    
3074          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3075          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3076          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3077              int iWaveIndex = -1;              int iWaveIndex = -1;
3078              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2206  namespace { Line 3085  namespace {
3085                          break;                          break;
3086                      }                      }
3087                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3088              }              }
3089              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3090          }          }
3091      }      }
3092    
# Line 2219  namespace { Line 3097  namespace {
3097              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3098              while (_3ewl) {              while (_3ewl) {
3099                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3100                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3101                      dimensionRegionNr++;                      dimensionRegionNr++;
3102                  }                  }
3103                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2228  namespace { Line 3106  namespace {
3106          }          }
3107      }      }
3108    
3109        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3110            // update KeyRange struct and make sure regions are in correct order
3111            DLS::Region::SetKeyRange(Low, High);
3112            // update Region key table for fast lookup
3113            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3114        }
3115    
3116      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3117          // get velocity dimension's index          // get velocity dimension's index
3118          int veldim = -1;          int veldim = -1;
# Line 2248  namespace { Line 3133  namespace {
3133          int dim[8] = { 0 };          int dim[8] = { 0 };
3134          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3135    
3136              if (pDimensionRegions[i]->VelocityUpperLimit) {              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3137                    pDimensionRegions[i]->VelocityUpperLimit) {
3138                  // create the velocity table                  // create the velocity table
3139                  uint8_t* table = pDimensionRegions[i]->VelocityTable;                  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3140                  if (!table) {                  if (!table) {
# Line 2257  namespace { Line 3143  namespace {
3143                  }                  }
3144                  int tableidx = 0;                  int tableidx = 0;
3145                  int velocityZone = 0;                  int velocityZone = 0;
3146                  for (int k = i ; k < end ; k += step) {                  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3147                      DimensionRegion *d = pDimensionRegions[k];                      for (int k = i ; k < end ; k += step) {
3148                      for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;                          DimensionRegion *d = pDimensionRegions[k];
3149                      velocityZone++;                          for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3150                            velocityZone++;
3151                        }
3152                    } else { // gig2
3153                        for (int k = i ; k < end ; k += step) {
3154                            DimensionRegion *d = pDimensionRegions[k];
3155                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3156                            velocityZone++;
3157                        }
3158                  }                  }
3159              } else {              } else {
3160                  if (pDimensionRegions[i]->VelocityTable) {                  if (pDimensionRegions[i]->VelocityTable) {
# Line 2324  namespace { Line 3218  namespace {
3218              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3219                  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");
3220    
3221            // pos is where the new dimension should be placed, normally
3222            // last in list, except for the samplechannel dimension which
3223            // has to be first in list
3224            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3225            int bitpos = 0;
3226            for (int i = 0 ; i < pos ; i++)
3227                bitpos += pDimensionDefinitions[i].bits;
3228    
3229            // make room for the new dimension
3230            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3231            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3232                for (int j = Dimensions ; j > pos ; j--) {
3233                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3234                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3235                }
3236            }
3237    
3238          // assign definition of new dimension          // assign definition of new dimension
3239          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3240    
3241          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
3242          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
3243              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
3244              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
3245              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
3246              DimensionRegions++;  
3247            // create new dimension region(s) for this new dimension, and make
3248            // sure that the dimension regions are placed correctly in both the
3249            // RIFF list and the pDimensionRegions array
3250            RIFF::Chunk* moveTo = NULL;
3251            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3252            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3253                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3254                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3255                }
3256                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3257                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3258                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3259                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3260                        // create a new dimension region and copy all parameter values from
3261                        // an existing dimension region
3262                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3263                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3264    
3265                        DimensionRegions++;
3266                    }
3267                }
3268                moveTo = pDimensionRegions[i]->pParentList;
3269            }
3270    
3271            // initialize the upper limits for this dimension
3272            int mask = (1 << bitpos) - 1;
3273            for (int z = 0 ; z < pDimDef->zones ; z++) {
3274                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3275                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3276                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3277                                      (z << bitpos) |
3278                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3279                }
3280          }          }
3281    
3282          Dimensions++;          Dimensions++;
# Line 2375  namespace { Line 3319  namespace {
3319          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3320              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3321    
3322            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3323    
3324          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3325          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3326          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2383  namespace { Line 3329  namespace {
3329                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3330                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3331                                      iLowerBit;                                      iLowerBit;
3332    
3333                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3334                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3335                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3336                      DimensionRegions--;                      DimensionRegions--;
# Line 2403  namespace { Line 3351  namespace {
3351              }              }
3352          }          }
3353    
3354            // remove the this dimension from the upper limits arrays
3355            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3356                DimensionRegion* d = pDimensionRegions[j];
3357                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3358                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3359                }
3360                d->DimensionUpperLimits[Dimensions - 1] = 127;
3361            }
3362    
3363          // 'remove' dimension definition          // 'remove' dimension definition
3364          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3365              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2455  namespace { Line 3412  namespace {
3412              } else {              } else {
3413                  switch (pDimensionDefinitions[i].split_type) {                  switch (pDimensionDefinitions[i].split_type) {
3414                      case split_type_normal:                      case split_type_normal:
3415                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3416                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3417                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3418                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3419                                }
3420                            } else {
3421                                // gig2: evenly sized zones
3422                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3423                            }
3424                          break;                          break;
3425                      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
3426                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
# Line 2469  namespace { Line 3434  namespace {
3434          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3435          if (veldim != -1) {          if (veldim != -1) {
3436              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3437              if (dimreg->VelocityUpperLimit) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3438                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim]];
3439              else // normal split type              else // normal split type
3440                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
# Line 2528  namespace { Line 3493  namespace {
3493          }          }
3494          return NULL;          return NULL;
3495      }      }
3496        
3497        /**
3498         * Make a (semi) deep copy of the Region object given by @a orig
3499         * and assign it to this object.
3500         *
3501         * Note that all sample pointers referenced by @a orig are simply copied as
3502         * memory address. Thus the respective samples are shared, not duplicated!
3503         *
3504         * @param orig - original Region object to be copied from
3505         */
3506        void Region::CopyAssign(const Region* orig) {
3507            CopyAssign(orig, NULL);
3508        }
3509        
3510        /**
3511         * Make a (semi) deep copy of the Region object given by @a orig and
3512         * assign it to this object
3513         *
3514         * @param mSamples - crosslink map between the foreign file's samples and
3515         *                   this file's samples
3516         */
3517        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3518            // handle base classes
3519            DLS::Region::CopyAssign(orig);
3520            
3521            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3522                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3523            }
3524            
3525            // handle own member variables
3526            for (int i = Dimensions - 1; i >= 0; --i) {
3527                DeleteDimension(&pDimensionDefinitions[i]);
3528            }
3529            Layers = 0; // just to be sure
3530            for (int i = 0; i < orig->Dimensions; i++) {
3531                // we need to copy the dim definition here, to avoid the compiler
3532                // complaining about const-ness issue
3533                dimension_def_t def = orig->pDimensionDefinitions[i];
3534                AddDimension(&def);
3535            }
3536            for (int i = 0; i < 256; i++) {
3537                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3538                    pDimensionRegions[i]->CopyAssign(
3539                        orig->pDimensionRegions[i],
3540                        mSamples
3541                    );
3542                }
3543            }
3544            Layers = orig->Layers;
3545        }
3546    
3547    
3548    // *************** MidiRule ***************
3549    // *
3550    
3551        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3552            _3ewg->SetPos(36);
3553            Triggers = _3ewg->ReadUint8();
3554            _3ewg->SetPos(40);
3555            ControllerNumber = _3ewg->ReadUint8();
3556            _3ewg->SetPos(46);
3557            for (int i = 0 ; i < Triggers ; i++) {
3558                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3559                pTriggers[i].Descending = _3ewg->ReadUint8();
3560                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3561                pTriggers[i].Key = _3ewg->ReadUint8();
3562                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3563                pTriggers[i].Velocity = _3ewg->ReadUint8();
3564                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3565                _3ewg->ReadUint8();
3566            }
3567        }
3568    
3569        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3570            ControllerNumber(0),
3571            Triggers(0) {
3572        }
3573    
3574        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3575            pData[32] = 4;
3576            pData[33] = 16;
3577            pData[36] = Triggers;
3578            pData[40] = ControllerNumber;
3579            for (int i = 0 ; i < Triggers ; i++) {
3580                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3581                pData[47 + i * 8] = pTriggers[i].Descending;
3582                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3583                pData[49 + i * 8] = pTriggers[i].Key;
3584                pData[50 + i * 8] = pTriggers[i].NoteOff;
3585                pData[51 + i * 8] = pTriggers[i].Velocity;
3586                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3587            }
3588        }
3589    
3590        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3591            _3ewg->SetPos(36);
3592            LegatoSamples = _3ewg->ReadUint8(); // always 12
3593            _3ewg->SetPos(40);
3594            BypassUseController = _3ewg->ReadUint8();
3595            BypassKey = _3ewg->ReadUint8();
3596            BypassController = _3ewg->ReadUint8();
3597            ThresholdTime = _3ewg->ReadUint16();
3598            _3ewg->ReadInt16();
3599            ReleaseTime = _3ewg->ReadUint16();
3600            _3ewg->ReadInt16();
3601            KeyRange.low = _3ewg->ReadUint8();
3602            KeyRange.high = _3ewg->ReadUint8();
3603            _3ewg->SetPos(64);
3604            ReleaseTriggerKey = _3ewg->ReadUint8();
3605            AltSustain1Key = _3ewg->ReadUint8();
3606            AltSustain2Key = _3ewg->ReadUint8();
3607        }
3608    
3609        MidiRuleLegato::MidiRuleLegato() :
3610            LegatoSamples(12),
3611            BypassUseController(false),
3612            BypassKey(0),
3613            BypassController(1),
3614            ThresholdTime(20),
3615            ReleaseTime(20),
3616            ReleaseTriggerKey(0),
3617            AltSustain1Key(0),
3618            AltSustain2Key(0)
3619        {
3620            KeyRange.low = KeyRange.high = 0;
3621        }
3622    
3623        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3624            pData[32] = 0;
3625            pData[33] = 16;
3626            pData[36] = LegatoSamples;
3627            pData[40] = BypassUseController;
3628            pData[41] = BypassKey;
3629            pData[42] = BypassController;
3630            store16(&pData[43], ThresholdTime);
3631            store16(&pData[47], ReleaseTime);
3632            pData[51] = KeyRange.low;
3633            pData[52] = KeyRange.high;
3634            pData[64] = ReleaseTriggerKey;
3635            pData[65] = AltSustain1Key;
3636            pData[66] = AltSustain2Key;
3637        }
3638    
3639        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3640            _3ewg->SetPos(36);
3641            Articulations = _3ewg->ReadUint8();
3642            int flags = _3ewg->ReadUint8();
3643            Polyphonic = flags & 8;
3644            Chained = flags & 4;
3645            Selector = (flags & 2) ? selector_controller :
3646                (flags & 1) ? selector_key_switch : selector_none;
3647            Patterns = _3ewg->ReadUint8();
3648            _3ewg->ReadUint8(); // chosen row
3649            _3ewg->ReadUint8(); // unknown
3650            _3ewg->ReadUint8(); // unknown
3651            _3ewg->ReadUint8(); // unknown
3652            KeySwitchRange.low = _3ewg->ReadUint8();
3653            KeySwitchRange.high = _3ewg->ReadUint8();
3654            Controller = _3ewg->ReadUint8();
3655            PlayRange.low = _3ewg->ReadUint8();
3656            PlayRange.high = _3ewg->ReadUint8();
3657    
3658            int n = std::min(int(Articulations), 32);
3659            for (int i = 0 ; i < n ; i++) {
3660                _3ewg->ReadString(pArticulations[i], 32);
3661            }
3662            _3ewg->SetPos(1072);
3663            n = std::min(int(Patterns), 32);
3664            for (int i = 0 ; i < n ; i++) {
3665                _3ewg->ReadString(pPatterns[i].Name, 16);
3666                pPatterns[i].Size = _3ewg->ReadUint8();
3667                _3ewg->Read(&pPatterns[i][0], 1, 32);
3668            }
3669        }
3670    
3671        MidiRuleAlternator::MidiRuleAlternator() :
3672            Articulations(0),
3673            Patterns(0),
3674            Selector(selector_none),
3675            Controller(0),
3676            Polyphonic(false),
3677            Chained(false)
3678        {
3679            PlayRange.low = PlayRange.high = 0;
3680            KeySwitchRange.low = KeySwitchRange.high = 0;
3681        }
3682    
3683        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3684            pData[32] = 3;
3685            pData[33] = 16;
3686            pData[36] = Articulations;
3687            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3688                (Selector == selector_controller ? 2 :
3689                 (Selector == selector_key_switch ? 1 : 0));
3690            pData[38] = Patterns;
3691    
3692            pData[43] = KeySwitchRange.low;
3693            pData[44] = KeySwitchRange.high;
3694            pData[45] = Controller;
3695            pData[46] = PlayRange.low;
3696            pData[47] = PlayRange.high;
3697    
3698            char* str = reinterpret_cast<char*>(pData);
3699            int pos = 48;
3700            int n = std::min(int(Articulations), 32);
3701            for (int i = 0 ; i < n ; i++, pos += 32) {
3702                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3703            }
3704    
3705            pos = 1072;
3706            n = std::min(int(Patterns), 32);
3707            for (int i = 0 ; i < n ; i++, pos += 49) {
3708                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3709                pData[pos + 16] = pPatterns[i].Size;
3710                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3711            }
3712        }
3713    
3714  // *************** Instrument ***************  // *************** Instrument ***************
3715  // *  // *
3716    
3717      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) {
3718          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
3719                { CHUNK_ID_INAM, 64 },
3720                { CHUNK_ID_ISFT, 12 },
3721                { 0, 0 }
3722            };
3723            pInfo->SetFixedStringLengths(fixedStringLengths);
3724    
3725          // Initialization          // Initialization
3726          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3727            EffectSend = 0;
3728            Attenuation = 0;
3729            FineTune = 0;
3730            PitchbendRange = 0;
3731            PianoReleaseMode = false;
3732            DimensionKeyRange.low = 0;
3733            DimensionKeyRange.high = 0;
3734            pMidiRules = new MidiRule*[3];
3735            pMidiRules[0] = NULL;
3736    
3737          // Loading          // Loading
3738          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2553  namespace { Line 3747  namespace {
3747                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3748                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3749                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3750    
3751                    if (_3ewg->GetSize() > 32) {
3752                        // read MIDI rules
3753                        int i = 0;
3754                        _3ewg->SetPos(32);
3755                        uint8_t id1 = _3ewg->ReadUint8();
3756                        uint8_t id2 = _3ewg->ReadUint8();
3757    
3758                        if (id2 == 16) {
3759                            if (id1 == 4) {
3760                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3761                            } else if (id1 == 0) {
3762                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3763                            } else if (id1 == 3) {
3764                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3765                            } else {
3766                                pMidiRules[i++] = new MidiRuleUnknown;
3767                            }
3768                        }
3769                        else if (id1 != 0 || id2 != 0) {
3770                            pMidiRules[i++] = new MidiRuleUnknown;
3771                        }
3772                        //TODO: all the other types of rules
3773    
3774                        pMidiRules[i] = NULL;
3775                    }
3776              }              }
3777          }          }
3778    
3779          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3780          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3781          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3782              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3783              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3784                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3785                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3786                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3787                            pRegions->push_back(new Region(this, rgn));
3788                        }
3789                        rgn = lrgn->GetNextSubList();
3790                  }                  }
3791                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3792                    UpdateRegionKeyTable();
3793              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3794          }          }
3795    
3796          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3797      }      }
3798    
3799      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3800            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3801          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3802          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3803          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2586  namespace { Line 3809  namespace {
3809      }      }
3810    
3811      Instrument::~Instrument() {      Instrument::~Instrument() {
3812            for (int i = 0 ; pMidiRules[i] ; i++) {
3813                delete pMidiRules[i];
3814            }
3815            delete[] pMidiRules;
3816      }      }
3817    
3818      /**      /**
# Line 2614  namespace { Line 3841  namespace {
3841          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3842          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3843          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3844          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3845                File* pFile = (File*) GetParent();
3846    
3847                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3848                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3849                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3850                memset(_3ewg->LoadChunkData(), 0, size);
3851            }
3852          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3853          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3854          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
3855          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
3856          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
3857          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
3858          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3859                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3860          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
3861          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
3862    
3863            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3864                pData[32] = 0;
3865                pData[33] = 0;
3866            } else {
3867                for (int i = 0 ; pMidiRules[i] ; i++) {
3868                    pMidiRules[i]->UpdateChunks(pData);
3869                }
3870            }
3871      }      }
3872    
3873      /**      /**
# Line 2635  namespace { Line 3878  namespace {
3878       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3879       */       */
3880      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3881          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3882          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3883    
3884          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2693  namespace { Line 3936  namespace {
3936          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3937      }      }
3938    
3939        /**
3940         * Returns a MIDI rule of the instrument.
3941         *
3942         * The list of MIDI rules, at least in gig v3, always contains at
3943         * most two rules. The second rule can only be the DEF filter
3944         * (which currently isn't supported by libgig).
3945         *
3946         * @param i - MIDI rule number
3947         * @returns   pointer address to MIDI rule number i or NULL if there is none
3948         */
3949        MidiRule* Instrument::GetMidiRule(int i) {
3950            return pMidiRules[i];
3951        }
3952    
3953        /**
3954         * Adds the "controller trigger" MIDI rule to the instrument.
3955         *
3956         * @returns the new MIDI rule
3957         */
3958        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3959            delete pMidiRules[0];
3960            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3961            pMidiRules[0] = r;
3962            pMidiRules[1] = 0;
3963            return r;
3964        }
3965    
3966        /**
3967         * Adds the legato MIDI rule to the instrument.
3968         *
3969         * @returns the new MIDI rule
3970         */
3971        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3972            delete pMidiRules[0];
3973            MidiRuleLegato* r = new MidiRuleLegato;
3974            pMidiRules[0] = r;
3975            pMidiRules[1] = 0;
3976            return r;
3977        }
3978    
3979        /**
3980         * Adds the alternator MIDI rule to the instrument.
3981         *
3982         * @returns the new MIDI rule
3983         */
3984        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3985            delete pMidiRules[0];
3986            MidiRuleAlternator* r = new MidiRuleAlternator;
3987            pMidiRules[0] = r;
3988            pMidiRules[1] = 0;
3989            return r;
3990        }
3991    
3992        /**
3993         * Deletes a MIDI rule from the instrument.
3994         *
3995         * @param i - MIDI rule number
3996         */
3997        void Instrument::DeleteMidiRule(int i) {
3998            delete pMidiRules[i];
3999            pMidiRules[i] = 0;
4000        }
4001    
4002        /**
4003         * Make a (semi) deep copy of the Instrument object given by @a orig
4004         * and assign it to this object.
4005         *
4006         * Note that all sample pointers referenced by @a orig are simply copied as
4007         * memory address. Thus the respective samples are shared, not duplicated!
4008         *
4009         * @param orig - original Instrument object to be copied from
4010         */
4011        void Instrument::CopyAssign(const Instrument* orig) {
4012            CopyAssign(orig, NULL);
4013        }
4014            
4015        /**
4016         * Make a (semi) deep copy of the Instrument object given by @a orig
4017         * and assign it to this object.
4018         *
4019         * @param orig - original Instrument object to be copied from
4020         * @param mSamples - crosslink map between the foreign file's samples and
4021         *                   this file's samples
4022         */
4023        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4024            // handle base class
4025            // (without copying DLS region stuff)
4026            DLS::Instrument::CopyAssignCore(orig);
4027            
4028            // handle own member variables
4029            Attenuation = orig->Attenuation;
4030            EffectSend = orig->EffectSend;
4031            FineTune = orig->FineTune;
4032            PitchbendRange = orig->PitchbendRange;
4033            PianoReleaseMode = orig->PianoReleaseMode;
4034            DimensionKeyRange = orig->DimensionKeyRange;
4035            
4036            // free old midi rules
4037            for (int i = 0 ; pMidiRules[i] ; i++) {
4038                delete pMidiRules[i];
4039            }
4040            //TODO: MIDI rule copying
4041            pMidiRules[0] = NULL;
4042            
4043            // delete all old regions
4044            while (Regions) DeleteRegion(GetFirstRegion());
4045            // create new regions and copy them from original
4046            {
4047                RegionList::const_iterator it = orig->pRegions->begin();
4048                for (int i = 0; i < orig->Regions; ++i, ++it) {
4049                    Region* dstRgn = AddRegion();
4050                    //NOTE: Region does semi-deep copy !
4051                    dstRgn->CopyAssign(
4052                        static_cast<gig::Region*>(*it),
4053                        mSamples
4054                    );
4055                }
4056            }
4057    
4058            UpdateRegionKeyTable();
4059        }
4060    
4061    
4062  // *************** Group ***************  // *************** Group ***************
# Line 2711  namespace { Line 4075  namespace {
4075      }      }
4076    
4077      Group::~Group() {      Group::~Group() {
4078            // remove the chunk associated with this group (if any)
4079            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4080      }      }
4081    
4082      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
4083       *       *
4084       * Apply current Group field values to the respective. You have to call       * Apply current Group field values to the respective chunks. You have
4085       * File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
4086         *
4087         * Usually there is absolutely no need to call this method explicitly.
4088         * It will be called automatically when File::Save() was called.
4089       */       */
4090      void Group::UpdateChunks() {      void Group::UpdateChunks() {
4091          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
4092          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
4093          if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);          if (!_3gri) {
4094                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
4095                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4096            }
4097          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4098          if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4099    
4100            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
4101                // v3 has a fixed list of 128 strings, find a free one
4102                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
4103                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
4104                        pNameChunk = ck;
4105                        break;
4106                    }
4107                }
4108            }
4109    
4110          // 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
4111          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
4112      }      }
# Line 2799  namespace { Line 4182  namespace {
4182  // *************** File ***************  // *************** File ***************
4183  // *  // *
4184    
4185        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
4186        const DLS::version_t File::VERSION_2 = {
4187            0, 2, 19980628 & 0xffff, 19980628 >> 16
4188        };
4189    
4190        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
4191        const DLS::version_t File::VERSION_3 = {
4192            0, 3, 20030331 & 0xffff, 20030331 >> 16
4193        };
4194    
4195        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
4196            { CHUNK_ID_IARL, 256 },
4197            { CHUNK_ID_IART, 128 },
4198            { CHUNK_ID_ICMS, 128 },
4199            { CHUNK_ID_ICMT, 1024 },
4200            { CHUNK_ID_ICOP, 128 },
4201            { CHUNK_ID_ICRD, 128 },
4202            { CHUNK_ID_IENG, 128 },
4203            { CHUNK_ID_IGNR, 128 },
4204            { CHUNK_ID_IKEY, 128 },
4205            { CHUNK_ID_IMED, 128 },
4206            { CHUNK_ID_INAM, 128 },
4207            { CHUNK_ID_IPRD, 128 },
4208            { CHUNK_ID_ISBJ, 128 },
4209            { CHUNK_ID_ISFT, 128 },
4210            { CHUNK_ID_ISRC, 128 },
4211            { CHUNK_ID_ISRF, 128 },
4212            { CHUNK_ID_ITCH, 128 },
4213            { 0, 0 }
4214        };
4215    
4216      File::File() : DLS::File() {      File::File() : DLS::File() {
4217            bAutoLoad = true;
4218            *pVersion = VERSION_3;
4219          pGroups = NULL;          pGroups = NULL;
4220          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4221            pInfo->ArchivalLocation = String(256, ' ');
4222    
4223            // add some mandatory chunks to get the file chunks in right
4224            // order (INFO chunk will be moved to first position later)
4225            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
4226            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
4227            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
4228    
4229            GenerateDLSID();
4230      }      }
4231    
4232      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
4233            bAutoLoad = true;
4234          pGroups = NULL;          pGroups = NULL;
4235          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4236      }      }
4237    
4238      File::~File() {      File::~File() {
# Line 2833  namespace { Line 4259  namespace {
4259          SamplesIterator++;          SamplesIterator++;
4260          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
4261      }      }
4262        
4263        /**
4264         * Returns Sample object of @a index.
4265         *
4266         * @returns sample object or NULL if index is out of bounds
4267         */
4268        Sample* File::GetSample(uint index) {
4269            if (!pSamples) LoadSamples();
4270            if (!pSamples) return NULL;
4271            DLS::File::SampleList::iterator it = pSamples->begin();
4272            for (int i = 0; i < index; ++i) {
4273                ++it;
4274                if (it == pSamples->end()) return NULL;
4275            }
4276            if (it == pSamples->end()) return NULL;
4277            return static_cast<gig::Sample*>( *it );
4278        }
4279    
4280      /** @brief Add a new sample.      /** @brief Add a new sample.
4281       *       *
# Line 2848  namespace { Line 4291  namespace {
4291         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
4292         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
4293         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*/);
4294    
4295           // add mandatory chunks to get the chunks in right order
4296           wave->AddSubChunk(CHUNK_ID_FMT, 16);
4297           wave->AddSubList(LIST_TYPE_INFO);
4298    
4299         pSamples->push_back(pSample);         pSamples->push_back(pSample);
4300         return pSample;         return pSample;
4301      }      }
4302    
4303      /** @brief Delete a sample.      /** @brief Delete a sample.
4304       *       *
4305       * 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
4306       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
4307         * removed. You have to call Save() to make this persistent to the file.
4308       *       *
4309       * @param pSample - sample to delete       * @param pSample - sample to delete
4310       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2864  namespace { Line 4313  namespace {
4313          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");
4314          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
4315          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");
4316            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
4317          pSamples->erase(iter);          pSamples->erase(iter);
4318          delete pSample;          delete pSample;
4319    
4320            SampleList::iterator tmp = SamplesIterator;
4321            // remove all references to the sample
4322            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4323                 instrument = GetNextInstrument()) {
4324                for (Region* region = instrument->GetFirstRegion() ; region ;
4325                     region = instrument->GetNextRegion()) {
4326    
4327                    if (region->GetSample() == pSample) region->SetSample(NULL);
4328    
4329                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
4330                        gig::DimensionRegion *d = region->pDimensionRegions[i];
4331                        if (d->pSample == pSample) d->pSample = NULL;
4332                    }
4333                }
4334            }
4335            SamplesIterator = tmp; // restore iterator
4336      }      }
4337    
4338      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2875  namespace { Line 4342  namespace {
4342      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
4343          // Groups must be loaded before samples, because samples will try          // Groups must be loaded before samples, because samples will try
4344          // to resolve the group they belong to          // to resolve the group they belong to
4345          LoadGroups();          if (!pGroups) LoadGroups();
4346    
4347          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
4348    
# Line 2956  namespace { Line 4423  namespace {
4423              progress_t subprogress;              progress_t subprogress;
4424              __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
4425              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
4426              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
4427                    GetFirstSample(&subprogress); // now force all samples to be loaded
4428              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
4429    
4430              // instrument loading subtask              // instrument loading subtask
# Line 2989  namespace { Line 4457  namespace {
4457         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
4458         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4459         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4460    
4461           // add mandatory chunks to get the chunks in right order
4462           lstInstr->AddSubList(LIST_TYPE_INFO);
4463           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4464    
4465         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
4466           pInstrument->GenerateDLSID();
4467    
4468           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4469    
4470           // this string is needed for the gig to be loadable in GSt:
4471           pInstrument->pInfo->Software = "Endless Wave";
4472    
4473         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4474         return pInstrument;         return pInstrument;
4475      }      }
4476        
4477        /** @brief Add a duplicate of an existing instrument.
4478         *
4479         * Duplicates the instrument definition given by @a orig and adds it
4480         * to this file. This allows in an instrument editor application to
4481         * easily create variations of an instrument, which will be stored in
4482         * the same .gig file, sharing i.e. the same samples.
4483         *
4484         * Note that all sample pointers referenced by @a orig are simply copied as
4485         * memory address. Thus the respective samples are shared, not duplicated!
4486         *
4487         * You have to call Save() to make this persistent to the file.
4488         *
4489         * @param orig - original instrument to be copied
4490         * @returns duplicated copy of the given instrument
4491         */
4492        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4493            Instrument* instr = AddInstrument();
4494            instr->CopyAssign(orig);
4495            return instr;
4496        }
4497        
4498        /** @brief Add content of another existing file.
4499         *
4500         * Duplicates the samples, groups and instruments of the original file
4501         * given by @a pFile and adds them to @c this File. In case @c this File is
4502         * a new one that you haven't saved before, then you have to call
4503         * SetFileName() before calling AddContentOf(), because this method will
4504         * automatically save this file during operation, which is required for
4505         * writing the sample waveform data by disk streaming.
4506         *
4507         * @param pFile - original file whose's content shall be copied from
4508         */
4509        void File::AddContentOf(File* pFile) {
4510            static int iCallCount = -1;
4511            iCallCount++;
4512            std::map<Group*,Group*> mGroups;
4513            std::map<Sample*,Sample*> mSamples;
4514            
4515            // clone sample groups
4516            for (int i = 0; pFile->GetGroup(i); ++i) {
4517                Group* g = AddGroup();
4518                g->Name =
4519                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4520                mGroups[pFile->GetGroup(i)] = g;
4521            }
4522            
4523            // clone samples (not waveform data here yet)
4524            for (int i = 0; pFile->GetSample(i); ++i) {
4525                Sample* s = AddSample();
4526                s->CopyAssignMeta(pFile->GetSample(i));
4527                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4528                mSamples[pFile->GetSample(i)] = s;
4529            }
4530            
4531            //BUG: For some reason this method only works with this additional
4532            //     Save() call in between here.
4533            //
4534            // Important: The correct one of the 2 Save() methods has to be called
4535            // here, depending on whether the file is completely new or has been
4536            // saved to disk already, otherwise it will result in data corruption.
4537            if (pRIFF->IsNew())
4538                Save(GetFileName());
4539            else
4540                Save();
4541            
4542            // clone instruments
4543            // (passing the crosslink table here for the cloned samples)
4544            for (int i = 0; pFile->GetInstrument(i); ++i) {
4545                Instrument* instr = AddInstrument();
4546                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4547            }
4548            
4549            // Mandatory: file needs to be saved to disk at this point, so this
4550            // file has the correct size and data layout for writing the samples'
4551            // waveform data to disk.
4552            Save();
4553            
4554            // clone samples' waveform data
4555            // (using direct read & write disk streaming)
4556            for (int i = 0; pFile->GetSample(i); ++i) {
4557                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4558            }
4559        }
4560    
4561      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4562       *       *
# Line 3000  namespace { Line 4564  namespace {
4564       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
4565       *       *
4566       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
4567       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
4568       */       */
4569      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
4570          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 3040  namespace { Line 4604  namespace {
4604          }          }
4605      }      }
4606    
4607        /// Updates the 3crc chunk with the checksum of a sample. The
4608        /// update is done directly to disk, as this method is called
4609        /// after File::Save()
4610        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4611            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4612            if (!_3crc) return;
4613    
4614            // get the index of the sample
4615            int iWaveIndex = -1;
4616            File::SampleList::iterator iter = pSamples->begin();
4617            File::SampleList::iterator end  = pSamples->end();
4618            for (int index = 0; iter != end; ++iter, ++index) {
4619                if (*iter == pSample) {
4620                    iWaveIndex = index;
4621                    break;
4622                }
4623            }
4624            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4625    
4626            // write the CRC-32 checksum to disk
4627            _3crc->SetPos(iWaveIndex * 8);
4628            uint32_t tmp = 1;
4629            _3crc->WriteUint32(&tmp); // unknown, always 1?
4630            _3crc->WriteUint32(&crc);
4631        }
4632    
4633      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
4634          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
4635          // there must always be at least one group          // there must always be at least one group
# Line 3078  namespace { Line 4668  namespace {
4668          return pGroup;          return pGroup;
4669      }      }
4670    
4671        /** @brief Delete a group and its samples.
4672         *
4673         * This will delete the given Group object and all the samples that
4674         * belong to this group from the gig file. You have to call Save() to
4675         * make this persistent to the file.
4676         *
4677         * @param pGroup - group to delete
4678         * @throws gig::Exception if given group could not be found
4679         */
4680      void File::DeleteGroup(Group* pGroup) {      void File::DeleteGroup(Group* pGroup) {
4681          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
4682          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4683          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");
4684          if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");          if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4685            // delete all members of this group
4686            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
4687                DeleteSample(pSample);
4688            }
4689            // now delete this group object
4690            pGroups->erase(iter);
4691            delete pGroup;
4692        }
4693    
4694        /** @brief Delete a group.
4695         *
4696         * This will delete the given Group object from the gig file. All the
4697         * samples that belong to this group will not be deleted, but instead
4698         * be moved to another group. You have to call Save() to make this
4699         * persistent to the file.
4700         *
4701         * @param pGroup - group to delete
4702         * @throws gig::Exception if given group could not be found
4703         */
4704        void File::DeleteGroupOnly(Group* pGroup) {
4705            if (!pGroups) LoadGroups();
4706            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
4707            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
4708            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
4709          // move all members of this group to another group          // move all members of this group to another group
4710          pGroup->MoveAll();          pGroup->MoveAll();
4711          pGroups->erase(iter);          pGroups->erase(iter);
# Line 3099  namespace { Line 4722  namespace {
4722                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4723                  while (ck) {                  while (ck) {
4724                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4725                            if (pVersion && pVersion->major == 3 &&
4726                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4727    
4728                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
4729                      }                      }
4730                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3113  namespace { Line 4739  namespace {
4739          }          }
4740      }      }
4741    
4742        /**
4743         * Apply all the gig file's current instruments, samples, groups and settings
4744         * to the respective RIFF chunks. You have to call Save() to make changes
4745         * persistent.
4746         *
4747         * Usually there is absolutely no need to call this method explicitly.
4748         * It will be called automatically when File::Save() was called.
4749         *
4750         * @throws Exception - on errors
4751         */
4752        void File::UpdateChunks() {
4753            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4754    
4755            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4756    
4757            // first update base class's chunks
4758            DLS::File::UpdateChunks();
4759    
4760            if (newFile) {
4761                // INFO was added by Resource::UpdateChunks - make sure it
4762                // is placed first in file
4763                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4764                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4765                if (first != info) {
4766                    pRIFF->MoveSubChunk(info, first);
4767                }
4768            }
4769    
4770            // update group's chunks
4771            if (pGroups) {
4772                // make sure '3gri' and '3gnl' list chunks exist
4773                // (before updating the Group chunks)
4774                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4775                if (!_3gri) {
4776                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4777                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4778                }
4779                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4780                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4781    
4782                // v3: make sure the file has 128 3gnm chunks
4783                // (before updating the Group chunks)
4784                if (pVersion && pVersion->major == 3) {
4785                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4786                    for (int i = 0 ; i < 128 ; i++) {
4787                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4788                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4789                    }
4790                }
4791    
4792                std::list<Group*>::iterator iter = pGroups->begin();
4793                std::list<Group*>::iterator end  = pGroups->end();
4794                for (; iter != end; ++iter) {
4795                    (*iter)->UpdateChunks();
4796                }
4797            }
4798    
4799            // update einf chunk
4800    
4801            // The einf chunk contains statistics about the gig file, such
4802            // as the number of regions and samples used by each
4803            // instrument. It is divided in equally sized parts, where the
4804            // first part contains information about the whole gig file,
4805            // and the rest of the parts map to each instrument in the
4806            // file.
4807            //
4808            // At the end of each part there is a bit map of each sample
4809            // in the file, where a set bit means that the sample is used
4810            // by the file/instrument.
4811            //
4812            // Note that there are several fields with unknown use. These
4813            // are set to zero.
4814    
4815            int sublen = pSamples->size() / 8 + 49;
4816            int einfSize = (Instruments + 1) * sublen;
4817    
4818            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4819            if (einf) {
4820                if (einf->GetSize() != einfSize) {
4821                    einf->Resize(einfSize);
4822                    memset(einf->LoadChunkData(), 0, einfSize);
4823                }
4824            } else if (newFile) {
4825                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4826            }
4827            if (einf) {
4828                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4829    
4830                std::map<gig::Sample*,int> sampleMap;
4831                int sampleIdx = 0;
4832                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4833                    sampleMap[pSample] = sampleIdx++;
4834                }
4835    
4836                int totnbusedsamples = 0;
4837                int totnbusedchannels = 0;
4838                int totnbregions = 0;
4839                int totnbdimregions = 0;
4840                int totnbloops = 0;
4841                int instrumentIdx = 0;
4842    
4843                memset(&pData[48], 0, sublen - 48);
4844    
4845                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4846                     instrument = GetNextInstrument()) {
4847                    int nbusedsamples = 0;
4848                    int nbusedchannels = 0;
4849                    int nbdimregions = 0;
4850                    int nbloops = 0;
4851    
4852                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4853    
4854                    for (Region* region = instrument->GetFirstRegion() ; region ;
4855                         region = instrument->GetNextRegion()) {
4856                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
4857                            gig::DimensionRegion *d = region->pDimensionRegions[i];
4858                            if (d->pSample) {
4859                                int sampleIdx = sampleMap[d->pSample];
4860                                int byte = 48 + sampleIdx / 8;
4861                                int bit = 1 << (sampleIdx & 7);
4862                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4863                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4864                                    nbusedsamples++;
4865                                    nbusedchannels += d->pSample->Channels;
4866    
4867                                    if ((pData[byte] & bit) == 0) {
4868                                        pData[byte] |= bit;
4869                                        totnbusedsamples++;
4870                                        totnbusedchannels += d->pSample->Channels;
4871                                    }
4872                                }
4873                            }
4874                            if (d->SampleLoops) nbloops++;
4875                        }
4876                        nbdimregions += region->DimensionRegions;
4877                    }
4878                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4879                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4880                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4881                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4882                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4883                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4884                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4885                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4886                    // next 8 bytes unknown
4887                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4888                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4889                    // next 4 bytes unknown
4890    
4891                    totnbregions += instrument->Regions;
4892                    totnbdimregions += nbdimregions;
4893                    totnbloops += nbloops;
4894                    instrumentIdx++;
4895                }
4896                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4897                // store32(&pData[0], sublen);
4898                store32(&pData[4], totnbusedchannels);
4899                store32(&pData[8], totnbusedsamples);
4900                store32(&pData[12], Instruments);
4901                store32(&pData[16], totnbregions);
4902                store32(&pData[20], totnbdimregions);
4903                store32(&pData[24], totnbloops);
4904                // next 8 bytes unknown
4905                // next 4 bytes unknown, not always 0
4906                store32(&pData[40], pSamples->size());
4907                // next 4 bytes unknown
4908            }
4909    
4910            // update 3crc chunk
4911    
4912            // The 3crc chunk contains CRC-32 checksums for the
4913            // samples. The actual checksum values will be filled in
4914            // later, by Sample::Write.
4915    
4916            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4917            if (_3crc) {
4918                _3crc->Resize(pSamples->size() * 8);
4919            } else if (newFile) {
4920                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4921                _3crc->LoadChunkData();
4922    
4923                // the order of einf and 3crc is not the same in v2 and v3
4924                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4925            }
4926        }
4927    
4928        /**
4929         * Enable / disable automatic loading. By default this properyt is
4930         * enabled and all informations are loaded automatically. However
4931         * loading all Regions, DimensionRegions and especially samples might
4932         * take a long time for large .gig files, and sometimes one might only
4933         * be interested in retrieving very superficial informations like the
4934         * amount of instruments and their names. In this case one might disable
4935         * automatic loading to avoid very slow response times.
4936         *
4937         * @e CAUTION: by disabling this property many pointers (i.e. sample
4938         * references) and informations will have invalid or even undefined
4939         * data! This feature is currently only intended for retrieving very
4940         * superficial informations in a very fast way. Don't use it to retrieve
4941         * details like synthesis informations or even to modify .gig files!
4942         */
4943        void File::SetAutoLoad(bool b) {
4944            bAutoLoad = b;
4945        }
4946    
4947        /**
4948         * Returns whether automatic loading is enabled.
4949         * @see SetAutoLoad()
4950         */
4951        bool File::GetAutoLoad() {
4952            return bAutoLoad;
4953        }
4954    
4955    
4956    
4957  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.930  
changed lines
  Added in v.2540

  ViewVC Help
Powered by ViewVC