/[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 1247 by persson, Fri Jun 22 09:59:57 2007 UTC revision 2484 by schoenebeck, Tue Dec 31 00:13:20 2013 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2013 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    
# Line 255  namespace { Line 256  namespace {
256    
257    
258    
259    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
260    // *
261    
262        static uint32_t* __initCRCTable() {
263            static uint32_t res[256];
264    
265            for (int i = 0 ; i < 256 ; i++) {
266                uint32_t c = i;
267                for (int j = 0 ; j < 8 ; j++) {
268                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269                }
270                res[i] = c;
271            }
272            return res;
273        }
274    
275        static const uint32_t* __CRCTable = __initCRCTable();
276    
277        /**
278         * Initialize a CRC variable.
279         *
280         * @param crc - variable to be initialized
281         */
282        inline static void __resetCRC(uint32_t& crc) {
283            crc = 0xffffffff;
284        }
285    
286        /**
287         * Used to calculate checksums of the sample data in a gig file. The
288         * checksums are stored in the 3crc chunk of the gig file and
289         * automatically updated when a sample is written with Sample::Write().
290         *
291         * One should call __resetCRC() to initialize the CRC variable to be
292         * used before calling this function the first time.
293         *
294         * After initializing the CRC variable one can call this function
295         * arbitrary times, i.e. to split the overall CRC calculation into
296         * steps.
297         *
298         * Once the whole data was processed by __calculateCRC(), one should
299         * call __encodeCRC() to get the final CRC result.
300         *
301         * @param buf     - pointer to data the CRC shall be calculated of
302         * @param bufSize - size of the data to be processed
303         * @param crc     - variable the CRC sum shall be stored to
304         */
305        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306            for (int i = 0 ; i < bufSize ; i++) {
307                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308            }
309        }
310    
311        /**
312         * Returns the final CRC result.
313         *
314         * @param crc - variable previously passed to __calculateCRC()
315         */
316        inline static uint32_t __encodeCRC(const uint32_t& crc) {
317            return crc ^ 0xffffffff;
318        }
319    
320    
321    
322  // *************** Other Internal functions  ***************  // *************** Other Internal functions  ***************
323  // *  // *
324    
# Line 278  namespace { Line 342  namespace {
342    
343    
344    
 // *************** CRC ***************  
 // *  
   
     const uint32_t* CRC::table(initTable());  
   
     uint32_t* CRC::initTable() {  
         uint32_t* res = new uint32_t[256];  
   
         for (int i = 0 ; i < 256 ; i++) {  
             uint32_t c = i;  
             for (int j = 0 ; j < 8 ; j++) {  
                 c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;  
             }  
             res[i] = c;  
         }  
         return res;  
     }  
   
   
   
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
# Line 323  namespace { Line 367  namespace {
367       *                         is located, 0 otherwise       *                         is located, 0 otherwise
368       */       */
369      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
370          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
371              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
372              { 0, 0 }              { 0, 0 }
373          };          };
374          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
375          Instances++;          Instances++;
376          FileNo = fileNo;          FileNo = fileNo;
377    
378            __resetCRC(crc);
379    
380          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381          if (pCk3gix) {          if (pCk3gix) {
382              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 408  namespace { Line 454  namespace {
454      }      }
455    
456      /**      /**
457         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518            }
519            pOrig->SetPos(restorePos);
520            delete [] buf;
521        }
522    
523        /**
524       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
525       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
526       *       *
# Line 468  namespace { Line 581  namespace {
581          // update '3gix' chunk          // update '3gix' chunk
582          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
583          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
584    
585            // if the library user toggled the "Compressed" attribute from true to
586            // false, then the EWAV chunk associated with compressed samples needs
587            // to be deleted
588            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
589            if (ewav && !Compressed) {
590                pWaveList->DeleteSubChunk(ewav);
591            }
592      }      }
593    
594      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 631  namespace { Line 752  namespace {
752          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
753          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
754          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
755            SetPos(0); // reset read position to begin of sample
756          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
757          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
758          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 668  namespace { Line 790  namespace {
790          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
791          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
792          RAMCache.Size   = 0;          RAMCache.Size   = 0;
793            RAMCache.NullExtensionSize = 0;
794      }      }
795    
796      /** @brief Resize sample.      /** @brief Resize sample.
# Line 760  namespace { Line 883  namespace {
883      /**      /**
884       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
885       */       */
886      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
887          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
888          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
889      }      }
# Line 862  namespace { Line 985  namespace {
985                                  }                                  }
986    
987                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
988                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
989                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
990                              }                              }
991                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
992                          break;                          break;
# Line 1152  namespace { Line 1276  namespace {
1276       *       *
1277       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1278       *       *
1279         * For 16 bit samples, the data in the source buffer should be
1280         * int16_t (using native endianness). For 24 bit, the buffer
1281         * should contain three bytes per sample, little-endian.
1282         *
1283       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1284       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1285       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1164  namespace { Line 1292  namespace {
1292          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
1293          // checksum calculator          // checksum calculator
1294          if (pCkData->GetPos() == 0) {          if (pCkData->GetPos() == 0) {
1295              crc.reset();              __resetCRC(crc);
1296          }          }
1297          unsigned long res = DLS::Sample::Write(pBuffer, SampleCount);          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1298          crc.update((unsigned char *)pBuffer, SampleCount * FrameSize);          unsigned long res;
1299            if (BitDepth == 24) {
1300                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1301            } else { // 16 bit
1302                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1303                                    : pCkData->Write(pBuffer, SampleCount, 2);
1304            }
1305            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1306    
1307          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1308          // file          // file
1309          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1310              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1311              pFile->SetSampleChecksum(this, crc.getValue());              pFile->SetSampleChecksum(this, __encodeCRC(crc));
1312          }          }
1313          return res;          return res;
1314      }      }
# Line 1251  namespace { Line 1386  namespace {
1386      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1387      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1388    
1389      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1390          Instances++;          Instances++;
1391    
1392          pSample = NULL;          pSample = NULL;
1393            pRegion = pParent;
1394    
1395          if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);          if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1396          else memset(&Crossfade, 0, 4);          else memset(&Crossfade, 0, 4);
# Line 1372  namespace { Line 1508  namespace {
1508                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1509              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1510              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1511                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1512              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1513              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1514              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1500  namespace { Line 1636  namespace {
1636                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1637                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1638    
1639          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1640          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1641                                        ReleaseVelocityResponseDepth
1642                                    );
1643    
1644            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1645                                                          VCFVelocityDynamicRange,
1646                                                          VCFVelocityScale,
1647                                                          VCFCutoffController);
1648    
1649          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1650          // velocity response curves for release time are not used even          VelocityTable = 0;
1651          // if specified, instead another curve is chosen.      }
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_nonlinear;  
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1652    
1653          curveType = VCFVelocityCurve;      /*
1654          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1655         * another DimensionRegion
1656         */
1657        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1658            Instances++;
1659            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1660            *this = src; // default memberwise shallow copy of all parameters
1661            pParentList = _3ewl; // restore the chunk pointer
1662    
1663            // deep copy of owned structures
1664            if (src.VelocityTable) {
1665                VelocityTable = new uint8_t[128];
1666                for (int k = 0 ; k < 128 ; k++)
1667                    VelocityTable[k] = src.VelocityTable[k];
1668            }
1669            if (src.pSampleLoops) {
1670                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1671                for (int k = 0 ; k < src.SampleLoops ; k++)
1672                    pSampleLoops[k] = src.pSampleLoops[k];
1673            }
1674        }
1675        
1676        /**
1677         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1678         * and assign it to this object.
1679         *
1680         * Note that all sample pointers referenced by @a orig are simply copied as
1681         * memory address. Thus the respective samples are shared, not duplicated!
1682         *
1683         * @param orig - original DimensionRegion object to be copied from
1684         */
1685        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1686            CopyAssign(orig, NULL);
1687        }
1688    
1689          // even stranger GSt: two of the velocity response curves for      /**
1690          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1691          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1692          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1693              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1694              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1695              depth = 5;       *                   this file's samples
1696         */
1697        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1698            // delete all allocated data first
1699            if (VelocityTable) delete [] VelocityTable;
1700            if (pSampleLoops) delete [] pSampleLoops;
1701            
1702            // backup parent list pointer
1703            RIFF::List* p = pParentList;
1704            
1705            gig::Sample* pOriginalSample = pSample;
1706            gig::Region* pOriginalRegion = pRegion;
1707            
1708            //NOTE: copy code copied from assignment constructor above, see comment there as well
1709            
1710            *this = *orig; // default memberwise shallow copy of all parameters
1711            pParentList = p; // restore the chunk pointer
1712            
1713            // only take the raw sample reference & parent region reference if the
1714            // two DimensionRegion objects are part of the same file
1715            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1716                pRegion = pOriginalRegion;
1717                pSample = pOriginalSample;
1718            }
1719            
1720            if (mSamples && mSamples->count(orig->pSample)) {
1721                pSample = mSamples->find(orig->pSample)->second;
1722            }
1723    
1724            // deep copy of owned structures
1725            if (orig->VelocityTable) {
1726                VelocityTable = new uint8_t[128];
1727                for (int k = 0 ; k < 128 ; k++)
1728                    VelocityTable[k] = orig->VelocityTable[k];
1729            }
1730            if (orig->pSampleLoops) {
1731                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1732                for (int k = 0 ; k < orig->SampleLoops ; k++)
1733                    pSampleLoops[k] = orig->pSampleLoops[k];
1734          }          }
1735          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1736    
1737        /**
1738         * Updates the respective member variable and updates @c SampleAttenuation
1739         * which depends on this value.
1740         */
1741        void DimensionRegion::SetGain(int32_t gain) {
1742            DLS::Sampler::SetGain(gain);
1743          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1744      }      }
1745    
1746      /**      /**
# Line 1551  namespace { Line 1763  namespace {
1763    
1764          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1765          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1766          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1767                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1768                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1769                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1770            }
1771          pData = (uint8_t*) _3ewa->LoadChunkData();          pData = (uint8_t*) _3ewa->LoadChunkData();
1772    
1773          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
# Line 1598  namespace { Line 1814  namespace {
1814          pData[44] = eg1ctl;          pData[44] = eg1ctl;
1815    
1816          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1817              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1818              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1819              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1820              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
# Line 1608  namespace { Line 1824  namespace {
1824          pData[46] = eg2ctl;          pData[46] = eg2ctl;
1825    
1826          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1827              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1828              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1829              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1830              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
# Line 1758  namespace { Line 1974  namespace {
1974          }          }
1975    
1976          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1977                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1978          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1979    
1980          // next 2 bytes unknown          // next 2 bytes unknown
1981    
# Line 1786  namespace { Line 2002  namespace {
2002          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2003          pData[131] = eg1hold;          pData[131] = eg1hold;
2004    
2005          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2006                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2007          pData[132] = vcfcutoff;          pData[132] = vcfcutoff;
2008    
2009          pData[133] = VCFCutoffController;          pData[133] = VCFCutoffController;
2010    
2011          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2012                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2013          pData[134] = vcfvelscale;          pData[134] = vcfvelscale;
2014    
2015          // next byte unknown          // next byte unknown
2016    
2017          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2018                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2019          pData[136] = vcfresonance;          pData[136] = vcfresonance;
2020    
2021          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2022                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2023          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2024    
2025          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2026                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2027          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2028    
# Line 1818  namespace { Line 2034  namespace {
2034          }          }
2035      }      }
2036    
2037        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2038            curve_type_t curveType = releaseVelocityResponseCurve;
2039            uint8_t depth = releaseVelocityResponseDepth;
2040            // this models a strange behaviour or bug in GSt: two of the
2041            // velocity response curves for release time are not used even
2042            // if specified, instead another curve is chosen.
2043            if ((curveType == curve_type_nonlinear && depth == 0) ||
2044                (curveType == curve_type_special   && depth == 4)) {
2045                curveType = curve_type_nonlinear;
2046                depth = 3;
2047            }
2048            return GetVelocityTable(curveType, depth, 0);
2049        }
2050    
2051        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2052                                                        uint8_t vcfVelocityDynamicRange,
2053                                                        uint8_t vcfVelocityScale,
2054                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2055        {
2056            curve_type_t curveType = vcfVelocityCurve;
2057            uint8_t depth = vcfVelocityDynamicRange;
2058            // even stranger GSt: two of the velocity response curves for
2059            // filter cutoff are not used, instead another special curve
2060            // is chosen. This curve is not used anywhere else.
2061            if ((curveType == curve_type_nonlinear && depth == 0) ||
2062                (curveType == curve_type_special   && depth == 4)) {
2063                curveType = curve_type_special;
2064                depth = 5;
2065            }
2066            return GetVelocityTable(curveType, depth,
2067                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2068                                        ? vcfVelocityScale : 0);
2069        }
2070    
2071      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2072      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2073      {      {
# Line 1833  namespace { Line 2083  namespace {
2083          return table;          return table;
2084      }      }
2085    
2086        Region* DimensionRegion::GetParent() const {
2087            return pRegion;
2088        }
2089    
2090      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2091          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2092          switch (EncodedController) {          switch (EncodedController) {
# Line 2086  namespace { Line 2340  namespace {
2340          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2341      }      }
2342    
2343        /**
2344         * Updates the respective member variable and the lookup table / cache
2345         * that depends on this value.
2346         */
2347        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2348            pVelocityAttenuationTable =
2349                GetVelocityTable(
2350                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2351                );
2352            VelocityResponseCurve = curve;
2353        }
2354    
2355        /**
2356         * Updates the respective member variable and the lookup table / cache
2357         * that depends on this value.
2358         */
2359        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2360            pVelocityAttenuationTable =
2361                GetVelocityTable(
2362                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2363                );
2364            VelocityResponseDepth = depth;
2365        }
2366    
2367        /**
2368         * Updates the respective member variable and the lookup table / cache
2369         * that depends on this value.
2370         */
2371        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2372            pVelocityAttenuationTable =
2373                GetVelocityTable(
2374                    VelocityResponseCurve, VelocityResponseDepth, scaling
2375                );
2376            VelocityResponseCurveScaling = scaling;
2377        }
2378    
2379        /**
2380         * Updates the respective member variable and the lookup table / cache
2381         * that depends on this value.
2382         */
2383        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2384            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2385            ReleaseVelocityResponseCurve = curve;
2386        }
2387    
2388        /**
2389         * Updates the respective member variable and the lookup table / cache
2390         * that depends on this value.
2391         */
2392        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2393            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2394            ReleaseVelocityResponseDepth = depth;
2395        }
2396    
2397        /**
2398         * Updates the respective member variable and the lookup table / cache
2399         * that depends on this value.
2400         */
2401        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2402            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2403            VCFCutoffController = controller;
2404        }
2405    
2406        /**
2407         * Updates the respective member variable and the lookup table / cache
2408         * that depends on this value.
2409         */
2410        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2411            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2412            VCFVelocityCurve = curve;
2413        }
2414    
2415        /**
2416         * Updates the respective member variable and the lookup table / cache
2417         * that depends on this value.
2418         */
2419        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2420            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2421            VCFVelocityDynamicRange = range;
2422        }
2423    
2424        /**
2425         * Updates the respective member variable and the lookup table / cache
2426         * that depends on this value.
2427         */
2428        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2429            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2430            VCFVelocityScale = scaling;
2431        }
2432    
2433      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) {
2434    
2435          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2169  namespace { Line 2513  namespace {
2513    
2514          // Actual Loading          // Actual Loading
2515    
2516            if (!file->GetAutoLoad()) return;
2517    
2518          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2519    
2520          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2212  namespace { Line 2558  namespace {
2558              else              else
2559                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2560    
2561              // load sample references              // load sample references (if auto loading is enabled)
2562              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2563                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2564                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2565                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2566                    }
2567                    GetSample(); // load global region sample reference
2568              }              }
             GetSample(); // load global region sample reference  
2569          } else {          } else {
2570              DimensionRegions = 0;              DimensionRegions = 0;
2571              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2232  namespace { Line 2580  namespace {
2580              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2581              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2582              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2583              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2584              DimensionRegions = 1;              DimensionRegions = 1;
2585          }          }
2586      }      }
# Line 2256  namespace { Line 2604  namespace {
2604          // first update base class's chunks          // first update base class's chunks
2605          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2606    
         File* pFile = (File*) GetParent()->GetParent();  
         bool version3 = pFile->pVersion && pFile->pVersion->major == 3;  
   
2607          // update dimension region's chunks          // update dimension region's chunks
2608          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
2609              DimensionRegion* d = pDimensionRegions[i];              pDimensionRegions[i]->UpdateChunks();
   
             // make sure '3ewa' chunk exists (we need to this before  
             // calling DimensionRegion::UpdateChunks, as  
             // DimensionRegion doesn't know which file version it is)  
             RIFF::Chunk* _3ewa = d->pParentList->GetSubChunk(CHUNK_ID_3EWA);  
             if (!_3ewa) d->pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);  
   
             d->UpdateChunks();  
2610          }          }
2611    
2612            File* pFile = (File*) GetParent()->GetParent();
2613            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2614          const int iMaxDimensions =  version3 ? 8 : 5;          const int iMaxDimensions =  version3 ? 8 : 5;
2615          const int iMaxDimensionRegions = version3 ? 256 : 32;          const int iMaxDimensionRegions = version3 ? 256 : 32;
2616    
# Line 2293  namespace { Line 2632  namespace {
2632          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2633              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2634              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2635              pData[6 + i * 8] = shift;              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2636              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2637              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2638              // next 3 bytes unknown, always zero?              // next 3 bytes unknown, always zero?
# Line 2315  namespace { Line 2654  namespace {
2654                          break;                          break;
2655                      }                      }
2656                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
2657              }              }
2658              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2659          }          }
# Line 2328  namespace { Line 2666  namespace {
2666              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2667              while (_3ewl) {              while (_3ewl) {
2668                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2669                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2670                      dimensionRegionNr++;                      dimensionRegionNr++;
2671                  }                  }
2672                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2337  namespace { Line 2675  namespace {
2675          }          }
2676      }      }
2677    
2678        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2679            // update KeyRange struct and make sure regions are in correct order
2680            DLS::Region::SetKeyRange(Low, High);
2681            // update Region key table for fast lookup
2682            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2683        }
2684    
2685      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
2686          // get velocity dimension's index          // get velocity dimension's index
2687          int veldim = -1;          int veldim = -1;
# Line 2442  namespace { Line 2787  namespace {
2787              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2788                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2789    
2790            // pos is where the new dimension should be placed, normally
2791            // last in list, except for the samplechannel dimension which
2792            // has to be first in list
2793            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2794            int bitpos = 0;
2795            for (int i = 0 ; i < pos ; i++)
2796                bitpos += pDimensionDefinitions[i].bits;
2797    
2798            // make room for the new dimension
2799            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2800            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2801                for (int j = Dimensions ; j > pos ; j--) {
2802                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2803                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2804                }
2805            }
2806    
2807          // assign definition of new dimension          // assign definition of new dimension
2808          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
2809    
2810          // auto correct certain dimension definition fields (where possible)          // auto correct certain dimension definition fields (where possible)
2811          pDimensionDefinitions[Dimensions].split_type  =          pDimensionDefinitions[pos].split_type  =
2812              __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);              __resolveSplitType(pDimensionDefinitions[pos].dimension);
2813          pDimensionDefinitions[Dimensions].zone_size =          pDimensionDefinitions[pos].zone_size =
2814              __resolveZoneSize(pDimensionDefinitions[Dimensions]);              __resolveZoneSize(pDimensionDefinitions[pos]);
2815    
2816          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension, and make
2817          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          // sure that the dimension regions are placed correctly in both the
2818              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values          // RIFF list and the pDimensionRegions array
2819              RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);          RIFF::Chunk* moveTo = NULL;
2820              RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);          RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2821              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);          for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2822                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2823              // copy the upper limits for the other dimensions                  pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2824              memcpy(pDimensionRegions[i]->DimensionUpperLimits,              }
2825                     pDimensionRegions[i & ((1 << iCurrentBits) - 1)]->DimensionUpperLimits, 8);              for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2826                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2827                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2828                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2829                        // create a new dimension region and copy all parameter values from
2830                        // an existing dimension region
2831                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2832                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2833    
2834              DimensionRegions++;                      DimensionRegions++;
2835                    }
2836                }
2837                moveTo = pDimensionRegions[i]->pParentList;
2838          }          }
2839    
2840          // initialize the upper limits for this dimension          // initialize the upper limits for this dimension
2841          for (int z = 0, j = 0 ; z < pDimDef->zones ; z++, j += 1 << iCurrentBits) {          int mask = (1 << bitpos) - 1;
2842              uint8_t upperLimit = (z + 1) * 128.0 / pDimDef->zones - 1;          for (int z = 0 ; z < pDimDef->zones ; z++) {
2843                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2844              for (int i = 0 ; i < 1 << iCurrentBits ; i++) {              for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2845                  pDimensionRegions[j + i]->DimensionUpperLimits[Dimensions] = upperLimit;                  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2846                                      (z << bitpos) |
2847                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2848              }              }
2849          }          }
2850    
# Line 2687  namespace { Line 3062  namespace {
3062          }          }
3063          return NULL;          return NULL;
3064      }      }
3065        
3066        /**
3067         * Make a (semi) deep copy of the Region object given by @a orig
3068         * and assign it to this object.
3069         *
3070         * Note that all sample pointers referenced by @a orig are simply copied as
3071         * memory address. Thus the respective samples are shared, not duplicated!
3072         *
3073         * @param orig - original Region object to be copied from
3074         */
3075        void Region::CopyAssign(const Region* orig) {
3076            CopyAssign(orig, NULL);
3077        }
3078        
3079        /**
3080         * Make a (semi) deep copy of the Region object given by @a orig and
3081         * assign it to this object
3082         *
3083         * @param mSamples - crosslink map between the foreign file's samples and
3084         *                   this file's samples
3085         */
3086        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3087            // handle base classes
3088            DLS::Region::CopyAssign(orig);
3089            
3090            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3091                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3092            }
3093            
3094            // handle own member variables
3095            for (int i = Dimensions - 1; i >= 0; --i) {
3096                DeleteDimension(&pDimensionDefinitions[i]);
3097            }
3098            Layers = 0; // just to be sure
3099            for (int i = 0; i < orig->Dimensions; i++) {
3100                // we need to copy the dim definition here, to avoid the compiler
3101                // complaining about const-ness issue
3102                dimension_def_t def = orig->pDimensionDefinitions[i];
3103                AddDimension(&def);
3104            }
3105            for (int i = 0; i < 256; i++) {
3106                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3107                    pDimensionRegions[i]->CopyAssign(
3108                        orig->pDimensionRegions[i],
3109                        mSamples
3110                    );
3111                }
3112            }
3113            Layers = orig->Layers;
3114        }
3115    
3116    
3117    // *************** MidiRule ***************
3118    // *
3119    
3120        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3121            _3ewg->SetPos(36);
3122            Triggers = _3ewg->ReadUint8();
3123            _3ewg->SetPos(40);
3124            ControllerNumber = _3ewg->ReadUint8();
3125            _3ewg->SetPos(46);
3126            for (int i = 0 ; i < Triggers ; i++) {
3127                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3128                pTriggers[i].Descending = _3ewg->ReadUint8();
3129                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3130                pTriggers[i].Key = _3ewg->ReadUint8();
3131                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3132                pTriggers[i].Velocity = _3ewg->ReadUint8();
3133                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3134                _3ewg->ReadUint8();
3135            }
3136        }
3137    
3138        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3139            ControllerNumber(0),
3140            Triggers(0) {
3141        }
3142    
3143        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3144            pData[32] = 4;
3145            pData[33] = 16;
3146            pData[36] = Triggers;
3147            pData[40] = ControllerNumber;
3148            for (int i = 0 ; i < Triggers ; i++) {
3149                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3150                pData[47 + i * 8] = pTriggers[i].Descending;
3151                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3152                pData[49 + i * 8] = pTriggers[i].Key;
3153                pData[50 + i * 8] = pTriggers[i].NoteOff;
3154                pData[51 + i * 8] = pTriggers[i].Velocity;
3155                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3156            }
3157        }
3158    
3159        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3160            _3ewg->SetPos(36);
3161            LegatoSamples = _3ewg->ReadUint8(); // always 12
3162            _3ewg->SetPos(40);
3163            BypassUseController = _3ewg->ReadUint8();
3164            BypassKey = _3ewg->ReadUint8();
3165            BypassController = _3ewg->ReadUint8();
3166            ThresholdTime = _3ewg->ReadUint16();
3167            _3ewg->ReadInt16();
3168            ReleaseTime = _3ewg->ReadUint16();
3169            _3ewg->ReadInt16();
3170            KeyRange.low = _3ewg->ReadUint8();
3171            KeyRange.high = _3ewg->ReadUint8();
3172            _3ewg->SetPos(64);
3173            ReleaseTriggerKey = _3ewg->ReadUint8();
3174            AltSustain1Key = _3ewg->ReadUint8();
3175            AltSustain2Key = _3ewg->ReadUint8();
3176        }
3177    
3178        MidiRuleLegato::MidiRuleLegato() :
3179            LegatoSamples(12),
3180            BypassUseController(false),
3181            BypassKey(0),
3182            BypassController(1),
3183            ThresholdTime(20),
3184            ReleaseTime(20),
3185            ReleaseTriggerKey(0),
3186            AltSustain1Key(0),
3187            AltSustain2Key(0)
3188        {
3189            KeyRange.low = KeyRange.high = 0;
3190        }
3191    
3192        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3193            pData[32] = 0;
3194            pData[33] = 16;
3195            pData[36] = LegatoSamples;
3196            pData[40] = BypassUseController;
3197            pData[41] = BypassKey;
3198            pData[42] = BypassController;
3199            store16(&pData[43], ThresholdTime);
3200            store16(&pData[47], ReleaseTime);
3201            pData[51] = KeyRange.low;
3202            pData[52] = KeyRange.high;
3203            pData[64] = ReleaseTriggerKey;
3204            pData[65] = AltSustain1Key;
3205            pData[66] = AltSustain2Key;
3206        }
3207    
3208        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3209            _3ewg->SetPos(36);
3210            Articulations = _3ewg->ReadUint8();
3211            int flags = _3ewg->ReadUint8();
3212            Polyphonic = flags & 8;
3213            Chained = flags & 4;
3214            Selector = (flags & 2) ? selector_controller :
3215                (flags & 1) ? selector_key_switch : selector_none;
3216            Patterns = _3ewg->ReadUint8();
3217            _3ewg->ReadUint8(); // chosen row
3218            _3ewg->ReadUint8(); // unknown
3219            _3ewg->ReadUint8(); // unknown
3220            _3ewg->ReadUint8(); // unknown
3221            KeySwitchRange.low = _3ewg->ReadUint8();
3222            KeySwitchRange.high = _3ewg->ReadUint8();
3223            Controller = _3ewg->ReadUint8();
3224            PlayRange.low = _3ewg->ReadUint8();
3225            PlayRange.high = _3ewg->ReadUint8();
3226    
3227            int n = std::min(int(Articulations), 32);
3228            for (int i = 0 ; i < n ; i++) {
3229                _3ewg->ReadString(pArticulations[i], 32);
3230            }
3231            _3ewg->SetPos(1072);
3232            n = std::min(int(Patterns), 32);
3233            for (int i = 0 ; i < n ; i++) {
3234                _3ewg->ReadString(pPatterns[i].Name, 16);
3235                pPatterns[i].Size = _3ewg->ReadUint8();
3236                _3ewg->Read(&pPatterns[i][0], 1, 32);
3237            }
3238        }
3239    
3240        MidiRuleAlternator::MidiRuleAlternator() :
3241            Articulations(0),
3242            Patterns(0),
3243            Selector(selector_none),
3244            Controller(0),
3245            Polyphonic(false),
3246            Chained(false)
3247        {
3248            PlayRange.low = PlayRange.high = 0;
3249            KeySwitchRange.low = KeySwitchRange.high = 0;
3250        }
3251    
3252        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3253            pData[32] = 3;
3254            pData[33] = 16;
3255            pData[36] = Articulations;
3256            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3257                (Selector == selector_controller ? 2 :
3258                 (Selector == selector_key_switch ? 1 : 0));
3259            pData[38] = Patterns;
3260    
3261            pData[43] = KeySwitchRange.low;
3262            pData[44] = KeySwitchRange.high;
3263            pData[45] = Controller;
3264            pData[46] = PlayRange.low;
3265            pData[47] = PlayRange.high;
3266    
3267            char* str = reinterpret_cast<char*>(pData);
3268            int pos = 48;
3269            int n = std::min(int(Articulations), 32);
3270            for (int i = 0 ; i < n ; i++, pos += 32) {
3271                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3272            }
3273    
3274            pos = 1072;
3275            n = std::min(int(Patterns), 32);
3276            for (int i = 0 ; i < n ; i++, pos += 49) {
3277                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3278                pData[pos + 16] = pPatterns[i].Size;
3279                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3280            }
3281        }
3282    
3283  // *************** Instrument ***************  // *************** Instrument ***************
3284  // *  // *
3285    
3286      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) {
3287          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
3288              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
3289              { CHUNK_ID_ISFT, 12 },              { CHUNK_ID_ISFT, 12 },
3290              { 0, 0 }              { 0, 0 }
3291          };          };
3292          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
3293    
3294          // Initialization          // Initialization
3295          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
# Line 2710  namespace { Line 3300  namespace {
3300          PianoReleaseMode = false;          PianoReleaseMode = false;
3301          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
3302          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
3303            pMidiRules = new MidiRule*[3];
3304            pMidiRules[0] = NULL;
3305    
3306          // Loading          // Loading
3307          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2724  namespace { Line 3316  namespace {
3316                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3317                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3318                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3319    
3320                    if (_3ewg->GetSize() > 32) {
3321                        // read MIDI rules
3322                        int i = 0;
3323                        _3ewg->SetPos(32);
3324                        uint8_t id1 = _3ewg->ReadUint8();
3325                        uint8_t id2 = _3ewg->ReadUint8();
3326    
3327                        if (id2 == 16) {
3328                            if (id1 == 4) {
3329                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3330                            } else if (id1 == 0) {
3331                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3332                            } else if (id1 == 3) {
3333                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3334                            } else {
3335                                pMidiRules[i++] = new MidiRuleUnknown;
3336                            }
3337                        }
3338                        else if (id1 != 0 || id2 != 0) {
3339                            pMidiRules[i++] = new MidiRuleUnknown;
3340                        }
3341                        //TODO: all the other types of rules
3342    
3343                        pMidiRules[i] = NULL;
3344                    }
3345              }              }
3346          }          }
3347    
3348          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3349          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3350          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3351              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3352              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3353                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3354                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3355                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3356                            pRegions->push_back(new Region(this, rgn));
3357                        }
3358                        rgn = lrgn->GetNextSubList();
3359                  }                  }
3360                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3361                    UpdateRegionKeyTable();
3362              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3363          }          }
3364    
3365          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3366      }      }
3367    
3368      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3369            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3370          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3371          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3372          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2757  namespace { Line 3378  namespace {
3378      }      }
3379    
3380      Instrument::~Instrument() {      Instrument::~Instrument() {
3381            for (int i = 0 ; pMidiRules[i] ; i++) {
3382                delete pMidiRules[i];
3383            }
3384            delete[] pMidiRules;
3385      }      }
3386    
3387      /**      /**
# Line 2785  namespace { Line 3410  namespace {
3410          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3411          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3412          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3413          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3414                File* pFile = (File*) GetParent();
3415    
3416                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3417                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3418                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3419                memset(_3ewg->LoadChunkData(), 0, size);
3420            }
3421          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3422          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3423          store16(&pData[0], EffectSend);          store16(&pData[0], EffectSend);
3424          store32(&pData[2], Attenuation);          store32(&pData[2], Attenuation);
3425          store16(&pData[6], FineTune);          store16(&pData[6], FineTune);
3426          store16(&pData[8], PitchbendRange);          store16(&pData[8], PitchbendRange);
3427          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3428                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3429          pData[10] = dimkeystart;          pData[10] = dimkeystart;
3430          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
3431    
3432            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3433                pData[32] = 0;
3434                pData[33] = 0;
3435            } else {
3436                for (int i = 0 ; pMidiRules[i] ; i++) {
3437                    pMidiRules[i]->UpdateChunks(pData);
3438                }
3439            }
3440      }      }
3441    
3442      /**      /**
# Line 2806  namespace { Line 3447  namespace {
3447       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3448       */       */
3449      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3450          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3451          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3452    
3453          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2864  namespace { Line 3505  namespace {
3505          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3506      }      }
3507    
3508        /**
3509         * Returns a MIDI rule of the instrument.
3510         *
3511         * The list of MIDI rules, at least in gig v3, always contains at
3512         * most two rules. The second rule can only be the DEF filter
3513         * (which currently isn't supported by libgig).
3514         *
3515         * @param i - MIDI rule number
3516         * @returns   pointer address to MIDI rule number i or NULL if there is none
3517         */
3518        MidiRule* Instrument::GetMidiRule(int i) {
3519            return pMidiRules[i];
3520        }
3521    
3522        /**
3523         * Adds the "controller trigger" MIDI rule to the instrument.
3524         *
3525         * @returns the new MIDI rule
3526         */
3527        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3528            delete pMidiRules[0];
3529            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3530            pMidiRules[0] = r;
3531            pMidiRules[1] = 0;
3532            return r;
3533        }
3534    
3535        /**
3536         * Adds the legato MIDI rule to the instrument.
3537         *
3538         * @returns the new MIDI rule
3539         */
3540        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3541            delete pMidiRules[0];
3542            MidiRuleLegato* r = new MidiRuleLegato;
3543            pMidiRules[0] = r;
3544            pMidiRules[1] = 0;
3545            return r;
3546        }
3547    
3548        /**
3549         * Adds the alternator MIDI rule to the instrument.
3550         *
3551         * @returns the new MIDI rule
3552         */
3553        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3554            delete pMidiRules[0];
3555            MidiRuleAlternator* r = new MidiRuleAlternator;
3556            pMidiRules[0] = r;
3557            pMidiRules[1] = 0;
3558            return r;
3559        }
3560    
3561        /**
3562         * Deletes a MIDI rule from the instrument.
3563         *
3564         * @param i - MIDI rule number
3565         */
3566        void Instrument::DeleteMidiRule(int i) {
3567            delete pMidiRules[i];
3568            pMidiRules[i] = 0;
3569        }
3570    
3571        /**
3572         * Make a (semi) deep copy of the Instrument object given by @a orig
3573         * and assign it to this object.
3574         *
3575         * Note that all sample pointers referenced by @a orig are simply copied as
3576         * memory address. Thus the respective samples are shared, not duplicated!
3577         *
3578         * @param orig - original Instrument object to be copied from
3579         */
3580        void Instrument::CopyAssign(const Instrument* orig) {
3581            CopyAssign(orig, NULL);
3582        }
3583            
3584        /**
3585         * Make a (semi) deep copy of the Instrument object given by @a orig
3586         * and assign it to this object.
3587         *
3588         * @param orig - original Instrument object to be copied from
3589         * @param mSamples - crosslink map between the foreign file's samples and
3590         *                   this file's samples
3591         */
3592        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3593            // handle base class
3594            // (without copying DLS region stuff)
3595            DLS::Instrument::CopyAssignCore(orig);
3596            
3597            // handle own member variables
3598            Attenuation = orig->Attenuation;
3599            EffectSend = orig->EffectSend;
3600            FineTune = orig->FineTune;
3601            PitchbendRange = orig->PitchbendRange;
3602            PianoReleaseMode = orig->PianoReleaseMode;
3603            DimensionKeyRange = orig->DimensionKeyRange;
3604            
3605            // free old midi rules
3606            for (int i = 0 ; pMidiRules[i] ; i++) {
3607                delete pMidiRules[i];
3608            }
3609            //TODO: MIDI rule copying
3610            pMidiRules[0] = NULL;
3611            
3612            // delete all old regions
3613            while (Regions) DeleteRegion(GetFirstRegion());
3614            // create new regions and copy them from original
3615            {
3616                RegionList::const_iterator it = orig->pRegions->begin();
3617                for (int i = 0; i < orig->Regions; ++i, ++it) {
3618                    Region* dstRgn = AddRegion();
3619                    //NOTE: Region does semi-deep copy !
3620                    dstRgn->CopyAssign(
3621                        static_cast<gig::Region*>(*it),
3622                        mSamples
3623                    );
3624                }
3625            }
3626    
3627            UpdateRegionKeyTable();
3628        }
3629    
3630    
3631  // *************** Group ***************  // *************** Group ***************
# Line 2903  namespace { Line 3665  namespace {
3665          }          }
3666          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3667          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3668    
3669            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3670                // v3 has a fixed list of 128 strings, find a free one
3671                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3672                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3673                        pNameChunk = ck;
3674                        break;
3675                    }
3676                }
3677            }
3678    
3679          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3680          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3681      }      }
# Line 2978  namespace { Line 3751  namespace {
3751  // *************** File ***************  // *************** File ***************
3752  // *  // *
3753    
3754      // File version 2.0, 1998-06-28      /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3755      const DLS::version_t File::VERSION_2 = {      const DLS::version_t File::VERSION_2 = {
3756          0, 2, 19980628 & 0xffff, 19980628 >> 16          0, 2, 19980628 & 0xffff, 19980628 >> 16
3757      };      };
3758    
3759      // File version 3.0, 2003-03-31      /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3760      const DLS::version_t File::VERSION_3 = {      const DLS::version_t File::VERSION_3 = {
3761          0, 3, 20030331 & 0xffff, 20030331 >> 16          0, 3, 20030331 & 0xffff, 20030331 >> 16
3762      };      };
3763    
3764      const DLS::Info::FixedStringLength File::FixedStringLengths[] = {      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3765          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
3766          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
3767          { CHUNK_ID_ICMS, 128 },          { CHUNK_ID_ICMS, 128 },
# Line 3010  namespace { Line 3783  namespace {
3783      };      };
3784    
3785      File::File() : DLS::File() {      File::File() : DLS::File() {
3786            bAutoLoad = true;
3787            *pVersion = VERSION_3;
3788          pGroups = NULL;          pGroups = NULL;
3789          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3790          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
3791    
3792          // add some mandatory chunks to get the file chunks in right          // add some mandatory chunks to get the file chunks in right
# Line 3024  namespace { Line 3799  namespace {
3799      }      }
3800    
3801      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3802            bAutoLoad = true;
3803          pGroups = NULL;          pGroups = NULL;
3804          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3805      }      }
3806    
3807      File::~File() {      File::~File() {
# Line 3052  namespace { Line 3828  namespace {
3828          SamplesIterator++;          SamplesIterator++;
3829          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3830      }      }
3831        
3832        /**
3833         * Returns Sample object of @a index.
3834         *
3835         * @returns sample object or NULL if index is out of bounds
3836         */
3837        Sample* File::GetSample(uint index) {
3838            if (!pSamples) LoadSamples();
3839            if (!pSamples) return NULL;
3840            DLS::File::SampleList::iterator it = pSamples->begin();
3841            for (int i = 0; i < index; ++i) {
3842                ++it;
3843                if (it == pSamples->end()) return NULL;
3844            }
3845            if (it == pSamples->end()) return NULL;
3846            return static_cast<gig::Sample*>( *it );
3847        }
3848    
3849      /** @brief Add a new sample.      /** @brief Add a new sample.
3850       *       *
# Line 3078  namespace { Line 3871  namespace {
3871    
3872      /** @brief Delete a sample.      /** @brief Delete a sample.
3873       *       *
3874       * This will delete the given Sample object from the gig file. You have       * This will delete the given Sample object from the gig file. Any
3875       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
3876         * removed. You have to call Save() to make this persistent to the file.
3877       *       *
3878       * @param pSample - sample to delete       * @param pSample - sample to delete
3879       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 3091  namespace { Line 3885  namespace {
3885          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3886          pSamples->erase(iter);          pSamples->erase(iter);
3887          delete pSample;          delete pSample;
3888    
3889            SampleList::iterator tmp = SamplesIterator;
3890            // remove all references to the sample
3891            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3892                 instrument = GetNextInstrument()) {
3893                for (Region* region = instrument->GetFirstRegion() ; region ;
3894                     region = instrument->GetNextRegion()) {
3895    
3896                    if (region->GetSample() == pSample) region->SetSample(NULL);
3897    
3898                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3899                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3900                        if (d->pSample == pSample) d->pSample = NULL;
3901                    }
3902                }
3903            }
3904            SamplesIterator = tmp; // restore iterator
3905      }      }
3906    
3907      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3181  namespace { Line 3992  namespace {
3992              progress_t subprogress;              progress_t subprogress;
3993              __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
3994              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3995              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3996                    GetFirstSample(&subprogress); // now force all samples to be loaded
3997              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3998    
3999              // instrument loading subtask              // instrument loading subtask
# Line 3230  namespace { Line 4042  namespace {
4042         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4043         return pInstrument;         return pInstrument;
4044      }      }
4045        
4046        /** @brief Add a duplicate of an existing instrument.
4047         *
4048         * Duplicates the instrument definition given by @a orig and adds it
4049         * to this file. This allows in an instrument editor application to
4050         * easily create variations of an instrument, which will be stored in
4051         * the same .gig file, sharing i.e. the same samples.
4052         *
4053         * Note that all sample pointers referenced by @a orig are simply copied as
4054         * memory address. Thus the respective samples are shared, not duplicated!
4055         *
4056         * You have to call Save() to make this persistent to the file.
4057         *
4058         * @param orig - original instrument to be copied
4059         * @returns duplicated copy of the given instrument
4060         */
4061        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4062            Instrument* instr = AddInstrument();
4063            instr->CopyAssign(orig);
4064            return instr;
4065        }
4066        
4067        /** @brief Add content of another existing file.
4068         *
4069         * Duplicates the samples, groups and instruments of the original file
4070         * given by @a pFile and adds them to @c this File. In case @c this File is
4071         * a new one that you haven't saved before, then you have to call
4072         * SetFileName() before calling AddContentOf(), because this method will
4073         * automatically save this file during operation, which is required for
4074         * writing the sample waveform data by disk streaming.
4075         *
4076         * @param pFile - original file whose's content shall be copied from
4077         */
4078        void File::AddContentOf(File* pFile) {
4079            static int iCallCount = -1;
4080            iCallCount++;
4081            std::map<Group*,Group*> mGroups;
4082            std::map<Sample*,Sample*> mSamples;
4083            
4084            // clone sample groups
4085            for (int i = 0; pFile->GetGroup(i); ++i) {
4086                Group* g = AddGroup();
4087                g->Name =
4088                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4089                mGroups[pFile->GetGroup(i)] = g;
4090            }
4091            
4092            // clone samples (not waveform data here yet)
4093            for (int i = 0; pFile->GetSample(i); ++i) {
4094                Sample* s = AddSample();
4095                s->CopyAssignMeta(pFile->GetSample(i));
4096                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4097                mSamples[pFile->GetSample(i)] = s;
4098            }
4099            
4100            //BUG: For some reason this method only works with this additional
4101            //     Save() call in between here.
4102            //
4103            // Important: The correct one of the 2 Save() methods has to be called
4104            // here, depending on whether the file is completely new or has been
4105            // saved to disk already, otherwise it will result in data corruption.
4106            if (pRIFF->IsNew())
4107                Save(GetFileName());
4108            else
4109                Save();
4110            
4111            // clone instruments
4112            // (passing the crosslink table here for the cloned samples)
4113            for (int i = 0; pFile->GetInstrument(i); ++i) {
4114                Instrument* instr = AddInstrument();
4115                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4116            }
4117            
4118            // Mandatory: file needs to be saved to disk at this point, so this
4119            // file has the correct size and data layout for writing the samples'
4120            // waveform data to disk.
4121            Save();
4122            
4123            // clone samples' waveform data
4124            // (using direct read & write disk streaming)
4125            for (int i = 0; pFile->GetSample(i); ++i) {
4126                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4127            }
4128        }
4129    
4130      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4131       *       *
# Line 3395  namespace { Line 4291  namespace {
4291                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4292                  while (ck) {                  while (ck) {
4293                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4294                            if (pVersion && pVersion->major == 3 &&
4295                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4296    
4297                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
4298                      }                      }
4299                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3439  namespace { Line 4338  namespace {
4338    
4339          // update group's chunks          // update group's chunks
4340          if (pGroups) {          if (pGroups) {
4341                // make sure '3gri' and '3gnl' list chunks exist
4342                // (before updating the Group chunks)
4343                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4344                if (!_3gri) {
4345                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4346                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4347                }
4348                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4349                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4350    
4351                // v3: make sure the file has 128 3gnm chunks
4352                // (before updating the Group chunks)
4353                if (pVersion && pVersion->major == 3) {
4354                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4355                    for (int i = 0 ; i < 128 ; i++) {
4356                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4357                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4358                    }
4359                }
4360    
4361              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
4362              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
4363              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
# Line 3487  namespace { Line 4406  namespace {
4406              int totnbusedchannels = 0;              int totnbusedchannels = 0;
4407              int totnbregions = 0;              int totnbregions = 0;
4408              int totnbdimregions = 0;              int totnbdimregions = 0;
4409                int totnbloops = 0;
4410              int instrumentIdx = 0;              int instrumentIdx = 0;
4411    
4412              memset(&pData[48], 0, sublen - 48);              memset(&pData[48], 0, sublen - 48);
# Line 3496  namespace { Line 4416  namespace {
4416                  int nbusedsamples = 0;                  int nbusedsamples = 0;
4417                  int nbusedchannels = 0;                  int nbusedchannels = 0;
4418                  int nbdimregions = 0;                  int nbdimregions = 0;
4419                    int nbloops = 0;
4420    
4421                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4422    
# Line 3519  namespace { Line 4440  namespace {
4440                                  }                                  }
4441                              }                              }
4442                          }                          }
4443                            if (d->SampleLoops) nbloops++;
4444                      }                      }
4445                      nbdimregions += region->DimensionRegions;                      nbdimregions += region->DimensionRegions;
4446                  }                  }
# Line 3529  namespace { Line 4451  namespace {
4451                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4452                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4453                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4454                  // next 12 bytes unknown                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4455                    // next 8 bytes unknown
4456                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4457                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4458                  // next 4 bytes unknown                  // next 4 bytes unknown
4459    
4460                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
4461                  totnbdimregions += nbdimregions;                  totnbdimregions += nbdimregions;
4462                    totnbloops += nbloops;
4463                  instrumentIdx++;                  instrumentIdx++;
4464              }              }
4465              // first 4 bytes unknown - sometimes 0, sometimes length of einf part              // first 4 bytes unknown - sometimes 0, sometimes length of einf part
# Line 3545  namespace { Line 4469  namespace {
4469              store32(&pData[12], Instruments);              store32(&pData[12], Instruments);
4470              store32(&pData[16], totnbregions);              store32(&pData[16], totnbregions);
4471              store32(&pData[20], totnbdimregions);              store32(&pData[20], totnbdimregions);
4472              // next 12 bytes unknown              store32(&pData[24], totnbloops);
4473              // next 4 bytes unknown, always 0?              // next 8 bytes unknown
4474                // next 4 bytes unknown, not always 0
4475              store32(&pData[40], pSamples->size());              store32(&pData[40], pSamples->size());
4476              // next 4 bytes unknown              // next 4 bytes unknown
4477          }          }
# Line 3563  namespace { Line 4488  namespace {
4488          } else if (newFile) {          } else if (newFile) {
4489              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4490              _3crc->LoadChunkData();              _3crc->LoadChunkData();
4491    
4492                // the order of einf and 3crc is not the same in v2 and v3
4493                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4494          }          }
4495      }      }
4496    
4497        /**
4498         * Enable / disable automatic loading. By default this properyt is
4499         * enabled and all informations are loaded automatically. However
4500         * loading all Regions, DimensionRegions and especially samples might
4501         * take a long time for large .gig files, and sometimes one might only
4502         * be interested in retrieving very superficial informations like the
4503         * amount of instruments and their names. In this case one might disable
4504         * automatic loading to avoid very slow response times.
4505         *
4506         * @e CAUTION: by disabling this property many pointers (i.e. sample
4507         * references) and informations will have invalid or even undefined
4508         * data! This feature is currently only intended for retrieving very
4509         * superficial informations in a very fast way. Don't use it to retrieve
4510         * details like synthesis informations or even to modify .gig files!
4511         */
4512        void File::SetAutoLoad(bool b) {
4513            bAutoLoad = b;
4514        }
4515    
4516        /**
4517         * Returns whether automatic loading is enabled.
4518         * @see SetAutoLoad()
4519         */
4520        bool File::GetAutoLoad() {
4521            return bAutoLoad;
4522        }
4523    
4524    
4525    
4526  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.1247  
changed lines
  Added in v.2484

  ViewVC Help
Powered by ViewVC