/[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 780 by schoenebeck, Sun Sep 25 13:40:37 2005 UTC revision 2555 by schoenebeck, Fri May 16 23:08:42 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-2005 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 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26    #include "helper.h"
27    
28    #include <algorithm>
29    #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// Initial size of the sample buffer which is used for decompression of
34    /// compressed sample wave streams - this value should always be bigger than
35    /// the biggest sample piece expected to be read by the sampler engine,
36    /// otherwise the buffer size will be raised at runtime and thus the buffer
37    /// reallocated which is time consuming and unefficient.
38    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
39    
40    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
41    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
42    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
43    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
44    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
45    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
46    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
47    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
48    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
49    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
50    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
51    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
52    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
53    
54  namespace gig {  namespace gig {
55    
# Line 59  namespace gig { Line 85  namespace gig {
85      }      }
86    
87    
88  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decompression ***************
89  // *  // *
90    
91  namespace {  namespace {
# Line 87  namespace { Line 113  namespace {
113          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
114      }      }
115    
116        inline void store24(unsigned char* pDst, int x)
117        {
118            pDst[0] = x;
119            pDst[1] = x >> 8;
120            pDst[2] = x >> 16;
121        }
122    
123      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
124                        int srcStep, int dstStep,                        int srcStep, int dstStep,
125                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
# Line 126  namespace { Line 159  namespace {
159      }      }
160    
161      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
162                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
163                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
164                        unsigned long copysamples, int truncatedBits)                        unsigned long copysamples, int truncatedBits)
165      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
166          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
167    
168  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
169          y    = get24(params);                   \          y    = get24(params);                   \
# Line 149  namespace { Line 179  namespace {
179    
180  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
181          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
182          *pDst = y >> shift;                     \          store24(pDst, y << truncatedBits);      \
183          pDst += dstStep          pDst += dstStep
184    
185          switch (compressionmode) {          switch (compressionmode) {
186              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
187                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
188                  while (copysamples) {                  while (copysamples) {
189                      *pDst = get24(pSrc) >> shift;                      store24(pDst, get24(pSrc) << truncatedBits);
190                      pDst += dstStep;                      pDst += dstStep;
191                      pSrc += 3;                      pSrc += 3;
192                      copysamples--;                      copysamples--;
# Line 226  namespace { Line 256  namespace {
256  }  }
257    
258    
259    
260    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
261    // *
262    
263        static uint32_t* __initCRCTable() {
264            static uint32_t res[256];
265    
266            for (int i = 0 ; i < 256 ; i++) {
267                uint32_t c = i;
268                for (int j = 0 ; j < 8 ; j++) {
269                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
270                }
271                res[i] = c;
272            }
273            return res;
274        }
275    
276        static const uint32_t* __CRCTable = __initCRCTable();
277    
278        /**
279         * Initialize a CRC variable.
280         *
281         * @param crc - variable to be initialized
282         */
283        inline static void __resetCRC(uint32_t& crc) {
284            crc = 0xffffffff;
285        }
286    
287        /**
288         * Used to calculate checksums of the sample data in a gig file. The
289         * checksums are stored in the 3crc chunk of the gig file and
290         * automatically updated when a sample is written with Sample::Write().
291         *
292         * One should call __resetCRC() to initialize the CRC variable to be
293         * used before calling this function the first time.
294         *
295         * After initializing the CRC variable one can call this function
296         * arbitrary times, i.e. to split the overall CRC calculation into
297         * steps.
298         *
299         * Once the whole data was processed by __calculateCRC(), one should
300         * call __encodeCRC() to get the final CRC result.
301         *
302         * @param buf     - pointer to data the CRC shall be calculated of
303         * @param bufSize - size of the data to be processed
304         * @param crc     - variable the CRC sum shall be stored to
305         */
306        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
307            for (int i = 0 ; i < bufSize ; i++) {
308                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
309            }
310        }
311    
312        /**
313         * Returns the final CRC result.
314         *
315         * @param crc - variable previously passed to __calculateCRC()
316         */
317        inline static uint32_t __encodeCRC(const uint32_t& crc) {
318            return crc ^ 0xffffffff;
319        }
320    
321    
322    
323    // *************** Other Internal functions  ***************
324    // *
325    
326        static split_type_t __resolveSplitType(dimension_t dimension) {
327            return (
328                dimension == dimension_layer ||
329                dimension == dimension_samplechannel ||
330                dimension == dimension_releasetrigger ||
331                dimension == dimension_keyboard ||
332                dimension == dimension_roundrobin ||
333                dimension == dimension_random ||
334                dimension == dimension_smartmidi ||
335                dimension == dimension_roundrobinkeyboard
336            ) ? split_type_bit : split_type_normal;
337        }
338    
339        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
340            return (dimension_definition.split_type == split_type_normal)
341            ? int(128.0 / dimension_definition.zones) : 0;
342        }
343    
344    
345    
346  // *************** Sample ***************  // *************** Sample ***************
347  // *  // *
348    
349      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
350      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
351    
352        /** @brief Constructor.
353         *
354         * Load an existing sample or create a new one. A 'wave' list chunk must
355         * be given to this constructor. In case the given 'wave' list chunk
356         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
357         * format and sample data will be loaded from there, otherwise default
358         * values will be used and those chunks will be created when
359         * File::Save() will be called later on.
360         *
361         * @param pFile          - pointer to gig::File where this sample is
362         *                         located (or will be located)
363         * @param waveList       - pointer to 'wave' list chunk which is (or
364         *                         will be) associated with this sample
365         * @param WavePoolOffset - offset of this sample data from wave pool
366         *                         ('wvpl') list chunk
367         * @param fileNo         - number of an extension file where this sample
368         *                         is located, 0 otherwise
369         */
370      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
371            static const DLS::Info::string_length_t fixedStringLengths[] = {
372                { CHUNK_ID_INAM, 64 },
373                { 0, 0 }
374            };
375            pInfo->SetFixedStringLengths(fixedStringLengths);
376          Instances++;          Instances++;
377          FileNo = fileNo;          FileNo = fileNo;
378    
379          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          __resetCRC(crc);
380          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");  
381          SampleGroup = _3gix->ReadInt16();          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
382            if (pCk3gix) {
383          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              uint16_t iSampleGroup = pCk3gix->ReadInt16();
384          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              pGroup = pFile->GetGroup(iSampleGroup);
385          Manufacturer      = smpl->ReadInt32();          } else { // '3gix' chunk missing
386          Product           = smpl->ReadInt32();              // by default assigned to that mandatory "Default Group"
387          SamplePeriod      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
388          MIDIUnityNote     = smpl->ReadInt32();          }
389          FineTune          = smpl->ReadInt32();  
390          smpl->Read(&SMPTEFormat, 1, 4);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
391          SMPTEOffset       = smpl->ReadInt32();          if (pCkSmpl) {
392          Loops             = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
393          smpl->ReadInt32(); // manufByt              Product       = pCkSmpl->ReadInt32();
394          LoopID            = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
395          smpl->Read(&LoopType, 1, 4);              MIDIUnityNote = pCkSmpl->ReadInt32();
396          LoopStart         = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
397          LoopEnd           = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
398          LoopFraction      = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
399          LoopPlayCount     = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
400                pCkSmpl->ReadInt32(); // manufByt
401                LoopID        = pCkSmpl->ReadInt32();
402                pCkSmpl->Read(&LoopType, 1, 4);
403                LoopStart     = pCkSmpl->ReadInt32();
404                LoopEnd       = pCkSmpl->ReadInt32();
405                LoopFraction  = pCkSmpl->ReadInt32();
406                LoopPlayCount = pCkSmpl->ReadInt32();
407            } else { // 'smpl' chunk missing
408                // use default values
409                Manufacturer  = 0;
410                Product       = 0;
411                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
412                MIDIUnityNote = 60;
413                FineTune      = 0;
414                SMPTEFormat   = smpte_format_no_offset;
415                SMPTEOffset   = 0;
416                Loops         = 0;
417                LoopID        = 0;
418                LoopType      = loop_type_normal;
419                LoopStart     = 0;
420                LoopEnd       = 0;
421                LoopFraction  = 0;
422                LoopPlayCount = 0;
423            }
424    
425          FrameTable                 = NULL;          FrameTable                 = NULL;
426          SamplePos                  = 0;          SamplePos                  = 0;
# Line 287  namespace { Line 451  namespace {
451          }          }
452          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
453    
454          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
455        }
456    
457        /**
458         * Make a (semi) deep copy of the Sample object given by @a orig (without
459         * the actual waveform data) and assign it to this object.
460         *
461         * Discussion: copying .gig samples is a bit tricky. It requires three
462         * steps:
463         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
464         *    its new sample waveform data size.
465         * 2. Saving the file (done by File::Save()) so that it gains correct size
466         *    and layout for writing the actual wave form data directly to disc
467         *    in next step.
468         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
469         *
470         * @param orig - original Sample object to be copied from
471         */
472        void Sample::CopyAssignMeta(const Sample* orig) {
473            // handle base classes
474            DLS::Sample::CopyAssignCore(orig);
475            
476            // handle actual own attributes of this class
477            Manufacturer = orig->Manufacturer;
478            Product = orig->Product;
479            SamplePeriod = orig->SamplePeriod;
480            MIDIUnityNote = orig->MIDIUnityNote;
481            FineTune = orig->FineTune;
482            SMPTEFormat = orig->SMPTEFormat;
483            SMPTEOffset = orig->SMPTEOffset;
484            Loops = orig->Loops;
485            LoopID = orig->LoopID;
486            LoopType = orig->LoopType;
487            LoopStart = orig->LoopStart;
488            LoopEnd = orig->LoopEnd;
489            LoopSize = orig->LoopSize;
490            LoopFraction = orig->LoopFraction;
491            LoopPlayCount = orig->LoopPlayCount;
492            
493            // schedule resizing this sample to the given sample's size
494            Resize(orig->GetSize());
495        }
496    
497        /**
498         * Should be called after CopyAssignMeta() and File::Save() sequence.
499         * Read more about it in the discussion of CopyAssignMeta(). This method
500         * copies the actual waveform data by disk streaming.
501         *
502         * @e CAUTION: this method is currently not thread safe! During this
503         * operation the sample must not be used for other purposes by other
504         * threads!
505         *
506         * @param orig - original Sample object to be copied from
507         */
508        void Sample::CopyAssignWave(const Sample* orig) {
509            const int iReadAtOnce = 32*1024;
510            char* buf = new char[iReadAtOnce * orig->FrameSize];
511            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
512            unsigned long restorePos = pOrig->GetPos();
513            pOrig->SetPos(0);
514            SetPos(0);
515            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
516                               n = pOrig->Read(buf, iReadAtOnce))
517            {
518                Write(buf, n);
519            }
520            pOrig->SetPos(restorePos);
521            delete [] buf;
522        }
523    
524        /**
525         * Apply sample and its settings to the respective RIFF chunks. You have
526         * to call File::Save() to make changes persistent.
527         *
528         * Usually there is absolutely no need to call this method explicitly.
529         * It will be called automatically when File::Save() was called.
530         *
531         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
532         *                        was provided yet
533         * @throws gig::Exception if there is any invalid sample setting
534         */
535        void Sample::UpdateChunks() {
536            // first update base class's chunks
537            DLS::Sample::UpdateChunks();
538    
539            // make sure 'smpl' chunk exists
540            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
541            if (!pCkSmpl) {
542                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
543                memset(pCkSmpl->LoadChunkData(), 0, 60);
544            }
545            // update 'smpl' chunk
546            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
547            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
548            store32(&pData[0], Manufacturer);
549            store32(&pData[4], Product);
550            store32(&pData[8], SamplePeriod);
551            store32(&pData[12], MIDIUnityNote);
552            store32(&pData[16], FineTune);
553            store32(&pData[20], SMPTEFormat);
554            store32(&pData[24], SMPTEOffset);
555            store32(&pData[28], Loops);
556    
557            // we skip 'manufByt' for now (4 bytes)
558    
559            store32(&pData[36], LoopID);
560            store32(&pData[40], LoopType);
561            store32(&pData[44], LoopStart);
562            store32(&pData[48], LoopEnd);
563            store32(&pData[52], LoopFraction);
564            store32(&pData[56], LoopPlayCount);
565    
566            // make sure '3gix' chunk exists
567            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
568            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
569            // determine appropriate sample group index (to be stored in chunk)
570            uint16_t iSampleGroup = 0; // 0 refers to default sample group
571            File* pFile = static_cast<File*>(pParent);
572            if (pFile->pGroups) {
573                std::list<Group*>::iterator iter = pFile->pGroups->begin();
574                std::list<Group*>::iterator end  = pFile->pGroups->end();
575                for (int i = 0; iter != end; i++, iter++) {
576                    if (*iter == pGroup) {
577                        iSampleGroup = i;
578                        break; // found
579                    }
580                }
581            }
582            // update '3gix' chunk
583            pData = (uint8_t*) pCk3gix->LoadChunkData();
584            store16(&pData[0], iSampleGroup);
585    
586            // if the library user toggled the "Compressed" attribute from true to
587            // false, then the EWAV chunk associated with compressed samples needs
588            // to be deleted
589            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
590            if (ewav && !Compressed) {
591                pWaveList->DeleteSubChunk(ewav);
592            }
593      }      }
594    
595      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 451  namespace { Line 753  namespace {
753          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
754          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
755          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
756            SetPos(0); // reset read position to begin of sample
757          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
758          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
759          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 488  namespace { Line 791  namespace {
791          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
792          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
793          RAMCache.Size   = 0;          RAMCache.Size   = 0;
794            RAMCache.NullExtensionSize = 0;
795        }
796    
797        /** @brief Resize sample.
798         *
799         * Resizes the sample's wave form data, that is the actual size of
800         * sample wave data possible to be written for this sample. This call
801         * will return immediately and just schedule the resize operation. You
802         * should call File::Save() to actually perform the resize operation(s)
803         * "physically" to the file. As this can take a while on large files, it
804         * is recommended to call Resize() first on all samples which have to be
805         * resized and finally to call File::Save() to perform all those resize
806         * operations in one rush.
807         *
808         * The actual size (in bytes) is dependant to the current FrameSize
809         * value. You may want to set FrameSize before calling Resize().
810         *
811         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
812         * enlarged samples before calling File::Save() as this might exceed the
813         * current sample's boundary!
814         *
815         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
816         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
817         * other formats will fail!
818         *
819         * @param iNewSize - new sample wave data size in sample points (must be
820         *                   greater than zero)
821         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
822         *                         or if \a iNewSize is less than 1
823         * @throws gig::Exception if existing sample is compressed
824         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
825         *      DLS::Sample::FormatTag, File::Save()
826         */
827        void Sample::Resize(int iNewSize) {
828            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
829            DLS::Sample::Resize(iNewSize);
830      }      }
831    
832      /**      /**
# Line 545  namespace { Line 884  namespace {
884      /**      /**
885       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
886       */       */
887      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
888          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
889          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
890      }      }
# Line 579  namespace { Line 918  namespace {
918       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
919       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
920       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
921         * @param pDimRgn          dimension region with looping information
922       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
923       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
924       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
925       */       */
926      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
927                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
928          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
929          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
930    
931          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
932    
933          if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined          if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
934    
935              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
936                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
937    
938                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
939                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
940    
941                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
942                              // determine the end position within the loop first,                          do {
943                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
944                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
945                              // backward playback  
946                                if (!pPlaybackState->reverse) { // forward playback
947                              unsigned long swapareastart       = totalreadsamples;                                  do {
948                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
949                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
950                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
951                                        totalreadsamples += readsamples;
952                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
953                                            pPlaybackState->reverse = true;
954                              // read samples for backward playback                                          break;
955                              do {                                      }
956                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
957                                  samplestoreadinloop -= readsamples;                              }
958                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
959    
960                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
961                                    // determine the end position within the loop first,
962                                    // read forward from that 'end' and finally after
963                                    // reading, swap all sample frames so it reflects
964                                    // backward playback
965    
966                                    unsigned long swapareastart       = totalreadsamples;
967                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
968                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
969                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
970    
971                                    SetPos(reverseplaybackend);
972    
973                                    // read samples for backward playback
974                                    do {
975                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
976                                        samplestoreadinloop -= readsamples;
977                                        samplestoread       -= readsamples;
978                                        totalreadsamples    += readsamples;
979                                    } while (samplestoreadinloop && readsamples);
980    
981                                    SetPos(reverseplaybackend); // pretend we really read backwards
982    
983                                    if (reverseplaybackend == loop.LoopStart) {
984                                        pPlaybackState->loop_cycles_left--;
985                                        pPlaybackState->reverse = false;
986                                    }
987    
988                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
989                                  pPlaybackState->loop_cycles_left--;                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
990                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
991                              }                              }
992                            } while (samplestoread && readsamples);
993                            break;
994                        }
995    
996                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
997                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
998                          }                          if (!pPlaybackState->reverse) do {
999                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
1000                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1001                  }                              samplestoread    -= readsamples;
1002                                totalreadsamples += readsamples;
1003                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
1004                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
1005                      if (!pPlaybackState->reverse) do {                                  break;
1006                          samplestoloopend  = this->LoopEnd - GetPos();                              }
1007                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
1008    
1009                      if (!samplestoread) break;                          if (!samplestoread) break;
1010    
1011                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
1012                      // determine the end position within the loop first,                          // determine the end position within the loop first,
1013                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
1014                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1015                      // backward playback                          // backward playback
1016    
1017                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
1018                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
1019                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1020                                                                                : samplestoread;                                                                                    : samplestoread;
1021                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1022    
1023                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1024    
1025                      // read samples for backward playback                          // read samples for backward playback
1026                      do {                          do {
1027                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1028                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1029                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
1030                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1031                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1032                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1033                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1034                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1035                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1036                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1037                          }                              }
1038                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1039    
1040                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1041    
1042                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1043                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1044                      break;                          break;
1045                  }                      }
1046    
1047                  default: case loop_type_normal: {                      default: case loop_type_normal: {
1048                      do {                          do {
1049                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1050                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1051                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
1052                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1053                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1054                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1055                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1056                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1057                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1058                          }                              }
1059                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1060                      break;                          break;
1061                        }
1062                  }                  }
1063              }              }
1064          }          }
# Line 741  namespace { Line 1088  namespace {
1088       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
1089       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
1090       *       *
1091         * For 16 bit samples, the data in the buffer will be int16_t
1092         * (using native endianness). For 24 bit, the buffer will
1093         * contain three bytes per sample, little-endian.
1094         *
1095       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1096       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1097       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 751  namespace { Line 1102  namespace {
1102          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1103          if (!Compressed) {          if (!Compressed) {
1104              if (BitDepth == 24) {              if (BitDepth == 24) {
1105                  // 24 bit sample. For now just truncate to 16 bit.                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
                 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);  
                 int16_t* pDst = static_cast<int16_t*>(pBuffer);  
                 if (Channels == 2) { // Stereo  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;  
                 }  
                 else { // Mono  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return pDst - static_cast<int16_t*>(pBuffer);  
                 }  
1106              }              }
1107              else { // 16 bit              else { // 16 bit
1108                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 801  namespace { Line 1132  namespace {
1132    
1133              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1134              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1135                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1136              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1137    
1138              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 882  namespace { Line 1214  namespace {
1214                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1215                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1216    
1217                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1218                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1219                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1220                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1221                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1222                          }                          }
1223                          else { // Mono                          else { // Mono
1224                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1225                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1226                              pDst += copysamples;                              pDst24 += copysamples * 3;
1227                          }                          }
1228                      }                      }
1229                      else { // 16 bit                      else { // 16 bit
# Line 933  namespace { Line 1265  namespace {
1265          }          }
1266      }      }
1267    
1268        /** @brief Write sample wave data.
1269         *
1270         * Writes \a SampleCount number of sample points from the buffer pointed
1271         * by \a pBuffer and increments the position within the sample. Use this
1272         * method to directly write the sample data to disk, i.e. if you don't
1273         * want or cannot load the whole sample data into RAM.
1274         *
1275         * You have to Resize() the sample to the desired size and call
1276         * File::Save() <b>before</b> using Write().
1277         *
1278         * Note: there is currently no support for writing compressed samples.
1279         *
1280         * For 16 bit samples, the data in the source buffer should be
1281         * int16_t (using native endianness). For 24 bit, the buffer
1282         * should contain three bytes per sample, little-endian.
1283         *
1284         * @param pBuffer     - source buffer
1285         * @param SampleCount - number of sample points to write
1286         * @throws DLS::Exception if current sample size is too small
1287         * @throws gig::Exception if sample is compressed
1288         * @see DLS::LoadSampleData()
1289         */
1290        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1291            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1292    
1293            // if this is the first write in this sample, reset the
1294            // checksum calculator
1295            if (pCkData->GetPos() == 0) {
1296                __resetCRC(crc);
1297            }
1298            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1299            unsigned long res;
1300            if (BitDepth == 24) {
1301                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1302            } else { // 16 bit
1303                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1304                                    : pCkData->Write(pBuffer, SampleCount, 2);
1305            }
1306            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1307    
1308            // if this is the last write, update the checksum chunk in the
1309            // file
1310            if (pCkData->GetPos() == pCkData->GetSize()) {
1311                File* pFile = static_cast<File*>(GetParent());
1312                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1313            }
1314            return res;
1315        }
1316    
1317      /**      /**
1318       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1319       * with Sample::Read(). If you are using more than one streaming thread       * with Sample::Read(). If you are using more than one streaming thread
# Line 975  namespace { Line 1356  namespace {
1356          }          }
1357      }      }
1358    
1359        /**
1360         * Returns pointer to the Group this Sample belongs to. In the .gig
1361         * format a sample always belongs to one group. If it wasn't explicitly
1362         * assigned to a certain group, it will be automatically assigned to a
1363         * default group.
1364         *
1365         * @returns Sample's Group (never NULL)
1366         */
1367        Group* Sample::GetGroup() const {
1368            return pGroup;
1369        }
1370    
1371      Sample::~Sample() {      Sample::~Sample() {
1372          Instances--;          Instances--;
1373          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 994  namespace { Line 1387  namespace {
1387      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1388      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1389    
1390      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1391          Instances++;          Instances++;
1392    
1393          memcpy(&Crossfade, &SamplerOptions, 4);          pSample = NULL;
1394            pRegion = pParent;
1395    
1396            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1397            else memset(&Crossfade, 0, 4);
1398    
1399          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1400    
1401          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1402          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1403          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1404          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1405          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1406          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1407          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1408          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1409          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1410          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1411          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1412          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1413          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1414          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1415          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1416          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1417          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1418          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1419          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1420          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1421          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1422          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1423          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1424          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1425          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1426          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1427          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1428          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1429          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1430          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1431          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1432          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1433          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1434          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1435          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1436          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1437          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1438          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1439          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1440          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1441          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1442          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1443          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1444          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1445          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1446          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1447          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1448          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1449          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1450          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1451          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1452          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1453              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1454              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1455          }                  VelocityResponseDepth = velocityresponse;
1456          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1457              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1458              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1459          }              } else if (velocityresponse < 15) {
1460          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1461              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1462              VelocityResponseDepth = velocityresponse - 10;              } else {
1463                    VelocityResponseCurve = curve_type_unknown;
1464                    VelocityResponseDepth = 0;
1465                }
1466                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1467                if (releasevelocityresponse < 5) {
1468                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1469                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1470                } else if (releasevelocityresponse < 10) {
1471                    ReleaseVelocityResponseCurve = curve_type_linear;
1472                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1473                } else if (releasevelocityresponse < 15) {
1474                    ReleaseVelocityResponseCurve = curve_type_special;
1475                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1476                } else {
1477                    ReleaseVelocityResponseCurve = curve_type_unknown;
1478                    ReleaseVelocityResponseDepth = 0;
1479                }
1480                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1481                AttenuationControllerThreshold = _3ewa->ReadInt8();
1482                _3ewa->ReadInt32(); // unknown
1483                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1484                _3ewa->ReadInt16(); // unknown
1485                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1486                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1487                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1488                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1489                else                                       DimensionBypass = dim_bypass_ctrl_none;
1490                uint8_t pan = _3ewa->ReadUint8();
1491                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1492                SelfMask = _3ewa->ReadInt8() & 0x01;
1493                _3ewa->ReadInt8(); // unknown
1494                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1495                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1496                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1497                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1498                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1499                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1500                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1501                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1502                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1503                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1504                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1505                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1506                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1507                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1508                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1509                                                            : vcf_res_ctrl_none;
1510                uint16_t eg3depth = _3ewa->ReadUint16();
1511                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1512                                            : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1513                _3ewa->ReadInt16(); // unknown
1514                ChannelOffset = _3ewa->ReadUint8() / 4;
1515                uint8_t regoptions = _3ewa->ReadUint8();
1516                MSDecode           = regoptions & 0x01; // bit 0
1517                SustainDefeat      = regoptions & 0x02; // bit 1
1518                _3ewa->ReadInt16(); // unknown
1519                VelocityUpperLimit = _3ewa->ReadInt8();
1520                _3ewa->ReadInt8(); // unknown
1521                _3ewa->ReadInt16(); // unknown
1522                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1523                _3ewa->ReadInt8(); // unknown
1524                _3ewa->ReadInt8(); // unknown
1525                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1526                uint8_t vcfcutoff = _3ewa->ReadUint8();
1527                VCFEnabled = vcfcutoff & 0x80; // bit 7
1528                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1529                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1530                uint8_t vcfvelscale = _3ewa->ReadUint8();
1531                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1532                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1533                _3ewa->ReadInt8(); // unknown
1534                uint8_t vcfresonance = _3ewa->ReadUint8();
1535                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1536                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1537                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1538                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1539                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1540                uint8_t vcfvelocity = _3ewa->ReadUint8();
1541                VCFVelocityDynamicRange = vcfvelocity % 5;
1542                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1543                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1544                if (VCFType == vcf_type_lowpass) {
1545                    if (lfo3ctrl & 0x40) // bit 6
1546                        VCFType = vcf_type_lowpassturbo;
1547                }
1548                if (_3ewa->RemainingBytes() >= 8) {
1549                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1550                } else {
1551                    memset(DimensionUpperLimits, 0, 8);
1552                }
1553            } else { // '3ewa' chunk does not exist yet
1554                // use default values
1555                LFO3Frequency                   = 1.0;
1556                EG3Attack                       = 0.0;
1557                LFO1InternalDepth               = 0;
1558                LFO3InternalDepth               = 0;
1559                LFO1ControlDepth                = 0;
1560                LFO3ControlDepth                = 0;
1561                EG1Attack                       = 0.0;
1562                EG1Decay1                       = 0.005;
1563                EG1Sustain                      = 1000;
1564                EG1Release                      = 0.3;
1565                EG1Controller.type              = eg1_ctrl_t::type_none;
1566                EG1Controller.controller_number = 0;
1567                EG1ControllerInvert             = false;
1568                EG1ControllerAttackInfluence    = 0;
1569                EG1ControllerDecayInfluence     = 0;
1570                EG1ControllerReleaseInfluence   = 0;
1571                EG2Controller.type              = eg2_ctrl_t::type_none;
1572                EG2Controller.controller_number = 0;
1573                EG2ControllerInvert             = false;
1574                EG2ControllerAttackInfluence    = 0;
1575                EG2ControllerDecayInfluence     = 0;
1576                EG2ControllerReleaseInfluence   = 0;
1577                LFO1Frequency                   = 1.0;
1578                EG2Attack                       = 0.0;
1579                EG2Decay1                       = 0.005;
1580                EG2Sustain                      = 1000;
1581                EG2Release                      = 0.3;
1582                LFO2ControlDepth                = 0;
1583                LFO2Frequency                   = 1.0;
1584                LFO2InternalDepth               = 0;
1585                EG1Decay2                       = 0.0;
1586                EG1InfiniteSustain              = true;
1587                EG1PreAttack                    = 0;
1588                EG2Decay2                       = 0.0;
1589                EG2InfiniteSustain              = true;
1590                EG2PreAttack                    = 0;
1591                VelocityResponseCurve           = curve_type_nonlinear;
1592                VelocityResponseDepth           = 3;
1593                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1594                ReleaseVelocityResponseDepth    = 3;
1595                VelocityResponseCurveScaling    = 32;
1596                AttenuationControllerThreshold  = 0;
1597                SampleStartOffset               = 0;
1598                PitchTrack                      = true;
1599                DimensionBypass                 = dim_bypass_ctrl_none;
1600                Pan                             = 0;
1601                SelfMask                        = true;
1602                LFO3Controller                  = lfo3_ctrl_modwheel;
1603                LFO3Sync                        = false;
1604                InvertAttenuationController     = false;
1605                AttenuationController.type      = attenuation_ctrl_t::type_none;
1606                AttenuationController.controller_number = 0;
1607                LFO2Controller                  = lfo2_ctrl_internal;
1608                LFO2FlipPhase                   = false;
1609                LFO2Sync                        = false;
1610                LFO1Controller                  = lfo1_ctrl_internal;
1611                LFO1FlipPhase                   = false;
1612                LFO1Sync                        = false;
1613                VCFResonanceController          = vcf_res_ctrl_none;
1614                EG3Depth                        = 0;
1615                ChannelOffset                   = 0;
1616                MSDecode                        = false;
1617                SustainDefeat                   = false;
1618                VelocityUpperLimit              = 0;
1619                ReleaseTriggerDecay             = 0;
1620                EG1Hold                         = false;
1621                VCFEnabled                      = false;
1622                VCFCutoff                       = 0;
1623                VCFCutoffController             = vcf_cutoff_ctrl_none;
1624                VCFCutoffControllerInvert       = false;
1625                VCFVelocityScale                = 0;
1626                VCFResonance                    = 0;
1627                VCFResonanceDynamic             = false;
1628                VCFKeyboardTracking             = false;
1629                VCFKeyboardTrackingBreakpoint   = 0;
1630                VCFVelocityDynamicRange         = 0x04;
1631                VCFVelocityCurve                = curve_type_linear;
1632                VCFType                         = vcf_type_lowpass;
1633                memset(DimensionUpperLimits, 127, 8);
1634          }          }
1635          else {  
1636              VelocityResponseCurve = curve_type_unknown;          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1637              VelocityResponseDepth = 0;                                                       VelocityResponseDepth,
1638                                                         VelocityResponseCurveScaling);
1639    
1640            pVelocityReleaseTable = GetReleaseVelocityTable(
1641                                        ReleaseVelocityResponseCurve,
1642                                        ReleaseVelocityResponseDepth
1643                                    );
1644    
1645            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1646                                                          VCFVelocityDynamicRange,
1647                                                          VCFVelocityScale,
1648                                                          VCFCutoffController);
1649    
1650            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1651            VelocityTable = 0;
1652        }
1653    
1654        /*
1655         * Constructs a DimensionRegion by copying all parameters from
1656         * another DimensionRegion
1657         */
1658        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1659            Instances++;
1660            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1661            *this = src; // default memberwise shallow copy of all parameters
1662            pParentList = _3ewl; // restore the chunk pointer
1663    
1664            // deep copy of owned structures
1665            if (src.VelocityTable) {
1666                VelocityTable = new uint8_t[128];
1667                for (int k = 0 ; k < 128 ; k++)
1668                    VelocityTable[k] = src.VelocityTable[k];
1669            }
1670            if (src.pSampleLoops) {
1671                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1672                for (int k = 0 ; k < src.SampleLoops ; k++)
1673                    pSampleLoops[k] = src.pSampleLoops[k];
1674          }          }
1675          uint8_t releasevelocityresponse = _3ewa->ReadUint8();      }
1676          if (releasevelocityresponse < 5) {      
1677              ReleaseVelocityResponseCurve = curve_type_nonlinear;      /**
1678              ReleaseVelocityResponseDepth = releasevelocityresponse;       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1679          }       * and assign it to this object.
1680          else if (releasevelocityresponse < 10) {       *
1681              ReleaseVelocityResponseCurve = curve_type_linear;       * Note that all sample pointers referenced by @a orig are simply copied as
1682              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;       * memory address. Thus the respective samples are shared, not duplicated!
1683          }       *
1684          else if (releasevelocityresponse < 15) {       * @param orig - original DimensionRegion object to be copied from
1685              ReleaseVelocityResponseCurve = curve_type_special;       */
1686              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;      void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1687            CopyAssign(orig, NULL);
1688        }
1689    
1690        /**
1691         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1692         * and assign it to this object.
1693         *
1694         * @param orig - original DimensionRegion object to be copied from
1695         * @param mSamples - crosslink map between the foreign file's samples and
1696         *                   this file's samples
1697         */
1698        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1699            // delete all allocated data first
1700            if (VelocityTable) delete [] VelocityTable;
1701            if (pSampleLoops) delete [] pSampleLoops;
1702            
1703            // backup parent list pointer
1704            RIFF::List* p = pParentList;
1705            
1706            gig::Sample* pOriginalSample = pSample;
1707            gig::Region* pOriginalRegion = pRegion;
1708            
1709            //NOTE: copy code copied from assignment constructor above, see comment there as well
1710            
1711            *this = *orig; // default memberwise shallow copy of all parameters
1712            
1713            // restore members that shall not be altered
1714            pParentList = p; // restore the chunk pointer
1715            pRegion = pOriginalRegion;
1716            
1717            // only take the raw sample reference reference if the
1718            // two DimensionRegion objects are part of the same file
1719            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1720                pSample = pOriginalSample;
1721            }
1722            
1723            if (mSamples && mSamples->count(orig->pSample)) {
1724                pSample = mSamples->find(orig->pSample)->second;
1725            }
1726    
1727            // deep copy of owned structures
1728            if (orig->VelocityTable) {
1729                VelocityTable = new uint8_t[128];
1730                for (int k = 0 ; k < 128 ; k++)
1731                    VelocityTable[k] = orig->VelocityTable[k];
1732            }
1733            if (orig->pSampleLoops) {
1734                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1735                for (int k = 0 ; k < orig->SampleLoops ; k++)
1736                    pSampleLoops[k] = orig->pSampleLoops[k];
1737          }          }
1738          else {      }
1739              ReleaseVelocityResponseCurve = curve_type_unknown;  
1740              ReleaseVelocityResponseDepth = 0;      /**
1741         * Updates the respective member variable and updates @c SampleAttenuation
1742         * which depends on this value.
1743         */
1744        void DimensionRegion::SetGain(int32_t gain) {
1745            DLS::Sampler::SetGain(gain);
1746            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1747        }
1748    
1749        /**
1750         * Apply dimension region settings to the respective RIFF chunks. You
1751         * have to call File::Save() to make changes persistent.
1752         *
1753         * Usually there is absolutely no need to call this method explicitly.
1754         * It will be called automatically when File::Save() was called.
1755         */
1756        void DimensionRegion::UpdateChunks() {
1757            // first update base class's chunk
1758            DLS::Sampler::UpdateChunks();
1759    
1760            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1761            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1762            pData[12] = Crossfade.in_start;
1763            pData[13] = Crossfade.in_end;
1764            pData[14] = Crossfade.out_start;
1765            pData[15] = Crossfade.out_end;
1766    
1767            // make sure '3ewa' chunk exists
1768            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1769            if (!_3ewa) {
1770                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1771                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1772                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1773          }          }
1774          VelocityResponseCurveScaling = _3ewa->ReadUint8();          pData = (uint8_t*) _3ewa->LoadChunkData();
1775          AttenuationControllerThreshold = _3ewa->ReadInt8();  
1776          _3ewa->ReadInt32(); // unknown          // update '3ewa' chunk with DimensionRegion's current settings
1777          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1778          _3ewa->ReadInt16(); // unknown          const uint32_t chunksize = _3ewa->GetNewSize();
1779          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          store32(&pData[0], chunksize); // unknown, always chunk size?
1780          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1781          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1782          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          store32(&pData[4], lfo3freq);
1783          else                                       DimensionBypass = dim_bypass_ctrl_none;  
1784          uint8_t pan = _3ewa->ReadUint8();          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1785          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit          store32(&pData[8], eg3attack);
1786          SelfMask = _3ewa->ReadInt8() & 0x01;  
1787          _3ewa->ReadInt8(); // unknown          // next 2 bytes unknown
1788          uint8_t lfo3ctrl = _3ewa->ReadUint8();  
1789          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          store16(&pData[14], LFO1InternalDepth);
1790          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
1791          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          // next 2 bytes unknown
1792          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
1793          uint8_t lfo2ctrl       = _3ewa->ReadUint8();          store16(&pData[18], LFO3InternalDepth);
1794          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
1795          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7          // next 2 bytes unknown
1796          LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
1797          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6          store16(&pData[22], LFO1ControlDepth);
1798          uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
1799          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits          // next 2 bytes unknown
1800          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
1801          LFO1Sync               = lfo1ctrl & 0x40; // bit 6          store16(&pData[26], LFO3ControlDepth);
1802          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
1803                                                      : vcf_res_ctrl_none;          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1804          uint16_t eg3depth = _3ewa->ReadUint16();          store32(&pData[28], eg1attack);
1805          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
1806                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1807          _3ewa->ReadInt16(); // unknown          store32(&pData[32], eg1decay1);
1808          ChannelOffset = _3ewa->ReadUint8() / 4;  
1809          uint8_t regoptions = _3ewa->ReadUint8();          // next 2 bytes unknown
1810          MSDecode           = regoptions & 0x01; // bit 0  
1811          SustainDefeat      = regoptions & 0x02; // bit 1          store16(&pData[38], EG1Sustain);
1812          _3ewa->ReadInt16(); // unknown  
1813          VelocityUpperLimit = _3ewa->ReadInt8();          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1814          _3ewa->ReadInt8(); // unknown          store32(&pData[40], eg1release);
1815          _3ewa->ReadInt16(); // unknown  
1816          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1817          _3ewa->ReadInt8(); // unknown          pData[44] = eg1ctl;
1818          _3ewa->ReadInt8(); // unknown  
1819          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7          const uint8_t eg1ctrloptions =
1820          uint8_t vcfcutoff = _3ewa->ReadUint8();              (EG1ControllerInvert ? 0x01 : 0x00) |
1821          VCFEnabled = vcfcutoff & 0x80; // bit 7              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1822          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1823          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1824          uint8_t vcfvelscale = _3ewa->ReadUint8();          pData[45] = eg1ctrloptions;
1825          VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7  
1826          VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1827          _3ewa->ReadInt8(); // unknown          pData[46] = eg2ctl;
1828          uint8_t vcfresonance = _3ewa->ReadUint8();  
1829          VCFResonance = vcfresonance & 0x7f; // lower 7 bits          const uint8_t eg2ctrloptions =
1830          VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7              (EG2ControllerInvert ? 0x01 : 0x00) |
1831          uint8_t vcfbreakpoint         = _3ewa->ReadUint8();              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1832          VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1833          VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1834          uint8_t vcfvelocity = _3ewa->ReadUint8();          pData[47] = eg2ctrloptions;
1835          VCFVelocityDynamicRange = vcfvelocity % 5;  
1836          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1837          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());          store32(&pData[48], lfo1freq);
1838          if (VCFType == vcf_type_lowpass) {  
1839              if (lfo3ctrl & 0x40) // bit 6          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1840                  VCFType = vcf_type_lowpassturbo;          store32(&pData[52], eg2attack);
1841    
1842            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1843            store32(&pData[56], eg2decay1);
1844    
1845            // next 2 bytes unknown
1846    
1847            store16(&pData[62], EG2Sustain);
1848    
1849            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1850            store32(&pData[64], eg2release);
1851    
1852            // next 2 bytes unknown
1853    
1854            store16(&pData[70], LFO2ControlDepth);
1855    
1856            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1857            store32(&pData[72], lfo2freq);
1858    
1859            // next 2 bytes unknown
1860    
1861            store16(&pData[78], LFO2InternalDepth);
1862    
1863            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1864            store32(&pData[80], eg1decay2);
1865    
1866            // next 2 bytes unknown
1867    
1868            store16(&pData[86], EG1PreAttack);
1869    
1870            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1871            store32(&pData[88], eg2decay2);
1872    
1873            // next 2 bytes unknown
1874    
1875            store16(&pData[94], EG2PreAttack);
1876    
1877            {
1878                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1879                uint8_t velocityresponse = VelocityResponseDepth;
1880                switch (VelocityResponseCurve) {
1881                    case curve_type_nonlinear:
1882                        break;
1883                    case curve_type_linear:
1884                        velocityresponse += 5;
1885                        break;
1886                    case curve_type_special:
1887                        velocityresponse += 10;
1888                        break;
1889                    case curve_type_unknown:
1890                    default:
1891                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1892                }
1893                pData[96] = velocityresponse;
1894          }          }
1895    
1896          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          {
1897                                                       VelocityResponseDepth,              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1898                                                       VelocityResponseCurveScaling);              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1899                switch (ReleaseVelocityResponseCurve) {
1900                    case curve_type_nonlinear:
1901                        break;
1902                    case curve_type_linear:
1903                        releasevelocityresponse += 5;
1904                        break;
1905                    case curve_type_special:
1906                        releasevelocityresponse += 10;
1907                        break;
1908                    case curve_type_unknown:
1909                    default:
1910                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1911                }
1912                pData[97] = releasevelocityresponse;
1913            }
1914    
1915            pData[98] = VelocityResponseCurveScaling;
1916    
1917            pData[99] = AttenuationControllerThreshold;
1918    
1919            // next 4 bytes unknown
1920    
1921            store16(&pData[104], SampleStartOffset);
1922    
1923            // next 2 bytes unknown
1924    
1925            {
1926                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1927                switch (DimensionBypass) {
1928                    case dim_bypass_ctrl_94:
1929                        pitchTrackDimensionBypass |= 0x10;
1930                        break;
1931                    case dim_bypass_ctrl_95:
1932                        pitchTrackDimensionBypass |= 0x20;
1933                        break;
1934                    case dim_bypass_ctrl_none:
1935                        //FIXME: should we set anything here?
1936                        break;
1937                    default:
1938                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1939                }
1940                pData[108] = pitchTrackDimensionBypass;
1941            }
1942    
1943            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1944            pData[109] = pan;
1945    
1946            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1947            pData[110] = selfmask;
1948    
1949            // next byte unknown
1950    
1951            {
1952                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1953                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1954                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1955                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1956                pData[112] = lfo3ctrl;
1957            }
1958    
1959            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1960            pData[113] = attenctl;
1961    
1962            {
1963                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1964                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1965                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1966                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1967                pData[114] = lfo2ctrl;
1968            }
1969    
1970            {
1971                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1972                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1973                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1974                if (VCFResonanceController != vcf_res_ctrl_none)
1975                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1976                pData[115] = lfo1ctrl;
1977            }
1978    
1979            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1980                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1981            store16(&pData[116], eg3depth);
1982    
1983          curve_type_t curveType = ReleaseVelocityResponseCurve;          // next 2 bytes unknown
         uint8_t depth = ReleaseVelocityResponseDepth;  
1984    
1985            const uint8_t channeloffset = ChannelOffset * 4;
1986            pData[120] = channeloffset;
1987    
1988            {
1989                uint8_t regoptions = 0;
1990                if (MSDecode)      regoptions |= 0x01; // bit 0
1991                if (SustainDefeat) regoptions |= 0x02; // bit 1
1992                pData[121] = regoptions;
1993            }
1994    
1995            // next 2 bytes unknown
1996    
1997            pData[124] = VelocityUpperLimit;
1998    
1999            // next 3 bytes unknown
2000    
2001            pData[128] = ReleaseTriggerDecay;
2002    
2003            // next 2 bytes unknown
2004    
2005            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2006            pData[131] = eg1hold;
2007    
2008            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2009                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
2010            pData[132] = vcfcutoff;
2011    
2012            pData[133] = VCFCutoffController;
2013    
2014            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2015                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
2016            pData[134] = vcfvelscale;
2017    
2018            // next byte unknown
2019    
2020            const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2021                                         (VCFResonance & 0x7f); /* lower 7 bits */
2022            pData[136] = vcfresonance;
2023    
2024            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2025                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2026            pData[137] = vcfbreakpoint;
2027    
2028            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2029                                        VCFVelocityCurve * 5;
2030            pData[138] = vcfvelocity;
2031    
2032            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2033            pData[139] = vcftype;
2034    
2035            if (chunksize >= 148) {
2036                memcpy(&pData[140], DimensionUpperLimits, 8);
2037            }
2038        }
2039    
2040        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2041            curve_type_t curveType = releaseVelocityResponseCurve;
2042            uint8_t depth = releaseVelocityResponseDepth;
2043          // this models a strange behaviour or bug in GSt: two of the          // this models a strange behaviour or bug in GSt: two of the
2044          // velocity response curves for release time are not used even          // velocity response curves for release time are not used even
2045          // if specified, instead another curve is chosen.          // if specified, instead another curve is chosen.
# Line 1168  namespace { Line 2048  namespace {
2048              curveType = curve_type_nonlinear;              curveType = curve_type_nonlinear;
2049              depth = 3;              depth = 3;
2050          }          }
2051          pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);          return GetVelocityTable(curveType, depth, 0);
2052        }
         curveType = VCFVelocityCurve;  
         depth = VCFVelocityDynamicRange;  
2053    
2054        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2055                                                        uint8_t vcfVelocityDynamicRange,
2056                                                        uint8_t vcfVelocityScale,
2057                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2058        {
2059            curve_type_t curveType = vcfVelocityCurve;
2060            uint8_t depth = vcfVelocityDynamicRange;
2061          // even stranger GSt: two of the velocity response curves for          // even stranger GSt: two of the velocity response curves for
2062          // filter cutoff are not used, instead another special curve          // filter cutoff are not used, instead another special curve
2063          // is chosen. This curve is not used anywhere else.          // is chosen. This curve is not used anywhere else.
# Line 1181  namespace { Line 2066  namespace {
2066              curveType = curve_type_special;              curveType = curve_type_special;
2067              depth = 5;              depth = 5;
2068          }          }
2069          pVelocityCutoffTable = GetVelocityTable(curveType, depth,          return GetVelocityTable(curveType, depth,
2070                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);                                  (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2071                                        ? vcfVelocityScale : 0);
         SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));  
2072      }      }
2073    
2074      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
# Line 1202  namespace { Line 2086  namespace {
2086          return table;          return table;
2087      }      }
2088    
2089        Region* DimensionRegion::GetParent() const {
2090            return pRegion;
2091        }
2092    
2093    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2094    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2095    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2096    //#pragma GCC diagnostic push
2097    //#pragma GCC diagnostic error "-Wswitch"
2098    
2099      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2100          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2101          switch (EncodedController) {          switch (EncodedController) {
# Line 1313  namespace { Line 2207  namespace {
2207                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2208                  break;                  break;
2209    
2210                // format extension (these controllers are so far only supported by
2211                // LinuxSampler & gigedit) they will *NOT* work with
2212                // Gigasampler/GigaStudio !
2213                case _lev_ctrl_CC3_EXT:
2214                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2215                    decodedcontroller.controller_number = 3;
2216                    break;
2217                case _lev_ctrl_CC6_EXT:
2218                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2219                    decodedcontroller.controller_number = 6;
2220                    break;
2221                case _lev_ctrl_CC7_EXT:
2222                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2223                    decodedcontroller.controller_number = 7;
2224                    break;
2225                case _lev_ctrl_CC8_EXT:
2226                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2227                    decodedcontroller.controller_number = 8;
2228                    break;
2229                case _lev_ctrl_CC9_EXT:
2230                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2231                    decodedcontroller.controller_number = 9;
2232                    break;
2233                case _lev_ctrl_CC10_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 10;
2236                    break;
2237                case _lev_ctrl_CC11_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 11;
2240                    break;
2241                case _lev_ctrl_CC14_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 14;
2244                    break;
2245                case _lev_ctrl_CC15_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 15;
2248                    break;
2249                case _lev_ctrl_CC20_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 20;
2252                    break;
2253                case _lev_ctrl_CC21_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 21;
2256                    break;
2257                case _lev_ctrl_CC22_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 22;
2260                    break;
2261                case _lev_ctrl_CC23_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 23;
2264                    break;
2265                case _lev_ctrl_CC24_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 24;
2268                    break;
2269                case _lev_ctrl_CC25_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 25;
2272                    break;
2273                case _lev_ctrl_CC26_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 26;
2276                    break;
2277                case _lev_ctrl_CC27_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 27;
2280                    break;
2281                case _lev_ctrl_CC28_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 28;
2284                    break;
2285                case _lev_ctrl_CC29_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 29;
2288                    break;
2289                case _lev_ctrl_CC30_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 30;
2292                    break;
2293                case _lev_ctrl_CC31_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 31;
2296                    break;
2297                case _lev_ctrl_CC68_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 68;
2300                    break;
2301                case _lev_ctrl_CC69_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 69;
2304                    break;
2305                case _lev_ctrl_CC70_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 70;
2308                    break;
2309                case _lev_ctrl_CC71_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 71;
2312                    break;
2313                case _lev_ctrl_CC72_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 72;
2316                    break;
2317                case _lev_ctrl_CC73_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 73;
2320                    break;
2321                case _lev_ctrl_CC74_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 74;
2324                    break;
2325                case _lev_ctrl_CC75_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 75;
2328                    break;
2329                case _lev_ctrl_CC76_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 76;
2332                    break;
2333                case _lev_ctrl_CC77_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 77;
2336                    break;
2337                case _lev_ctrl_CC78_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 78;
2340                    break;
2341                case _lev_ctrl_CC79_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 79;
2344                    break;
2345                case _lev_ctrl_CC84_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 84;
2348                    break;
2349                case _lev_ctrl_CC85_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 85;
2352                    break;
2353                case _lev_ctrl_CC86_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 86;
2356                    break;
2357                case _lev_ctrl_CC87_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 87;
2360                    break;
2361                case _lev_ctrl_CC89_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 89;
2364                    break;
2365                case _lev_ctrl_CC90_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 90;
2368                    break;
2369                case _lev_ctrl_CC96_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 96;
2372                    break;
2373                case _lev_ctrl_CC97_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 97;
2376                    break;
2377                case _lev_ctrl_CC102_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 102;
2380                    break;
2381                case _lev_ctrl_CC103_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 103;
2384                    break;
2385                case _lev_ctrl_CC104_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 104;
2388                    break;
2389                case _lev_ctrl_CC105_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 105;
2392                    break;
2393                case _lev_ctrl_CC106_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 106;
2396                    break;
2397                case _lev_ctrl_CC107_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 107;
2400                    break;
2401                case _lev_ctrl_CC108_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 108;
2404                    break;
2405                case _lev_ctrl_CC109_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 109;
2408                    break;
2409                case _lev_ctrl_CC110_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 110;
2412                    break;
2413                case _lev_ctrl_CC111_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 111;
2416                    break;
2417                case _lev_ctrl_CC112_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 112;
2420                    break;
2421                case _lev_ctrl_CC113_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 113;
2424                    break;
2425                case _lev_ctrl_CC114_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 114;
2428                    break;
2429                case _lev_ctrl_CC115_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 115;
2432                    break;
2433                case _lev_ctrl_CC116_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 116;
2436                    break;
2437                case _lev_ctrl_CC117_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 117;
2440                    break;
2441                case _lev_ctrl_CC118_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 118;
2444                    break;
2445                case _lev_ctrl_CC119_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 119;
2448                    break;
2449    
2450              // unknown controller type              // unknown controller type
2451              default:              default:
2452                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2453          }          }
2454          return decodedcontroller;          return decodedcontroller;
2455      }      }
2456        
2457    // see above (diagnostic push not supported prior GCC 4.6)
2458    //#pragma GCC diagnostic pop
2459    
2460        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2461            _lev_ctrl_t encodedcontroller;
2462            switch (DecodedController.type) {
2463                // special controller
2464                case leverage_ctrl_t::type_none:
2465                    encodedcontroller = _lev_ctrl_none;
2466                    break;
2467                case leverage_ctrl_t::type_velocity:
2468                    encodedcontroller = _lev_ctrl_velocity;
2469                    break;
2470                case leverage_ctrl_t::type_channelaftertouch:
2471                    encodedcontroller = _lev_ctrl_channelaftertouch;
2472                    break;
2473    
2474                // ordinary MIDI control change controller
2475                case leverage_ctrl_t::type_controlchange:
2476                    switch (DecodedController.controller_number) {
2477                        case 1:
2478                            encodedcontroller = _lev_ctrl_modwheel;
2479                            break;
2480                        case 2:
2481                            encodedcontroller = _lev_ctrl_breath;
2482                            break;
2483                        case 4:
2484                            encodedcontroller = _lev_ctrl_foot;
2485                            break;
2486                        case 12:
2487                            encodedcontroller = _lev_ctrl_effect1;
2488                            break;
2489                        case 13:
2490                            encodedcontroller = _lev_ctrl_effect2;
2491                            break;
2492                        case 16:
2493                            encodedcontroller = _lev_ctrl_genpurpose1;
2494                            break;
2495                        case 17:
2496                            encodedcontroller = _lev_ctrl_genpurpose2;
2497                            break;
2498                        case 18:
2499                            encodedcontroller = _lev_ctrl_genpurpose3;
2500                            break;
2501                        case 19:
2502                            encodedcontroller = _lev_ctrl_genpurpose4;
2503                            break;
2504                        case 5:
2505                            encodedcontroller = _lev_ctrl_portamentotime;
2506                            break;
2507                        case 64:
2508                            encodedcontroller = _lev_ctrl_sustainpedal;
2509                            break;
2510                        case 65:
2511                            encodedcontroller = _lev_ctrl_portamento;
2512                            break;
2513                        case 66:
2514                            encodedcontroller = _lev_ctrl_sostenutopedal;
2515                            break;
2516                        case 67:
2517                            encodedcontroller = _lev_ctrl_softpedal;
2518                            break;
2519                        case 80:
2520                            encodedcontroller = _lev_ctrl_genpurpose5;
2521                            break;
2522                        case 81:
2523                            encodedcontroller = _lev_ctrl_genpurpose6;
2524                            break;
2525                        case 82:
2526                            encodedcontroller = _lev_ctrl_genpurpose7;
2527                            break;
2528                        case 83:
2529                            encodedcontroller = _lev_ctrl_genpurpose8;
2530                            break;
2531                        case 91:
2532                            encodedcontroller = _lev_ctrl_effect1depth;
2533                            break;
2534                        case 92:
2535                            encodedcontroller = _lev_ctrl_effect2depth;
2536                            break;
2537                        case 93:
2538                            encodedcontroller = _lev_ctrl_effect3depth;
2539                            break;
2540                        case 94:
2541                            encodedcontroller = _lev_ctrl_effect4depth;
2542                            break;
2543                        case 95:
2544                            encodedcontroller = _lev_ctrl_effect5depth;
2545                            break;
2546    
2547                        // format extension (these controllers are so far only
2548                        // supported by LinuxSampler & gigedit) they will *NOT*
2549                        // work with Gigasampler/GigaStudio !
2550                        case 3:
2551                            encodedcontroller = _lev_ctrl_CC3_EXT;
2552                            break;
2553                        case 6:
2554                            encodedcontroller = _lev_ctrl_CC6_EXT;
2555                            break;
2556                        case 7:
2557                            encodedcontroller = _lev_ctrl_CC7_EXT;
2558                            break;
2559                        case 8:
2560                            encodedcontroller = _lev_ctrl_CC8_EXT;
2561                            break;
2562                        case 9:
2563                            encodedcontroller = _lev_ctrl_CC9_EXT;
2564                            break;
2565                        case 10:
2566                            encodedcontroller = _lev_ctrl_CC10_EXT;
2567                            break;
2568                        case 11:
2569                            encodedcontroller = _lev_ctrl_CC11_EXT;
2570                            break;
2571                        case 14:
2572                            encodedcontroller = _lev_ctrl_CC14_EXT;
2573                            break;
2574                        case 15:
2575                            encodedcontroller = _lev_ctrl_CC15_EXT;
2576                            break;
2577                        case 20:
2578                            encodedcontroller = _lev_ctrl_CC20_EXT;
2579                            break;
2580                        case 21:
2581                            encodedcontroller = _lev_ctrl_CC21_EXT;
2582                            break;
2583                        case 22:
2584                            encodedcontroller = _lev_ctrl_CC22_EXT;
2585                            break;
2586                        case 23:
2587                            encodedcontroller = _lev_ctrl_CC23_EXT;
2588                            break;
2589                        case 24:
2590                            encodedcontroller = _lev_ctrl_CC24_EXT;
2591                            break;
2592                        case 25:
2593                            encodedcontroller = _lev_ctrl_CC25_EXT;
2594                            break;
2595                        case 26:
2596                            encodedcontroller = _lev_ctrl_CC26_EXT;
2597                            break;
2598                        case 27:
2599                            encodedcontroller = _lev_ctrl_CC27_EXT;
2600                            break;
2601                        case 28:
2602                            encodedcontroller = _lev_ctrl_CC28_EXT;
2603                            break;
2604                        case 29:
2605                            encodedcontroller = _lev_ctrl_CC29_EXT;
2606                            break;
2607                        case 30:
2608                            encodedcontroller = _lev_ctrl_CC30_EXT;
2609                            break;
2610                        case 31:
2611                            encodedcontroller = _lev_ctrl_CC31_EXT;
2612                            break;
2613                        case 68:
2614                            encodedcontroller = _lev_ctrl_CC68_EXT;
2615                            break;
2616                        case 69:
2617                            encodedcontroller = _lev_ctrl_CC69_EXT;
2618                            break;
2619                        case 70:
2620                            encodedcontroller = _lev_ctrl_CC70_EXT;
2621                            break;
2622                        case 71:
2623                            encodedcontroller = _lev_ctrl_CC71_EXT;
2624                            break;
2625                        case 72:
2626                            encodedcontroller = _lev_ctrl_CC72_EXT;
2627                            break;
2628                        case 73:
2629                            encodedcontroller = _lev_ctrl_CC73_EXT;
2630                            break;
2631                        case 74:
2632                            encodedcontroller = _lev_ctrl_CC74_EXT;
2633                            break;
2634                        case 75:
2635                            encodedcontroller = _lev_ctrl_CC75_EXT;
2636                            break;
2637                        case 76:
2638                            encodedcontroller = _lev_ctrl_CC76_EXT;
2639                            break;
2640                        case 77:
2641                            encodedcontroller = _lev_ctrl_CC77_EXT;
2642                            break;
2643                        case 78:
2644                            encodedcontroller = _lev_ctrl_CC78_EXT;
2645                            break;
2646                        case 79:
2647                            encodedcontroller = _lev_ctrl_CC79_EXT;
2648                            break;
2649                        case 84:
2650                            encodedcontroller = _lev_ctrl_CC84_EXT;
2651                            break;
2652                        case 85:
2653                            encodedcontroller = _lev_ctrl_CC85_EXT;
2654                            break;
2655                        case 86:
2656                            encodedcontroller = _lev_ctrl_CC86_EXT;
2657                            break;
2658                        case 87:
2659                            encodedcontroller = _lev_ctrl_CC87_EXT;
2660                            break;
2661                        case 89:
2662                            encodedcontroller = _lev_ctrl_CC89_EXT;
2663                            break;
2664                        case 90:
2665                            encodedcontroller = _lev_ctrl_CC90_EXT;
2666                            break;
2667                        case 96:
2668                            encodedcontroller = _lev_ctrl_CC96_EXT;
2669                            break;
2670                        case 97:
2671                            encodedcontroller = _lev_ctrl_CC97_EXT;
2672                            break;
2673                        case 102:
2674                            encodedcontroller = _lev_ctrl_CC102_EXT;
2675                            break;
2676                        case 103:
2677                            encodedcontroller = _lev_ctrl_CC103_EXT;
2678                            break;
2679                        case 104:
2680                            encodedcontroller = _lev_ctrl_CC104_EXT;
2681                            break;
2682                        case 105:
2683                            encodedcontroller = _lev_ctrl_CC105_EXT;
2684                            break;
2685                        case 106:
2686                            encodedcontroller = _lev_ctrl_CC106_EXT;
2687                            break;
2688                        case 107:
2689                            encodedcontroller = _lev_ctrl_CC107_EXT;
2690                            break;
2691                        case 108:
2692                            encodedcontroller = _lev_ctrl_CC108_EXT;
2693                            break;
2694                        case 109:
2695                            encodedcontroller = _lev_ctrl_CC109_EXT;
2696                            break;
2697                        case 110:
2698                            encodedcontroller = _lev_ctrl_CC110_EXT;
2699                            break;
2700                        case 111:
2701                            encodedcontroller = _lev_ctrl_CC111_EXT;
2702                            break;
2703                        case 112:
2704                            encodedcontroller = _lev_ctrl_CC112_EXT;
2705                            break;
2706                        case 113:
2707                            encodedcontroller = _lev_ctrl_CC113_EXT;
2708                            break;
2709                        case 114:
2710                            encodedcontroller = _lev_ctrl_CC114_EXT;
2711                            break;
2712                        case 115:
2713                            encodedcontroller = _lev_ctrl_CC115_EXT;
2714                            break;
2715                        case 116:
2716                            encodedcontroller = _lev_ctrl_CC116_EXT;
2717                            break;
2718                        case 117:
2719                            encodedcontroller = _lev_ctrl_CC117_EXT;
2720                            break;
2721                        case 118:
2722                            encodedcontroller = _lev_ctrl_CC118_EXT;
2723                            break;
2724                        case 119:
2725                            encodedcontroller = _lev_ctrl_CC119_EXT;
2726                            break;
2727    
2728                        default:
2729                            throw gig::Exception("leverage controller number is not supported by the gig format");
2730                    }
2731                    break;
2732                default:
2733                    throw gig::Exception("Unknown leverage controller type.");
2734            }
2735            return encodedcontroller;
2736        }
2737    
2738      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
2739          Instances--;          Instances--;
# Line 1333  namespace { Line 2748  namespace {
2748              delete pVelocityTables;              delete pVelocityTables;
2749              pVelocityTables = NULL;              pVelocityTables = NULL;
2750          }          }
2751            if (VelocityTable) delete[] VelocityTable;
2752      }      }
2753    
2754      /**      /**
# Line 1358  namespace { Line 2774  namespace {
2774          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2775      }      }
2776    
2777        /**
2778         * Updates the respective member variable and the lookup table / cache
2779         * that depends on this value.
2780         */
2781        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2782            pVelocityAttenuationTable =
2783                GetVelocityTable(
2784                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2785                );
2786            VelocityResponseCurve = curve;
2787        }
2788    
2789        /**
2790         * Updates the respective member variable and the lookup table / cache
2791         * that depends on this value.
2792         */
2793        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2794            pVelocityAttenuationTable =
2795                GetVelocityTable(
2796                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2797                );
2798            VelocityResponseDepth = depth;
2799        }
2800    
2801        /**
2802         * Updates the respective member variable and the lookup table / cache
2803         * that depends on this value.
2804         */
2805        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2806            pVelocityAttenuationTable =
2807                GetVelocityTable(
2808                    VelocityResponseCurve, VelocityResponseDepth, scaling
2809                );
2810            VelocityResponseCurveScaling = scaling;
2811        }
2812    
2813        /**
2814         * Updates the respective member variable and the lookup table / cache
2815         * that depends on this value.
2816         */
2817        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2818            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2819            ReleaseVelocityResponseCurve = curve;
2820        }
2821    
2822        /**
2823         * Updates the respective member variable and the lookup table / cache
2824         * that depends on this value.
2825         */
2826        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2827            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2828            ReleaseVelocityResponseDepth = depth;
2829        }
2830    
2831        /**
2832         * Updates the respective member variable and the lookup table / cache
2833         * that depends on this value.
2834         */
2835        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2836            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2837            VCFCutoffController = controller;
2838        }
2839    
2840        /**
2841         * Updates the respective member variable and the lookup table / cache
2842         * that depends on this value.
2843         */
2844        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2845            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2846            VCFVelocityCurve = curve;
2847        }
2848    
2849        /**
2850         * Updates the respective member variable and the lookup table / cache
2851         * that depends on this value.
2852         */
2853        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2854            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2855            VCFVelocityDynamicRange = range;
2856        }
2857    
2858        /**
2859         * Updates the respective member variable and the lookup table / cache
2860         * that depends on this value.
2861         */
2862        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2863            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2864            VCFVelocityScale = scaling;
2865        }
2866    
2867      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2868    
2869          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1441  namespace { Line 2947  namespace {
2947    
2948          // Actual Loading          // Actual Loading
2949    
2950            if (!file->GetAutoLoad()) return;
2951    
2952          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2953    
2954          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 1449  namespace { Line 2957  namespace {
2957              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2958                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2959                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2960                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2961                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2962                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2963                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2964                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2965                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2966                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2967                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2968                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2969                  }                  }
2970                  else { // active dimension                  else { // active dimension
2971                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2972                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2973                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2974                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2975                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2976                      Dimensions++;                      Dimensions++;
2977    
2978                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 1481  namespace { Line 2980  namespace {
2980                  }                  }
2981                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2982              }              }
2983                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2984    
2985              // check velocity dimension (if there is one) for custom defined zone ranges              // if there's a velocity dimension and custom velocity zone splits are used,
2986              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2987                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
                 if (pDimDef->dimension == dimension_velocity) {  
                     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {  
                         // no custom defined ranges  
                         pDimDef->split_type = split_type_normal;  
                         pDimDef->ranges     = NULL;  
                     }  
                     else { // custom defined ranges  
                         pDimDef->split_type = split_type_customvelocity;  
                         pDimDef->ranges     = new range_t[pDimDef->zones];  
                         uint8_t bits[8] = { 0 };  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);  
   
                             pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;  
                             pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;  
                             previousUpperLimit = pDimDef->ranges[velocityZone].high;  
                             // fill velocity table  
                             for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {  
                                 VelocityTable[i] = velocityZone;  
                             }  
                         }  
                     }  
                 }  
             }  
2988    
2989              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
             File* file = (File*) GetParent()->GetParent();  
2990              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2991                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2992              else              else
2993                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2994    
2995              // load sample references              // load sample references (if auto loading is enabled)
2996              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2997                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2998                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2999                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3000                    }
3001                    GetSample(); // load global region sample reference
3002                }
3003            } else {
3004                DimensionRegions = 0;
3005                for (int i = 0 ; i < 8 ; i++) {
3006                    pDimensionDefinitions[i].dimension  = dimension_none;
3007                    pDimensionDefinitions[i].bits       = 0;
3008                    pDimensionDefinitions[i].zones      = 0;
3009                }
3010            }
3011    
3012            // make sure there is at least one dimension region
3013            if (!DimensionRegions) {
3014                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3015                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3016                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3017                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3018                DimensionRegions = 1;
3019            }
3020        }
3021    
3022        /**
3023         * Apply Region settings and all its DimensionRegions to the respective
3024         * RIFF chunks. You have to call File::Save() to make changes persistent.
3025         *
3026         * Usually there is absolutely no need to call this method explicitly.
3027         * It will be called automatically when File::Save() was called.
3028         *
3029         * @throws gig::Exception if samples cannot be dereferenced
3030         */
3031        void Region::UpdateChunks() {
3032            // in the gig format we don't care about the Region's sample reference
3033            // but we still have to provide some existing one to not corrupt the
3034            // file, so to avoid the latter we simply always assign the sample of
3035            // the first dimension region of this region
3036            pSample = pDimensionRegions[0]->pSample;
3037    
3038            // first update base class's chunks
3039            DLS::Region::UpdateChunks();
3040    
3041            // update dimension region's chunks
3042            for (int i = 0; i < DimensionRegions; i++) {
3043                pDimensionRegions[i]->UpdateChunks();
3044            }
3045    
3046            File* pFile = (File*) GetParent()->GetParent();
3047            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3048            const int iMaxDimensions =  version3 ? 8 : 5;
3049            const int iMaxDimensionRegions = version3 ? 256 : 32;
3050    
3051            // make sure '3lnk' chunk exists
3052            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3053            if (!_3lnk) {
3054                const int _3lnkChunkSize = version3 ? 1092 : 172;
3055                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3056                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3057    
3058                // move 3prg to last position
3059                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
3060            }
3061    
3062            // update dimension definitions in '3lnk' chunk
3063            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3064            store32(&pData[0], DimensionRegions);
3065            int shift = 0;
3066            for (int i = 0; i < iMaxDimensions; i++) {
3067                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3068                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3069                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3070                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3071                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3072                // next 3 bytes unknown, always zero?
3073    
3074                shift += pDimensionDefinitions[i].bits;
3075            }
3076    
3077            // update wave pool table in '3lnk' chunk
3078            const int iWavePoolOffset = version3 ? 68 : 44;
3079            for (uint i = 0; i < iMaxDimensionRegions; i++) {
3080                int iWaveIndex = -1;
3081                if (i < DimensionRegions) {
3082                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
3083                    File::SampleList::iterator iter = pFile->pSamples->begin();
3084                    File::SampleList::iterator end  = pFile->pSamples->end();
3085                    for (int index = 0; iter != end; ++iter, ++index) {
3086                        if (*iter == pDimensionRegions[i]->pSample) {
3087                            iWaveIndex = index;
3088                            break;
3089                        }
3090                    }
3091              }              }
3092                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3093          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
3094      }      }
3095    
3096      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1535  namespace { Line 3100  namespace {
3100              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3101              while (_3ewl) {              while (_3ewl) {
3102                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3103                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3104                      dimensionRegionNr++;                      dimensionRegionNr++;
3105                  }                  }
3106                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 1544  namespace { Line 3109  namespace {
3109          }          }
3110      }      }
3111    
3112      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3113          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
3114              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
3115            // update Region key table for fast lookup
3116            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3117        }
3118    
3119        void Region::UpdateVelocityTable() {
3120            // get velocity dimension's index
3121            int veldim = -1;
3122            for (int i = 0 ; i < Dimensions ; i++) {
3123                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
3124                    veldim = i;
3125                    break;
3126                }
3127            }
3128            if (veldim == -1) return;
3129    
3130            int step = 1;
3131            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3132            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
3133            int end = step * pDimensionDefinitions[veldim].zones;
3134    
3135            // loop through all dimension regions for all dimensions except the velocity dimension
3136            int dim[8] = { 0 };
3137            for (int i = 0 ; i < DimensionRegions ; i++) {
3138    
3139                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3140                    pDimensionRegions[i]->VelocityUpperLimit) {
3141                    // create the velocity table
3142                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
3143                    if (!table) {
3144                        table = new uint8_t[128];
3145                        pDimensionRegions[i]->VelocityTable = table;
3146                    }
3147                    int tableidx = 0;
3148                    int velocityZone = 0;
3149                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3150                        for (int k = i ; k < end ; k += step) {
3151                            DimensionRegion *d = pDimensionRegions[k];
3152                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3153                            velocityZone++;
3154                        }
3155                    } else { // gig2
3156                        for (int k = i ; k < end ; k += step) {
3157                            DimensionRegion *d = pDimensionRegions[k];
3158                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3159                            velocityZone++;
3160                        }
3161                    }
3162                } else {
3163                    if (pDimensionRegions[i]->VelocityTable) {
3164                        delete[] pDimensionRegions[i]->VelocityTable;
3165                        pDimensionRegions[i]->VelocityTable = 0;
3166                    }
3167                }
3168    
3169                int j;
3170                int shift = 0;
3171                for (j = 0 ; j < Dimensions ; j++) {
3172                    if (j == veldim) i += skipveldim; // skip velocity dimension
3173                    else {
3174                        dim[j]++;
3175                        if (dim[j] < pDimensionDefinitions[j].zones) break;
3176                        else {
3177                            // skip unused dimension regions
3178                            dim[j] = 0;
3179                            i += ((1 << pDimensionDefinitions[j].bits) -
3180                                  pDimensionDefinitions[j].zones) << shift;
3181                        }
3182                    }
3183                    shift += pDimensionDefinitions[j].bits;
3184                }
3185                if (j == Dimensions) break;
3186            }
3187        }
3188    
3189        /** @brief Einstein would have dreamed of it - create a new dimension.
3190         *
3191         * Creates a new dimension with the dimension definition given by
3192         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
3193         * There is a hard limit of dimensions and total amount of "bits" all
3194         * dimensions can have. This limit is dependant to what gig file format
3195         * version this file refers to. The gig v2 (and lower) format has a
3196         * dimension limit and total amount of bits limit of 5, whereas the gig v3
3197         * format has a limit of 8.
3198         *
3199         * @param pDimDef - defintion of the new dimension
3200         * @throws gig::Exception if dimension of the same type exists already
3201         * @throws gig::Exception if amount of dimensions or total amount of
3202         *                        dimension bits limit is violated
3203         */
3204        void Region::AddDimension(dimension_def_t* pDimDef) {
3205            // some initial sanity checks of the given dimension definition
3206            if (pDimDef->zones < 2)
3207                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3208            if (pDimDef->bits < 1)
3209                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3210            if (pDimDef->dimension == dimension_samplechannel) {
3211                if (pDimDef->zones != 2)
3212                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3213                if (pDimDef->bits != 1)
3214                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3215            }
3216    
3217            // check if max. amount of dimensions reached
3218            File* file = (File*) GetParent()->GetParent();
3219            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
3220            if (Dimensions >= iMaxDimensions)
3221                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3222            // check if max. amount of dimension bits reached
3223            int iCurrentBits = 0;
3224            for (int i = 0; i < Dimensions; i++)
3225                iCurrentBits += pDimensionDefinitions[i].bits;
3226            if (iCurrentBits >= iMaxDimensions)
3227                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
3228            const int iNewBits = iCurrentBits + pDimDef->bits;
3229            if (iNewBits > iMaxDimensions)
3230                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
3231            // check if there's already a dimensions of the same type
3232            for (int i = 0; i < Dimensions; i++)
3233                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3234                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3235    
3236            // pos is where the new dimension should be placed, normally
3237            // last in list, except for the samplechannel dimension which
3238            // has to be first in list
3239            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3240            int bitpos = 0;
3241            for (int i = 0 ; i < pos ; i++)
3242                bitpos += pDimensionDefinitions[i].bits;
3243    
3244            // make room for the new dimension
3245            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3246            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3247                for (int j = Dimensions ; j > pos ; j--) {
3248                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3249                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3250                }
3251            }
3252    
3253            // assign definition of new dimension
3254            pDimensionDefinitions[pos] = *pDimDef;
3255    
3256            // auto correct certain dimension definition fields (where possible)
3257            pDimensionDefinitions[pos].split_type  =
3258                __resolveSplitType(pDimensionDefinitions[pos].dimension);
3259            pDimensionDefinitions[pos].zone_size =
3260                __resolveZoneSize(pDimensionDefinitions[pos]);
3261    
3262            // create new dimension region(s) for this new dimension, and make
3263            // sure that the dimension regions are placed correctly in both the
3264            // RIFF list and the pDimensionRegions array
3265            RIFF::Chunk* moveTo = NULL;
3266            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3267            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3268                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3269                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3270                }
3271                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3272                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3273                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3274                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3275                        // create a new dimension region and copy all parameter values from
3276                        // an existing dimension region
3277                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3278                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3279    
3280                        DimensionRegions++;
3281                    }
3282                }
3283                moveTo = pDimensionRegions[i]->pParentList;
3284            }
3285    
3286            // initialize the upper limits for this dimension
3287            int mask = (1 << bitpos) - 1;
3288            for (int z = 0 ; z < pDimDef->zones ; z++) {
3289                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3290                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3291                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3292                                      (z << bitpos) |
3293                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3294                }
3295            }
3296    
3297            Dimensions++;
3298    
3299            // if this is a layer dimension, update 'Layers' attribute
3300            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
3301    
3302            UpdateVelocityTable();
3303        }
3304    
3305        /** @brief Delete an existing dimension.
3306         *
3307         * Deletes the dimension given by \a pDimDef and deletes all respective
3308         * dimension regions, that is all dimension regions where the dimension's
3309         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
3310         * for example this would delete all dimension regions for the case(s)
3311         * where the sustain pedal is pressed down.
3312         *
3313         * @param pDimDef - dimension to delete
3314         * @throws gig::Exception if given dimension cannot be found
3315         */
3316        void Region::DeleteDimension(dimension_def_t* pDimDef) {
3317            // get dimension's index
3318            int iDimensionNr = -1;
3319            for (int i = 0; i < Dimensions; i++) {
3320                if (&pDimensionDefinitions[i] == pDimDef) {
3321                    iDimensionNr = i;
3322                    break;
3323                }
3324            }
3325            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
3326    
3327            // get amount of bits below the dimension to delete
3328            int iLowerBits = 0;
3329            for (int i = 0; i < iDimensionNr; i++)
3330                iLowerBits += pDimensionDefinitions[i].bits;
3331    
3332            // get amount ot bits above the dimension to delete
3333            int iUpperBits = 0;
3334            for (int i = iDimensionNr + 1; i < Dimensions; i++)
3335                iUpperBits += pDimensionDefinitions[i].bits;
3336    
3337            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3338    
3339            // delete dimension regions which belong to the given dimension
3340            // (that is where the dimension's bit > 0)
3341            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
3342                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
3343                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
3344                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3345                                        iObsoleteBit << iLowerBits |
3346                                        iLowerBit;
3347    
3348                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3349                        delete pDimensionRegions[iToDelete];
3350                        pDimensionRegions[iToDelete] = NULL;
3351                        DimensionRegions--;
3352                    }
3353                }
3354            }
3355    
3356            // defrag pDimensionRegions array
3357            // (that is remove the NULL spaces within the pDimensionRegions array)
3358            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
3359                if (!pDimensionRegions[iTo]) {
3360                    if (iFrom <= iTo) iFrom = iTo + 1;
3361                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
3362                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
3363                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
3364                        pDimensionRegions[iFrom] = NULL;
3365                    }
3366                }
3367            }
3368    
3369            // remove the this dimension from the upper limits arrays
3370            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3371                DimensionRegion* d = pDimensionRegions[j];
3372                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3373                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3374                }
3375                d->DimensionUpperLimits[Dimensions - 1] = 127;
3376            }
3377    
3378            // 'remove' dimension definition
3379            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3380                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
3381            }
3382            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
3383            pDimensionDefinitions[Dimensions - 1].bits      = 0;
3384            pDimensionDefinitions[Dimensions - 1].zones     = 0;
3385    
3386            Dimensions--;
3387    
3388            // if this was a layer dimension, update 'Layers' attribute
3389            if (pDimDef->dimension == dimension_layer) Layers = 1;
3390        }
3391    
3392        /** @brief Delete one split zone of a dimension (decrement zone amount).
3393         *
3394         * Instead of deleting an entire dimensions, this method will only delete
3395         * one particular split zone given by @a zone of the Region's dimension
3396         * given by @a type. So this method will simply decrement the amount of
3397         * zones by one of the dimension in question. To be able to do that, the
3398         * respective dimension must exist on this Region and it must have at least
3399         * 3 zones. All DimensionRegion objects associated with the zone will be
3400         * deleted.
3401         *
3402         * @param type - identifies the dimension where a zone shall be deleted
3403         * @param zone - index of the dimension split zone that shall be deleted
3404         * @throws gig::Exception if requested zone could not be deleted
3405         */
3406        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3407            dimension_def_t* oldDef = GetDimensionDefinition(type);
3408            if (!oldDef)
3409                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3410            if (oldDef->zones <= 2)
3411                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3412            if (zone < 0 || zone >= oldDef->zones)
3413                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3414    
3415            const int newZoneSize = oldDef->zones - 1;
3416    
3417            // create a temporary Region which just acts as a temporary copy
3418            // container and will be deleted at the end of this function and will
3419            // also not be visible through the API during this process
3420            gig::Region* tempRgn = NULL;
3421            {
3422                // adding these temporary chunks is probably not even necessary
3423                Instrument* instr = static_cast<Instrument*>(GetParent());
3424                RIFF::List* pCkInstrument = instr->pCkInstrument;
3425                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3426                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3427                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3428                tempRgn = new Region(instr, rgn);
3429            }
3430    
3431            // copy this region's dimensions (with already the dimension split size
3432            // requested by the arguments of this method call) to the temporary
3433            // region, and don't use Region::CopyAssign() here for this task, since
3434            // it would also alter fast lookup helper variables here and there
3435            dimension_def_t newDef;
3436            for (int i = 0; i < Dimensions; ++i) {
3437                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3438                // is this the dimension requested by the method arguments? ...
3439                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3440                    def.zones = newZoneSize;
3441                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3442                    newDef = def;
3443                }
3444                tempRgn->AddDimension(&def);
3445            }
3446    
3447            // find the dimension index in the tempRegion which is the dimension
3448            // type passed to this method (paranoidly expecting different order)
3449            int tempReducedDimensionIndex = -1;
3450            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3451                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3452                    tempReducedDimensionIndex = d;
3453                    break;
3454                }
3455          }          }
3456    
3457            // copy dimension regions from this region to the temporary region
3458            for (int iDst = 0; iDst < 256; ++iDst) {
3459                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3460                if (!dstDimRgn) continue;
3461                std::map<dimension_t,int> dimCase;
3462                bool isValidZone = true;
3463                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3464                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3465                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3466                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3467                    baseBits += dstBits;
3468                    // there are also DimensionRegion objects of unused zones, skip them
3469                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3470                        isValidZone = false;
3471                        break;
3472                    }
3473                }
3474                if (!isValidZone) continue;
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3478                if (dimCase[type] >= zone) dimCase[type]++;
3479                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3480                dstDimRgn->CopyAssign(srcDimRgn);
3481                // if this is the upper most zone of the dimension passed to this
3482                // method, then correct (raise) its upper limit to 127
3483                if (newDef.split_type == split_type_normal && isLastZone)
3484                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3485            }
3486    
3487            // now tempRegion's dimensions and DimensionRegions basically reflect
3488            // what we wanted to get for this actual Region here, so we now just
3489            // delete and recreate the dimension in question with the new amount
3490            // zones and then copy back from tempRegion      
3491            DeleteDimension(oldDef);
3492            AddDimension(&newDef);
3493            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3494                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3495                if (!srcDimRgn) continue;
3496                std::map<dimension_t,int> dimCase;
3497                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3498                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3499                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3500                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3501                    baseBits += srcBits;
3502                }
3503                // a bit paranoid: cope with the chance that the dimensions would
3504                // have different order in source and destination regions
3505                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3506                if (!dstDimRgn) continue;
3507                dstDimRgn->CopyAssign(srcDimRgn);
3508            }
3509    
3510            // delete temporary region
3511            delete tempRgn;
3512        }
3513    
3514        /** @brief Divide split zone of a dimension in two (increment zone amount).
3515         *
3516         * This will increment the amount of zones for the dimension (given by
3517         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3518         * in the middle of its zone range in two. So the two zones resulting from
3519         * the zone being splitted, will be an equivalent copy regarding all their
3520         * articulation informations and sample reference. The two zones will only
3521         * differ in their zone's upper limit
3522         * (DimensionRegion::DimensionUpperLimits).
3523         *
3524         * @param type - identifies the dimension where a zone shall be splitted
3525         * @param zone - index of the dimension split zone that shall be splitted
3526         * @throws gig::Exception if requested zone could not be splitted
3527         */
3528        void Region::SplitDimensionZone(dimension_t type, int zone) {
3529            dimension_def_t* oldDef = GetDimensionDefinition(type);
3530            if (!oldDef)
3531                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3532            if (zone < 0 || zone >= oldDef->zones)
3533                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3534    
3535            const int newZoneSize = oldDef->zones + 1;
3536    
3537            // create a temporary Region which just acts as a temporary copy
3538            // container and will be deleted at the end of this function and will
3539            // also not be visible through the API during this process
3540            gig::Region* tempRgn = NULL;
3541            {
3542                // adding these temporary chunks is probably not even necessary
3543                Instrument* instr = static_cast<Instrument*>(GetParent());
3544                RIFF::List* pCkInstrument = instr->pCkInstrument;
3545                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3546                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3547                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3548                tempRgn = new Region(instr, rgn);
3549            }
3550    
3551            // copy this region's dimensions (with already the dimension split size
3552            // requested by the arguments of this method call) to the temporary
3553            // region, and don't use Region::CopyAssign() here for this task, since
3554            // it would also alter fast lookup helper variables here and there
3555            dimension_def_t newDef;
3556            for (int i = 0; i < Dimensions; ++i) {
3557                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3558                // is this the dimension requested by the method arguments? ...
3559                if (def.dimension == type) { // ... if yes, increment zone amount by one
3560                    def.zones = newZoneSize;
3561                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3562                    newDef = def;
3563                }
3564                tempRgn->AddDimension(&def);
3565            }
3566    
3567            // find the dimension index in the tempRegion which is the dimension
3568            // type passed to this method (paranoidly expecting different order)
3569            int tempIncreasedDimensionIndex = -1;
3570            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3571                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3572                    tempIncreasedDimensionIndex = d;
3573                    break;
3574                }
3575            }
3576    
3577            // copy dimension regions from this region to the temporary region
3578            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3579                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3580                if (!srcDimRgn) continue;
3581                std::map<dimension_t,int> dimCase;
3582                bool isValidZone = true;
3583                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3584                    const int srcBits = pDimensionDefinitions[d].bits;
3585                    dimCase[pDimensionDefinitions[d].dimension] =
3586                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3587                    // there are also DimensionRegion objects for unused zones, skip them
3588                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3589                        isValidZone = false;
3590                        break;
3591                    }
3592                    baseBits += srcBits;
3593                }
3594                if (!isValidZone) continue;
3595                // a bit paranoid: cope with the chance that the dimensions would
3596                // have different order in source and destination regions            
3597                if (dimCase[type] > zone) dimCase[type]++;
3598                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3599                dstDimRgn->CopyAssign(srcDimRgn);
3600                // if this is the requested zone to be splitted, then also copy
3601                // the source DimensionRegion to the newly created target zone
3602                // and set the old zones upper limit lower
3603                if (dimCase[type] == zone) {
3604                    // lower old zones upper limit
3605                    if (newDef.split_type == split_type_normal) {
3606                        const int high =
3607                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3608                        int low = 0;
3609                        if (zone > 0) {
3610                            std::map<dimension_t,int> lowerCase = dimCase;
3611                            lowerCase[type]--;
3612                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3613                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3614                        }
3615                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3616                    }
3617                    // fill the newly created zone of the divided zone as well
3618                    dimCase[type]++;
3619                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3620                    dstDimRgn->CopyAssign(srcDimRgn);
3621                }
3622            }
3623    
3624            // now tempRegion's dimensions and DimensionRegions basically reflect
3625            // what we wanted to get for this actual Region here, so we now just
3626            // delete and recreate the dimension in question with the new amount
3627            // zones and then copy back from tempRegion      
3628            DeleteDimension(oldDef);
3629            AddDimension(&newDef);
3630            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3631                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3632                if (!srcDimRgn) continue;
3633                std::map<dimension_t,int> dimCase;
3634                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3635                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3636                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3637                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3638                    baseBits += srcBits;
3639                }
3640                // a bit paranoid: cope with the chance that the dimensions would
3641                // have different order in source and destination regions
3642                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3643                if (!dstDimRgn) continue;
3644                dstDimRgn->CopyAssign(srcDimRgn);
3645            }
3646    
3647            // delete temporary region
3648            delete tempRgn;
3649        }
3650    
3651        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3652            uint8_t bits[8] = {};
3653            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3654                 it != DimCase.end(); ++it)
3655            {
3656                for (int d = 0; d < Dimensions; ++d) {
3657                    if (pDimensionDefinitions[d].dimension == it->first) {
3658                        bits[d] = it->second;
3659                        goto nextDimCaseSlice;
3660                    }
3661                }
3662                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3663                nextDimCaseSlice:
3664                ; // noop
3665            }
3666            return GetDimensionRegionByBit(bits);
3667        }
3668    
3669        /**
3670         * Searches in the current Region for a dimension of the given dimension
3671         * type and returns the precise configuration of that dimension in this
3672         * Region.
3673         *
3674         * @param type - dimension type of the sought dimension
3675         * @returns dimension definition or NULL if there is no dimension with
3676         *          sought type in this Region.
3677         */
3678        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3679            for (int i = 0; i < Dimensions; ++i)
3680                if (pDimensionDefinitions[i].dimension == type)
3681                    return &pDimensionDefinitions[i];
3682            return NULL;
3683        }
3684    
3685        Region::~Region() {
3686          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3687              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
3688          }          }
# Line 1572  namespace { Line 3707  namespace {
3707       * @see             Dimensions       * @see             Dimensions
3708       */       */
3709      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3710          uint8_t bits[8] = { 0 };          uint8_t bits;
3711            int veldim = -1;
3712            int velbitpos;
3713            int bitpos = 0;
3714            int dimregidx = 0;
3715          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
3716              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3717              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
3718                  case split_type_normal:                  veldim = i;
3719                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);                  velbitpos = bitpos;
3720                      break;              } else {
3721                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
3722                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
3723                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3724                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3725                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3726                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3727                      break;                              }
3728                            } else {
3729                                // gig2: evenly sized zones
3730                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3731                            }
3732                            break;
3733                        case split_type_bit: // the value is already the sought dimension bit number
3734                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3735                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3736                            break;
3737                    }
3738                    dimregidx |= bits << bitpos;
3739              }              }
3740                bitpos += pDimensionDefinitions[i].bits;
3741          }          }
3742          return GetDimensionRegionByBit(bits);          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3743            if (veldim != -1) {
3744                // (dimreg is now the dimension region for the lowest velocity)
3745                if (dimreg->VelocityTable) // custom defined zone ranges
3746                    bits = dimreg->VelocityTable[DimValues[veldim]];
3747                else // normal split type
3748                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
3749    
3750                dimregidx |= bits << velbitpos;
3751                dimreg = pDimensionRegions[dimregidx];
3752            }
3753            return dimreg;
3754      }      }
3755    
3756      /**      /**
# Line 1628  namespace { Line 3790  namespace {
3790      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3791          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3792          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3793            if (!file->pWavePoolTable) return NULL;
3794          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3795          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3796          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
3797          while (sample) {          while (sample) {
3798              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
3799                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3800              sample = file->GetNextSample();              sample = file->GetNextSample();
3801          }          }
3802          return NULL;          return NULL;
3803      }      }
3804        
3805        /**
3806         * Make a (semi) deep copy of the Region object given by @a orig
3807         * and assign it to this object.
3808         *
3809         * Note that all sample pointers referenced by @a orig are simply copied as
3810         * memory address. Thus the respective samples are shared, not duplicated!
3811         *
3812         * @param orig - original Region object to be copied from
3813         */
3814        void Region::CopyAssign(const Region* orig) {
3815            CopyAssign(orig, NULL);
3816        }
3817        
3818        /**
3819         * Make a (semi) deep copy of the Region object given by @a orig and
3820         * assign it to this object
3821         *
3822         * @param mSamples - crosslink map between the foreign file's samples and
3823         *                   this file's samples
3824         */
3825        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3826            // handle base classes
3827            DLS::Region::CopyAssign(orig);
3828            
3829            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3830                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3831            }
3832            
3833            // handle own member variables
3834            for (int i = Dimensions - 1; i >= 0; --i) {
3835                DeleteDimension(&pDimensionDefinitions[i]);
3836            }
3837            Layers = 0; // just to be sure
3838            for (int i = 0; i < orig->Dimensions; i++) {
3839                // we need to copy the dim definition here, to avoid the compiler
3840                // complaining about const-ness issue
3841                dimension_def_t def = orig->pDimensionDefinitions[i];
3842                AddDimension(&def);
3843            }
3844            for (int i = 0; i < 256; i++) {
3845                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3846                    pDimensionRegions[i]->CopyAssign(
3847                        orig->pDimensionRegions[i],
3848                        mSamples
3849                    );
3850                }
3851            }
3852            Layers = orig->Layers;
3853        }
3854    
3855    
3856    // *************** MidiRule ***************
3857    // *
3858    
3859        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3860            _3ewg->SetPos(36);
3861            Triggers = _3ewg->ReadUint8();
3862            _3ewg->SetPos(40);
3863            ControllerNumber = _3ewg->ReadUint8();
3864            _3ewg->SetPos(46);
3865            for (int i = 0 ; i < Triggers ; i++) {
3866                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3867                pTriggers[i].Descending = _3ewg->ReadUint8();
3868                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3869                pTriggers[i].Key = _3ewg->ReadUint8();
3870                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3871                pTriggers[i].Velocity = _3ewg->ReadUint8();
3872                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3873                _3ewg->ReadUint8();
3874            }
3875        }
3876    
3877        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3878            ControllerNumber(0),
3879            Triggers(0) {
3880        }
3881    
3882        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3883            pData[32] = 4;
3884            pData[33] = 16;
3885            pData[36] = Triggers;
3886            pData[40] = ControllerNumber;
3887            for (int i = 0 ; i < Triggers ; i++) {
3888                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3889                pData[47 + i * 8] = pTriggers[i].Descending;
3890                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3891                pData[49 + i * 8] = pTriggers[i].Key;
3892                pData[50 + i * 8] = pTriggers[i].NoteOff;
3893                pData[51 + i * 8] = pTriggers[i].Velocity;
3894                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3895            }
3896        }
3897    
3898        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3899            _3ewg->SetPos(36);
3900            LegatoSamples = _3ewg->ReadUint8(); // always 12
3901            _3ewg->SetPos(40);
3902            BypassUseController = _3ewg->ReadUint8();
3903            BypassKey = _3ewg->ReadUint8();
3904            BypassController = _3ewg->ReadUint8();
3905            ThresholdTime = _3ewg->ReadUint16();
3906            _3ewg->ReadInt16();
3907            ReleaseTime = _3ewg->ReadUint16();
3908            _3ewg->ReadInt16();
3909            KeyRange.low = _3ewg->ReadUint8();
3910            KeyRange.high = _3ewg->ReadUint8();
3911            _3ewg->SetPos(64);
3912            ReleaseTriggerKey = _3ewg->ReadUint8();
3913            AltSustain1Key = _3ewg->ReadUint8();
3914            AltSustain2Key = _3ewg->ReadUint8();
3915        }
3916    
3917        MidiRuleLegato::MidiRuleLegato() :
3918            LegatoSamples(12),
3919            BypassUseController(false),
3920            BypassKey(0),
3921            BypassController(1),
3922            ThresholdTime(20),
3923            ReleaseTime(20),
3924            ReleaseTriggerKey(0),
3925            AltSustain1Key(0),
3926            AltSustain2Key(0)
3927        {
3928            KeyRange.low = KeyRange.high = 0;
3929        }
3930    
3931        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3932            pData[32] = 0;
3933            pData[33] = 16;
3934            pData[36] = LegatoSamples;
3935            pData[40] = BypassUseController;
3936            pData[41] = BypassKey;
3937            pData[42] = BypassController;
3938            store16(&pData[43], ThresholdTime);
3939            store16(&pData[47], ReleaseTime);
3940            pData[51] = KeyRange.low;
3941            pData[52] = KeyRange.high;
3942            pData[64] = ReleaseTriggerKey;
3943            pData[65] = AltSustain1Key;
3944            pData[66] = AltSustain2Key;
3945        }
3946    
3947        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3948            _3ewg->SetPos(36);
3949            Articulations = _3ewg->ReadUint8();
3950            int flags = _3ewg->ReadUint8();
3951            Polyphonic = flags & 8;
3952            Chained = flags & 4;
3953            Selector = (flags & 2) ? selector_controller :
3954                (flags & 1) ? selector_key_switch : selector_none;
3955            Patterns = _3ewg->ReadUint8();
3956            _3ewg->ReadUint8(); // chosen row
3957            _3ewg->ReadUint8(); // unknown
3958            _3ewg->ReadUint8(); // unknown
3959            _3ewg->ReadUint8(); // unknown
3960            KeySwitchRange.low = _3ewg->ReadUint8();
3961            KeySwitchRange.high = _3ewg->ReadUint8();
3962            Controller = _3ewg->ReadUint8();
3963            PlayRange.low = _3ewg->ReadUint8();
3964            PlayRange.high = _3ewg->ReadUint8();
3965    
3966            int n = std::min(int(Articulations), 32);
3967            for (int i = 0 ; i < n ; i++) {
3968                _3ewg->ReadString(pArticulations[i], 32);
3969            }
3970            _3ewg->SetPos(1072);
3971            n = std::min(int(Patterns), 32);
3972            for (int i = 0 ; i < n ; i++) {
3973                _3ewg->ReadString(pPatterns[i].Name, 16);
3974                pPatterns[i].Size = _3ewg->ReadUint8();
3975                _3ewg->Read(&pPatterns[i][0], 1, 32);
3976            }
3977        }
3978    
3979        MidiRuleAlternator::MidiRuleAlternator() :
3980            Articulations(0),
3981            Patterns(0),
3982            Selector(selector_none),
3983            Controller(0),
3984            Polyphonic(false),
3985            Chained(false)
3986        {
3987            PlayRange.low = PlayRange.high = 0;
3988            KeySwitchRange.low = KeySwitchRange.high = 0;
3989        }
3990    
3991        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3992            pData[32] = 3;
3993            pData[33] = 16;
3994            pData[36] = Articulations;
3995            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3996                (Selector == selector_controller ? 2 :
3997                 (Selector == selector_key_switch ? 1 : 0));
3998            pData[38] = Patterns;
3999    
4000            pData[43] = KeySwitchRange.low;
4001            pData[44] = KeySwitchRange.high;
4002            pData[45] = Controller;
4003            pData[46] = PlayRange.low;
4004            pData[47] = PlayRange.high;
4005    
4006            char* str = reinterpret_cast<char*>(pData);
4007            int pos = 48;
4008            int n = std::min(int(Articulations), 32);
4009            for (int i = 0 ; i < n ; i++, pos += 32) {
4010                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4011            }
4012    
4013            pos = 1072;
4014            n = std::min(int(Patterns), 32);
4015            for (int i = 0 ; i < n ; i++, pos += 49) {
4016                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4017                pData[pos + 16] = pPatterns[i].Size;
4018                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4019            }
4020        }
4021    
4022  // *************** Instrument ***************  // *************** Instrument ***************
4023  // *  // *
4024    
4025      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) {
4026            static const DLS::Info::string_length_t fixedStringLengths[] = {
4027                { CHUNK_ID_INAM, 64 },
4028                { CHUNK_ID_ISFT, 12 },
4029                { 0, 0 }
4030            };
4031            pInfo->SetFixedStringLengths(fixedStringLengths);
4032    
4033          // Initialization          // Initialization
4034          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4035          RegionIndex = -1;          EffectSend = 0;
4036            Attenuation = 0;
4037            FineTune = 0;
4038            PitchbendRange = 0;
4039            PianoReleaseMode = false;
4040            DimensionKeyRange.low = 0;
4041            DimensionKeyRange.high = 0;
4042            pMidiRules = new MidiRule*[3];
4043            pMidiRules[0] = NULL;
4044    
4045          // Loading          // Loading
4046          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1662  namespace { Line 4055  namespace {
4055                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4056                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4057                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4058    
4059                    if (_3ewg->GetSize() > 32) {
4060                        // read MIDI rules
4061                        int i = 0;
4062                        _3ewg->SetPos(32);
4063                        uint8_t id1 = _3ewg->ReadUint8();
4064                        uint8_t id2 = _3ewg->ReadUint8();
4065    
4066                        if (id2 == 16) {
4067                            if (id1 == 4) {
4068                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4069                            } else if (id1 == 0) {
4070                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4071                            } else if (id1 == 3) {
4072                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4073                            } else {
4074                                pMidiRules[i++] = new MidiRuleUnknown;
4075                            }
4076                        }
4077                        else if (id1 != 0 || id2 != 0) {
4078                            pMidiRules[i++] = new MidiRuleUnknown;
4079                        }
4080                        //TODO: all the other types of rules
4081    
4082                        pMidiRules[i] = NULL;
4083                    }
4084              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
4085          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
4086    
4087          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          if (pFile->GetAutoLoad()) {
4088          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");              if (!pRegions) pRegions = new RegionList;
4089          pRegions = new Region*[Regions];              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4090          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              if (lrgn) {
4091          RIFF::List* rgn = lrgn->GetFirstSubList();                  RIFF::List* rgn = lrgn->GetFirstSubList();
4092          unsigned int iRegion = 0;                  while (rgn) {
4093          while (rgn) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4094              if (rgn->GetListType() == LIST_TYPE_RGN) {                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4095                  __notify_progress(pProgress, (float) iRegion / (float) Regions);                          pRegions->push_back(new Region(this, rgn));
4096                  pRegions[iRegion] = new Region(this, rgn);                      }
4097                  iRegion++;                      rgn = lrgn->GetNextSubList();
4098              }                  }
4099              rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
4100          }                  UpdateRegionKeyTable();
   
         // Creating Region Key Table for fast lookup  
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
4101              }              }
4102          }          }
4103    
4104          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4105      }      }
4106    
4107        void Instrument::UpdateRegionKeyTable() {
4108            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4109            RegionList::iterator iter = pRegions->begin();
4110            RegionList::iterator end  = pRegions->end();
4111            for (; iter != end; ++iter) {
4112                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
4113                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
4114                    RegionKeyTable[iKey] = pRegion;
4115                }
4116            }
4117        }
4118    
4119      Instrument::~Instrument() {      Instrument::~Instrument() {
4120          for (uint i = 0; i < Regions; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
4121              if (pRegions) {              delete pMidiRules[i];
4122                  if (pRegions[i]) delete (pRegions[i]);          }
4123            delete[] pMidiRules;
4124        }
4125    
4126        /**
4127         * Apply Instrument with all its Regions to the respective RIFF chunks.
4128         * You have to call File::Save() to make changes persistent.
4129         *
4130         * Usually there is absolutely no need to call this method explicitly.
4131         * It will be called automatically when File::Save() was called.
4132         *
4133         * @throws gig::Exception if samples cannot be dereferenced
4134         */
4135        void Instrument::UpdateChunks() {
4136            // first update base classes' chunks
4137            DLS::Instrument::UpdateChunks();
4138    
4139            // update Regions' chunks
4140            {
4141                RegionList::iterator iter = pRegions->begin();
4142                RegionList::iterator end  = pRegions->end();
4143                for (; iter != end; ++iter)
4144                    (*iter)->UpdateChunks();
4145            }
4146    
4147            // make sure 'lart' RIFF list chunk exists
4148            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
4149            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4150            // make sure '3ewg' RIFF chunk exists
4151            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4152            if (!_3ewg)  {
4153                File* pFile = (File*) GetParent();
4154    
4155                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4156                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4157                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4158                memset(_3ewg->LoadChunkData(), 0, size);
4159            }
4160            // update '3ewg' RIFF chunk
4161            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4162            store16(&pData[0], EffectSend);
4163            store32(&pData[2], Attenuation);
4164            store16(&pData[6], FineTune);
4165            store16(&pData[8], PitchbendRange);
4166            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4167                                        DimensionKeyRange.low << 1;
4168            pData[10] = dimkeystart;
4169            pData[11] = DimensionKeyRange.high;
4170    
4171            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4172                pData[32] = 0;
4173                pData[33] = 0;
4174            } else {
4175                for (int i = 0 ; pMidiRules[i] ; i++) {
4176                    pMidiRules[i]->UpdateChunks(pData);
4177              }              }
4178          }          }
         if (pRegions) delete[] pRegions;  
4179      }      }
4180    
4181      /**      /**
# Line 1709  namespace { Line 4186  namespace {
4186       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4187       */       */
4188      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4189          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4190          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4191    
4192          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
4193              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
4194                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1726  namespace { Line 4204  namespace {
4204       * @see      GetNextRegion()       * @see      GetNextRegion()
4205       */       */
4206      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
4207          if (!Regions) return NULL;          if (!pRegions) return NULL;
4208          RegionIndex = 1;          RegionsIterator = pRegions->begin();
4209          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4210      }      }
4211    
4212      /**      /**
# Line 1740  namespace { Line 4218  namespace {
4218       * @see      GetFirstRegion()       * @see      GetFirstRegion()
4219       */       */
4220      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
4221          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
4222          return pRegions[RegionIndex++];          RegionsIterator++;
4223            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
4224        }
4225    
4226        Region* Instrument::AddRegion() {
4227            // create new Region object (and its RIFF chunks)
4228            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
4229            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
4230            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4231            Region* pNewRegion = new Region(this, rgn);
4232            pRegions->push_back(pNewRegion);
4233            Regions = pRegions->size();
4234            // update Region key table for fast lookup
4235            UpdateRegionKeyTable();
4236            // done
4237            return pNewRegion;
4238        }
4239    
4240        void Instrument::DeleteRegion(Region* pRegion) {
4241            if (!pRegions) return;
4242            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
4243            // update Region key table for fast lookup
4244            UpdateRegionKeyTable();
4245        }
4246    
4247        /**
4248         * Returns a MIDI rule of the instrument.
4249         *
4250         * The list of MIDI rules, at least in gig v3, always contains at
4251         * most two rules. The second rule can only be the DEF filter
4252         * (which currently isn't supported by libgig).
4253         *
4254         * @param i - MIDI rule number
4255         * @returns   pointer address to MIDI rule number i or NULL if there is none
4256         */
4257        MidiRule* Instrument::GetMidiRule(int i) {
4258            return pMidiRules[i];
4259        }
4260    
4261        /**
4262         * Adds the "controller trigger" MIDI rule to the instrument.
4263         *
4264         * @returns the new MIDI rule
4265         */
4266        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4267            delete pMidiRules[0];
4268            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4269            pMidiRules[0] = r;
4270            pMidiRules[1] = 0;
4271            return r;
4272        }
4273    
4274        /**
4275         * Adds the legato MIDI rule to the instrument.
4276         *
4277         * @returns the new MIDI rule
4278         */
4279        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4280            delete pMidiRules[0];
4281            MidiRuleLegato* r = new MidiRuleLegato;
4282            pMidiRules[0] = r;
4283            pMidiRules[1] = 0;
4284            return r;
4285        }
4286    
4287        /**
4288         * Adds the alternator MIDI rule to the instrument.
4289         *
4290         * @returns the new MIDI rule
4291         */
4292        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4293            delete pMidiRules[0];
4294            MidiRuleAlternator* r = new MidiRuleAlternator;
4295            pMidiRules[0] = r;
4296            pMidiRules[1] = 0;
4297            return r;
4298        }
4299    
4300        /**
4301         * Deletes a MIDI rule from the instrument.
4302         *
4303         * @param i - MIDI rule number
4304         */
4305        void Instrument::DeleteMidiRule(int i) {
4306            delete pMidiRules[i];
4307            pMidiRules[i] = 0;
4308        }
4309    
4310        /**
4311         * Make a (semi) deep copy of the Instrument object given by @a orig
4312         * and assign it to this object.
4313         *
4314         * Note that all sample pointers referenced by @a orig are simply copied as
4315         * memory address. Thus the respective samples are shared, not duplicated!
4316         *
4317         * @param orig - original Instrument object to be copied from
4318         */
4319        void Instrument::CopyAssign(const Instrument* orig) {
4320            CopyAssign(orig, NULL);
4321        }
4322            
4323        /**
4324         * Make a (semi) deep copy of the Instrument object given by @a orig
4325         * and assign it to this object.
4326         *
4327         * @param orig - original Instrument object to be copied from
4328         * @param mSamples - crosslink map between the foreign file's samples and
4329         *                   this file's samples
4330         */
4331        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4332            // handle base class
4333            // (without copying DLS region stuff)
4334            DLS::Instrument::CopyAssignCore(orig);
4335            
4336            // handle own member variables
4337            Attenuation = orig->Attenuation;
4338            EffectSend = orig->EffectSend;
4339            FineTune = orig->FineTune;
4340            PitchbendRange = orig->PitchbendRange;
4341            PianoReleaseMode = orig->PianoReleaseMode;
4342            DimensionKeyRange = orig->DimensionKeyRange;
4343            
4344            // free old midi rules
4345            for (int i = 0 ; pMidiRules[i] ; i++) {
4346                delete pMidiRules[i];
4347            }
4348            //TODO: MIDI rule copying
4349            pMidiRules[0] = NULL;
4350            
4351            // delete all old regions
4352            while (Regions) DeleteRegion(GetFirstRegion());
4353            // create new regions and copy them from original
4354            {
4355                RegionList::const_iterator it = orig->pRegions->begin();
4356                for (int i = 0; i < orig->Regions; ++i, ++it) {
4357                    Region* dstRgn = AddRegion();
4358                    //NOTE: Region does semi-deep copy !
4359                    dstRgn->CopyAssign(
4360                        static_cast<gig::Region*>(*it),
4361                        mSamples
4362                    );
4363                }
4364            }
4365    
4366            UpdateRegionKeyTable();
4367        }
4368    
4369    
4370    // *************** Group ***************
4371    // *
4372    
4373        /** @brief Constructor.
4374         *
4375         * @param file   - pointer to the gig::File object
4376         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
4377         *                 NULL if this is a new Group
4378         */
4379        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
4380            pFile      = file;
4381            pNameChunk = ck3gnm;
4382            ::LoadString(pNameChunk, Name);
4383        }
4384    
4385        Group::~Group() {
4386            // remove the chunk associated with this group (if any)
4387            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
4388        }
4389    
4390        /** @brief Update chunks with current group settings.
4391         *
4392         * Apply current Group field values to the respective chunks. You have
4393         * to call File::Save() to make changes persistent.
4394         *
4395         * Usually there is absolutely no need to call this method explicitly.
4396         * It will be called automatically when File::Save() was called.
4397         */
4398        void Group::UpdateChunks() {
4399            // make sure <3gri> and <3gnl> list chunks exist
4400            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
4401            if (!_3gri) {
4402                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
4403                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4404            }
4405            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4406            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4407    
4408            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
4409                // v3 has a fixed list of 128 strings, find a free one
4410                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
4411                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
4412                        pNameChunk = ck;
4413                        break;
4414                    }
4415                }
4416            }
4417    
4418            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
4419            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
4420        }
4421    
4422        /**
4423         * Returns the first Sample of this Group. You have to call this method
4424         * once before you use GetNextSample().
4425         *
4426         * <b>Notice:</b> this method might block for a long time, in case the
4427         * samples of this .gig file were not scanned yet
4428         *
4429         * @returns  pointer address to first Sample or NULL if there is none
4430         *           applied to this Group
4431         * @see      GetNextSample()
4432         */
4433        Sample* Group::GetFirstSample() {
4434            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4435            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
4436                if (pSample->GetGroup() == this) return pSample;
4437            }
4438            return NULL;
4439        }
4440    
4441        /**
4442         * Returns the next Sample of the Group. You have to call
4443         * GetFirstSample() once before you can use this method. By calling this
4444         * method multiple times it iterates through the Samples assigned to
4445         * this Group.
4446         *
4447         * @returns  pointer address to the next Sample of this Group or NULL if
4448         *           end reached
4449         * @see      GetFirstSample()
4450         */
4451        Sample* Group::GetNextSample() {
4452            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
4453            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
4454                if (pSample->GetGroup() == this) return pSample;
4455            }
4456            return NULL;
4457        }
4458    
4459        /**
4460         * Move Sample given by \a pSample from another Group to this Group.
4461         */
4462        void Group::AddSample(Sample* pSample) {
4463            pSample->pGroup = this;
4464        }
4465    
4466        /**
4467         * Move all members of this group to another group (preferably the 1st
4468         * one except this). This method is called explicitly by
4469         * File::DeleteGroup() thus when a Group was deleted. This code was
4470         * intentionally not placed in the destructor!
4471         */
4472        void Group::MoveAll() {
4473            // get "that" other group first
4474            Group* pOtherGroup = NULL;
4475            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
4476                if (pOtherGroup != this) break;
4477            }
4478            if (!pOtherGroup) throw Exception(
4479                "Could not move samples to another group, since there is no "
4480                "other Group. This is a bug, report it!"
4481            );
4482            // now move all samples of this group to the other group
4483            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4484                pOtherGroup->AddSample(pSample);
4485            }
4486      }      }
4487    
4488    
# Line 1749  namespace { Line 4490  namespace {
4490  // *************** File ***************  // *************** File ***************
4491  // *  // *
4492    
4493        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
4494        const DLS::version_t File::VERSION_2 = {
4495            0, 2, 19980628 & 0xffff, 19980628 >> 16
4496        };
4497    
4498        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
4499        const DLS::version_t File::VERSION_3 = {
4500            0, 3, 20030331 & 0xffff, 20030331 >> 16
4501        };
4502    
4503        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
4504            { CHUNK_ID_IARL, 256 },
4505            { CHUNK_ID_IART, 128 },
4506            { CHUNK_ID_ICMS, 128 },
4507            { CHUNK_ID_ICMT, 1024 },
4508            { CHUNK_ID_ICOP, 128 },
4509            { CHUNK_ID_ICRD, 128 },
4510            { CHUNK_ID_IENG, 128 },
4511            { CHUNK_ID_IGNR, 128 },
4512            { CHUNK_ID_IKEY, 128 },
4513            { CHUNK_ID_IMED, 128 },
4514            { CHUNK_ID_INAM, 128 },
4515            { CHUNK_ID_IPRD, 128 },
4516            { CHUNK_ID_ISBJ, 128 },
4517            { CHUNK_ID_ISFT, 128 },
4518            { CHUNK_ID_ISRC, 128 },
4519            { CHUNK_ID_ISRF, 128 },
4520            { CHUNK_ID_ITCH, 128 },
4521            { 0, 0 }
4522        };
4523    
4524        File::File() : DLS::File() {
4525            bAutoLoad = true;
4526            *pVersion = VERSION_3;
4527            pGroups = NULL;
4528            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4529            pInfo->ArchivalLocation = String(256, ' ');
4530    
4531            // add some mandatory chunks to get the file chunks in right
4532            // order (INFO chunk will be moved to first position later)
4533            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
4534            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
4535            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
4536    
4537            GenerateDLSID();
4538        }
4539    
4540      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
4541          pSamples     = NULL;          bAutoLoad = true;
4542          pInstruments = NULL;          pGroups = NULL;
4543            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
4544      }      }
4545    
4546      File::~File() {      File::~File() {
4547          // free samples          if (pGroups) {
4548          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
4549              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
4550              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
4551                  delete (*SamplesIterator);                  delete *iter;
4552                  SamplesIterator++;                  ++iter;
4553              }              }
4554              pSamples->clear();              delete pGroups;
4555              delete pSamples;          }
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
             }  
             pInstruments->clear();  
             delete pInstruments;  
         }  
         // free extension files  
         for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)  
             delete *i;  
4556      }      }
4557    
4558      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 1793  namespace { Line 4567  namespace {
4567          SamplesIterator++;          SamplesIterator++;
4568          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
4569      }      }
4570        
4571        /**
4572         * Returns Sample object of @a index.
4573         *
4574         * @returns sample object or NULL if index is out of bounds
4575         */
4576        Sample* File::GetSample(uint index) {
4577            if (!pSamples) LoadSamples();
4578            if (!pSamples) return NULL;
4579            DLS::File::SampleList::iterator it = pSamples->begin();
4580            for (int i = 0; i < index; ++i) {
4581                ++it;
4582                if (it == pSamples->end()) return NULL;
4583            }
4584            if (it == pSamples->end()) return NULL;
4585            return static_cast<gig::Sample*>( *it );
4586        }
4587    
4588        /** @brief Add a new sample.
4589         *
4590         * This will create a new Sample object for the gig file. You have to
4591         * call Save() to make this persistent to the file.
4592         *
4593         * @returns pointer to new Sample object
4594         */
4595        Sample* File::AddSample() {
4596           if (!pSamples) LoadSamples();
4597           __ensureMandatoryChunksExist();
4598           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
4599           // create new Sample object and its respective 'wave' list chunk
4600           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
4601           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
4602    
4603           // add mandatory chunks to get the chunks in right order
4604           wave->AddSubChunk(CHUNK_ID_FMT, 16);
4605           wave->AddSubList(LIST_TYPE_INFO);
4606    
4607           pSamples->push_back(pSample);
4608           return pSample;
4609        }
4610    
4611        /** @brief Delete a sample.
4612         *
4613         * This will delete the given Sample object from the gig file. Any
4614         * references to this sample from Regions and DimensionRegions will be
4615         * removed. You have to call Save() to make this persistent to the file.
4616         *
4617         * @param pSample - sample to delete
4618         * @throws gig::Exception if given sample could not be found
4619         */
4620        void File::DeleteSample(Sample* pSample) {
4621            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
4622            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
4623            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
4624            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
4625            pSamples->erase(iter);
4626            delete pSample;
4627    
4628            SampleList::iterator tmp = SamplesIterator;
4629            // remove all references to the sample
4630            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4631                 instrument = GetNextInstrument()) {
4632                for (Region* region = instrument->GetFirstRegion() ; region ;
4633                     region = instrument->GetNextRegion()) {
4634    
4635                    if (region->GetSample() == pSample) region->SetSample(NULL);
4636    
4637                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
4638                        gig::DimensionRegion *d = region->pDimensionRegions[i];
4639                        if (d->pSample == pSample) d->pSample = NULL;
4640                    }
4641                }
4642            }
4643            SamplesIterator = tmp; // restore iterator
4644        }
4645    
4646        void File::LoadSamples() {
4647            LoadSamples(NULL);
4648        }
4649    
4650      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
4651            // Groups must be loaded before samples, because samples will try
4652            // to resolve the group they belong to
4653            if (!pGroups) LoadGroups();
4654    
4655            if (!pSamples) pSamples = new SampleList;
4656    
4657          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
4658    
4659          // just for progress calculation          // just for progress calculation
# Line 1822  namespace { Line 4681  namespace {
4681                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
4682                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
4683    
                         if (!pSamples) pSamples = new SampleList;  
4684                          unsigned long waveFileOffset = wave->GetFilePos();                          unsigned long waveFileOffset = wave->GetFilePos();
4685                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
4686    
# Line 1839  namespace { Line 4697  namespace {
4697                  name.replace(nameLen, 5, suffix);                  name.replace(nameLen, 5, suffix);
4698                  file = new RIFF::File(name);                  file = new RIFF::File(name);
4699                  ExtensionFiles.push_back(file);                  ExtensionFiles.push_back(file);
4700              }              } else break;
             else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
4701          }          }
4702    
4703          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
# Line 1850  namespace { Line 4707  namespace {
4707          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
4708          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
4709          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
4710          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
4711      }      }
4712    
4713      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
4714          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
4715          InstrumentsIterator++;          InstrumentsIterator++;
4716          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
4717      }      }
4718    
4719      /**      /**
# Line 1874  namespace { Line 4731  namespace {
4731              progress_t subprogress;              progress_t subprogress;
4732              __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
4733              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
4734              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
4735                    GetFirstSample(&subprogress); // now force all samples to be loaded
4736              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
4737    
4738              // instrument loading subtask              // instrument loading subtask
# Line 1889  namespace { Line 4747  namespace {
4747          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
4748          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
4749          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
4750              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
4751              InstrumentsIterator++;              InstrumentsIterator++;
4752          }          }
4753          return NULL;          return NULL;
4754      }      }
4755    
4756        /** @brief Add a new instrument definition.
4757         *
4758         * This will create a new Instrument object for the gig file. You have
4759         * to call Save() to make this persistent to the file.
4760         *
4761         * @returns pointer to new Instrument object
4762         */
4763        Instrument* File::AddInstrument() {
4764           if (!pInstruments) LoadInstruments();
4765           __ensureMandatoryChunksExist();
4766           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4767           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
4768    
4769           // add mandatory chunks to get the chunks in right order
4770           lstInstr->AddSubList(LIST_TYPE_INFO);
4771           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4772    
4773           Instrument* pInstrument = new Instrument(this, lstInstr);
4774           pInstrument->GenerateDLSID();
4775    
4776           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4777    
4778           // this string is needed for the gig to be loadable in GSt:
4779           pInstrument->pInfo->Software = "Endless Wave";
4780    
4781           pInstruments->push_back(pInstrument);
4782           return pInstrument;
4783        }
4784        
4785        /** @brief Add a duplicate of an existing instrument.
4786         *
4787         * Duplicates the instrument definition given by @a orig and adds it
4788         * to this file. This allows in an instrument editor application to
4789         * easily create variations of an instrument, which will be stored in
4790         * the same .gig file, sharing i.e. the same samples.
4791         *
4792         * Note that all sample pointers referenced by @a orig are simply copied as
4793         * memory address. Thus the respective samples are shared, not duplicated!
4794         *
4795         * You have to call Save() to make this persistent to the file.
4796         *
4797         * @param orig - original instrument to be copied
4798         * @returns duplicated copy of the given instrument
4799         */
4800        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4801            Instrument* instr = AddInstrument();
4802            instr->CopyAssign(orig);
4803            return instr;
4804        }
4805        
4806        /** @brief Add content of another existing file.
4807         *
4808         * Duplicates the samples, groups and instruments of the original file
4809         * given by @a pFile and adds them to @c this File. In case @c this File is
4810         * a new one that you haven't saved before, then you have to call
4811         * SetFileName() before calling AddContentOf(), because this method will
4812         * automatically save this file during operation, which is required for
4813         * writing the sample waveform data by disk streaming.
4814         *
4815         * @param pFile - original file whose's content shall be copied from
4816         */
4817        void File::AddContentOf(File* pFile) {
4818            static int iCallCount = -1;
4819            iCallCount++;
4820            std::map<Group*,Group*> mGroups;
4821            std::map<Sample*,Sample*> mSamples;
4822            
4823            // clone sample groups
4824            for (int i = 0; pFile->GetGroup(i); ++i) {
4825                Group* g = AddGroup();
4826                g->Name =
4827                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4828                mGroups[pFile->GetGroup(i)] = g;
4829            }
4830            
4831            // clone samples (not waveform data here yet)
4832            for (int i = 0; pFile->GetSample(i); ++i) {
4833                Sample* s = AddSample();
4834                s->CopyAssignMeta(pFile->GetSample(i));
4835                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4836                mSamples[pFile->GetSample(i)] = s;
4837            }
4838            
4839            //BUG: For some reason this method only works with this additional
4840            //     Save() call in between here.
4841            //
4842            // Important: The correct one of the 2 Save() methods has to be called
4843            // here, depending on whether the file is completely new or has been
4844            // saved to disk already, otherwise it will result in data corruption.
4845            if (pRIFF->IsNew())
4846                Save(GetFileName());
4847            else
4848                Save();
4849            
4850            // clone instruments
4851            // (passing the crosslink table here for the cloned samples)
4852            for (int i = 0; pFile->GetInstrument(i); ++i) {
4853                Instrument* instr = AddInstrument();
4854                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4855            }
4856            
4857            // Mandatory: file needs to be saved to disk at this point, so this
4858            // file has the correct size and data layout for writing the samples'
4859            // waveform data to disk.
4860            Save();
4861            
4862            // clone samples' waveform data
4863            // (using direct read & write disk streaming)
4864            for (int i = 0; pFile->GetSample(i); ++i) {
4865                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4866            }
4867        }
4868    
4869        /** @brief Delete an instrument.
4870         *
4871         * This will delete the given Instrument object from the gig file. You
4872         * have to call Save() to make this persistent to the file.
4873         *
4874         * @param pInstrument - instrument to delete
4875         * @throws gig::Exception if given instrument could not be found
4876         */
4877        void File::DeleteInstrument(Instrument* pInstrument) {
4878            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
4879            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
4880            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
4881            pInstruments->erase(iter);
4882            delete pInstrument;
4883        }
4884    
4885        void File::LoadInstruments() {
4886            LoadInstruments(NULL);
4887        }
4888    
4889      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
4890            if (!pInstruments) pInstruments = new InstrumentList;
4891          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
4892          if (lstInstruments) {          if (lstInstruments) {
4893              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1910  namespace { Line 4902  namespace {
4902                      progress_t subprogress;                      progress_t subprogress;
4903                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
4904    
                     if (!pInstruments) pInstruments = new InstrumentList;  
4905                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
4906    
4907                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1919  namespace { Line 4910  namespace {
4910              }              }
4911              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
4912          }          }
4913          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
4914    
4915        /// Updates the 3crc chunk with the checksum of a sample. The
4916        /// update is done directly to disk, as this method is called
4917        /// after File::Save()
4918        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4919            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4920            if (!_3crc) return;
4921    
4922            // get the index of the sample
4923            int iWaveIndex = -1;
4924            File::SampleList::iterator iter = pSamples->begin();
4925            File::SampleList::iterator end  = pSamples->end();
4926            for (int index = 0; iter != end; ++iter, ++index) {
4927                if (*iter == pSample) {
4928                    iWaveIndex = index;
4929                    break;
4930                }
4931            }
4932            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4933    
4934            // write the CRC-32 checksum to disk
4935            _3crc->SetPos(iWaveIndex * 8);
4936            uint32_t tmp = 1;
4937            _3crc->WriteUint32(&tmp); // unknown, always 1?
4938            _3crc->WriteUint32(&crc);
4939        }
4940    
4941        Group* File::GetFirstGroup() {
4942            if (!pGroups) LoadGroups();
4943            // there must always be at least one group
4944            GroupsIterator = pGroups->begin();
4945            return *GroupsIterator;
4946        }
4947    
4948        Group* File::GetNextGroup() {
4949            if (!pGroups) return NULL;
4950            ++GroupsIterator;
4951            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
4952        }
4953    
4954        /**
4955         * Returns the group with the given index.
4956         *
4957         * @param index - number of the sought group (0..n)
4958         * @returns sought group or NULL if there's no such group
4959         */
4960        Group* File::GetGroup(uint index) {
4961            if (!pGroups) LoadGroups();
4962            GroupsIterator = pGroups->begin();
4963            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
4964                if (i == index) return *GroupsIterator;
4965                ++GroupsIterator;
4966            }
4967            return NULL;
4968        }
4969    
4970        /**
4971         * Returns the group with the given group name.
4972         *
4973         * Note: group names don't have to be unique in the gig format! So there
4974         * can be multiple groups with the same name. This method will simply
4975         * return the first group found with the given name.
4976         *
4977         * @param name - name of the sought group
4978         * @returns sought group or NULL if there's no group with that name
4979         */
4980        Group* File::GetGroup(String name) {
4981            if (!pGroups) LoadGroups();
4982            GroupsIterator = pGroups->begin();
4983            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
4984                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
4985            return NULL;
4986        }
4987    
4988        Group* File::AddGroup() {
4989            if (!pGroups) LoadGroups();
4990            // there must always be at least one group
4991            __ensureMandatoryChunksExist();
4992            Group* pGroup = new Group(this, NULL);
4993            pGroups->push_back(pGroup);
4994            return pGroup;
4995        }
4996    
4997        /** @brief Delete a group and its samples.
4998         *
4999         * This will delete the given Group object and all the samples that
5000         * belong to this group from the gig file. You have to call Save() to
5001         * make this persistent to the file.
5002         *
5003         * @param pGroup - group to delete
5004         * @throws gig::Exception if given group could not be found
5005         */
5006        void File::DeleteGroup(Group* pGroup) {
5007            if (!pGroups) LoadGroups();
5008            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5009            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5010            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5011            // delete all members of this group
5012            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5013                DeleteSample(pSample);
5014            }
5015            // now delete this group object
5016            pGroups->erase(iter);
5017            delete pGroup;
5018        }
5019    
5020        /** @brief Delete a group.
5021         *
5022         * This will delete the given Group object from the gig file. All the
5023         * samples that belong to this group will not be deleted, but instead
5024         * be moved to another group. You have to call Save() to make this
5025         * persistent to the file.
5026         *
5027         * @param pGroup - group to delete
5028         * @throws gig::Exception if given group could not be found
5029         */
5030        void File::DeleteGroupOnly(Group* pGroup) {
5031            if (!pGroups) LoadGroups();
5032            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5033            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5034            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5035            // move all members of this group to another group
5036            pGroup->MoveAll();
5037            pGroups->erase(iter);
5038            delete pGroup;
5039        }
5040    
5041        void File::LoadGroups() {
5042            if (!pGroups) pGroups = new std::list<Group*>;
5043            // try to read defined groups from file
5044            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5045            if (lst3gri) {
5046                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5047                if (lst3gnl) {
5048                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5049                    while (ck) {
5050                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5051                            if (pVersion && pVersion->major == 3 &&
5052                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5053    
5054                            pGroups->push_back(new Group(this, ck));
5055                        }
5056                        ck = lst3gnl->GetNextSubChunk();
5057                    }
5058                }
5059            }
5060            // if there were no group(s), create at least the mandatory default group
5061            if (!pGroups->size()) {
5062                Group* pGroup = new Group(this, NULL);
5063                pGroup->Name = "Default Group";
5064                pGroups->push_back(pGroup);
5065            }
5066        }
5067    
5068        /**
5069         * Apply all the gig file's current instruments, samples, groups and settings
5070         * to the respective RIFF chunks. You have to call Save() to make changes
5071         * persistent.
5072         *
5073         * Usually there is absolutely no need to call this method explicitly.
5074         * It will be called automatically when File::Save() was called.
5075         *
5076         * @throws Exception - on errors
5077         */
5078        void File::UpdateChunks() {
5079            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5080    
5081            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5082    
5083            // first update base class's chunks
5084            DLS::File::UpdateChunks();
5085    
5086            if (newFile) {
5087                // INFO was added by Resource::UpdateChunks - make sure it
5088                // is placed first in file
5089                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
5090                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5091                if (first != info) {
5092                    pRIFF->MoveSubChunk(info, first);
5093                }
5094            }
5095    
5096            // update group's chunks
5097            if (pGroups) {
5098                // make sure '3gri' and '3gnl' list chunks exist
5099                // (before updating the Group chunks)
5100                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5101                if (!_3gri) {
5102                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5103                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5104                }
5105                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5106                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5107    
5108                // v3: make sure the file has 128 3gnm chunks
5109                // (before updating the Group chunks)
5110                if (pVersion && pVersion->major == 3) {
5111                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5112                    for (int i = 0 ; i < 128 ; i++) {
5113                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5114                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5115                    }
5116                }
5117    
5118                std::list<Group*>::iterator iter = pGroups->begin();
5119                std::list<Group*>::iterator end  = pGroups->end();
5120                for (; iter != end; ++iter) {
5121                    (*iter)->UpdateChunks();
5122                }
5123            }
5124    
5125            // update einf chunk
5126    
5127            // The einf chunk contains statistics about the gig file, such
5128            // as the number of regions and samples used by each
5129            // instrument. It is divided in equally sized parts, where the
5130            // first part contains information about the whole gig file,
5131            // and the rest of the parts map to each instrument in the
5132            // file.
5133            //
5134            // At the end of each part there is a bit map of each sample
5135            // in the file, where a set bit means that the sample is used
5136            // by the file/instrument.
5137            //
5138            // Note that there are several fields with unknown use. These
5139            // are set to zero.
5140    
5141            int sublen = pSamples->size() / 8 + 49;
5142            int einfSize = (Instruments + 1) * sublen;
5143    
5144            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5145            if (einf) {
5146                if (einf->GetSize() != einfSize) {
5147                    einf->Resize(einfSize);
5148                    memset(einf->LoadChunkData(), 0, einfSize);
5149                }
5150            } else if (newFile) {
5151                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5152            }
5153            if (einf) {
5154                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5155    
5156                std::map<gig::Sample*,int> sampleMap;
5157                int sampleIdx = 0;
5158                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5159                    sampleMap[pSample] = sampleIdx++;
5160                }
5161    
5162                int totnbusedsamples = 0;
5163                int totnbusedchannels = 0;
5164                int totnbregions = 0;
5165                int totnbdimregions = 0;
5166                int totnbloops = 0;
5167                int instrumentIdx = 0;
5168    
5169                memset(&pData[48], 0, sublen - 48);
5170    
5171                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5172                     instrument = GetNextInstrument()) {
5173                    int nbusedsamples = 0;
5174                    int nbusedchannels = 0;
5175                    int nbdimregions = 0;
5176                    int nbloops = 0;
5177    
5178                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5179    
5180                    for (Region* region = instrument->GetFirstRegion() ; region ;
5181                         region = instrument->GetNextRegion()) {
5182                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
5183                            gig::DimensionRegion *d = region->pDimensionRegions[i];
5184                            if (d->pSample) {
5185                                int sampleIdx = sampleMap[d->pSample];
5186                                int byte = 48 + sampleIdx / 8;
5187                                int bit = 1 << (sampleIdx & 7);
5188                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5189                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5190                                    nbusedsamples++;
5191                                    nbusedchannels += d->pSample->Channels;
5192    
5193                                    if ((pData[byte] & bit) == 0) {
5194                                        pData[byte] |= bit;
5195                                        totnbusedsamples++;
5196                                        totnbusedchannels += d->pSample->Channels;
5197                                    }
5198                                }
5199                            }
5200                            if (d->SampleLoops) nbloops++;
5201                        }
5202                        nbdimregions += region->DimensionRegions;
5203                    }
5204                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5205                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5206                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5207                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5208                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5209                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5210                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5211                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5212                    // next 8 bytes unknown
5213                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5214                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5215                    // next 4 bytes unknown
5216    
5217                    totnbregions += instrument->Regions;
5218                    totnbdimregions += nbdimregions;
5219                    totnbloops += nbloops;
5220                    instrumentIdx++;
5221                }
5222                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5223                // store32(&pData[0], sublen);
5224                store32(&pData[4], totnbusedchannels);
5225                store32(&pData[8], totnbusedsamples);
5226                store32(&pData[12], Instruments);
5227                store32(&pData[16], totnbregions);
5228                store32(&pData[20], totnbdimregions);
5229                store32(&pData[24], totnbloops);
5230                // next 8 bytes unknown
5231                // next 4 bytes unknown, not always 0
5232                store32(&pData[40], pSamples->size());
5233                // next 4 bytes unknown
5234            }
5235    
5236            // update 3crc chunk
5237    
5238            // The 3crc chunk contains CRC-32 checksums for the
5239            // samples. The actual checksum values will be filled in
5240            // later, by Sample::Write.
5241    
5242            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5243            if (_3crc) {
5244                _3crc->Resize(pSamples->size() * 8);
5245            } else if (newFile) {
5246                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5247                _3crc->LoadChunkData();
5248    
5249                // the order of einf and 3crc is not the same in v2 and v3
5250                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5251            }
5252        }
5253    
5254        /**
5255         * Enable / disable automatic loading. By default this properyt is
5256         * enabled and all informations are loaded automatically. However
5257         * loading all Regions, DimensionRegions and especially samples might
5258         * take a long time for large .gig files, and sometimes one might only
5259         * be interested in retrieving very superficial informations like the
5260         * amount of instruments and their names. In this case one might disable
5261         * automatic loading to avoid very slow response times.
5262         *
5263         * @e CAUTION: by disabling this property many pointers (i.e. sample
5264         * references) and informations will have invalid or even undefined
5265         * data! This feature is currently only intended for retrieving very
5266         * superficial informations in a very fast way. Don't use it to retrieve
5267         * details like synthesis informations or even to modify .gig files!
5268         */
5269        void File::SetAutoLoad(bool b) {
5270            bAutoLoad = b;
5271        }
5272    
5273        /**
5274         * Returns whether automatic loading is enabled.
5275         * @see SetAutoLoad()
5276         */
5277        bool File::GetAutoLoad() {
5278            return bAutoLoad;
5279      }      }
5280    
5281    

Legend:
Removed from v.780  
changed lines
  Added in v.2555

  ViewVC Help
Powered by ViewVC