/[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 1416 by schoenebeck, Sun Oct 14 12:06:32 2007 UTC revision 2640 by schoenebeck, Mon Jun 16 14:54:06 2014 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-2014 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
34  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 453  namespace { Line 455  namespace {
455      }      }
456    
457      /**      /**
458         * Make a (semi) deep copy of the Sample object given by @a orig (without
459         * the actual waveform data) and assign it to this object.
460         *
461         * Discussion: copying .gig samples is a bit tricky. It requires three
462         * steps:
463         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
464         *    its new sample waveform data size.
465         * 2. Saving the file (done by File::Save()) so that it gains correct size
466         *    and layout for writing the actual wave form data directly to disc
467         *    in next step.
468         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
469         *
470         * @param orig - original Sample object to be copied from
471         */
472        void Sample::CopyAssignMeta(const Sample* orig) {
473            // handle base classes
474            DLS::Sample::CopyAssignCore(orig);
475            
476            // handle actual own attributes of this class
477            Manufacturer = orig->Manufacturer;
478            Product = orig->Product;
479            SamplePeriod = orig->SamplePeriod;
480            MIDIUnityNote = orig->MIDIUnityNote;
481            FineTune = orig->FineTune;
482            SMPTEFormat = orig->SMPTEFormat;
483            SMPTEOffset = orig->SMPTEOffset;
484            Loops = orig->Loops;
485            LoopID = orig->LoopID;
486            LoopType = orig->LoopType;
487            LoopStart = orig->LoopStart;
488            LoopEnd = orig->LoopEnd;
489            LoopSize = orig->LoopSize;
490            LoopFraction = orig->LoopFraction;
491            LoopPlayCount = orig->LoopPlayCount;
492            
493            // schedule resizing this sample to the given sample's size
494            Resize(orig->GetSize());
495        }
496    
497        /**
498         * Should be called after CopyAssignMeta() and File::Save() sequence.
499         * Read more about it in the discussion of CopyAssignMeta(). This method
500         * copies the actual waveform data by disk streaming.
501         *
502         * @e CAUTION: this method is currently not thread safe! During this
503         * operation the sample must not be used for other purposes by other
504         * threads!
505         *
506         * @param orig - original Sample object to be copied from
507         */
508        void Sample::CopyAssignWave(const Sample* orig) {
509            const int iReadAtOnce = 32*1024;
510            char* buf = new char[iReadAtOnce * orig->FrameSize];
511            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
512            unsigned long restorePos = pOrig->GetPos();
513            pOrig->SetPos(0);
514            SetPos(0);
515            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
516                               n = pOrig->Read(buf, iReadAtOnce))
517            {
518                Write(buf, n);
519            }
520            pOrig->SetPos(restorePos);
521            delete [] buf;
522        }
523    
524        /**
525       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
526       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
527       *       *
# Line 513  namespace { Line 582  namespace {
582          // update '3gix' chunk          // update '3gix' chunk
583          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
584          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
585    
586            // if the library user toggled the "Compressed" attribute from true to
587            // false, then the EWAV chunk associated with compressed samples needs
588            // to be deleted
589            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
590            if (ewav && !Compressed) {
591                pWaveList->DeleteSubChunk(ewav);
592            }
593      }      }
594    
595      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 676  namespace { Line 753  namespace {
753          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
754          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
755          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
756            SetPos(0); // reset read position to begin of sample
757          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
758          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
759          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 713  namespace { Line 791  namespace {
791          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
792          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
793          RAMCache.Size   = 0;          RAMCache.Size   = 0;
794            RAMCache.NullExtensionSize = 0;
795      }      }
796    
797      /** @brief Resize sample.      /** @brief Resize sample.
# Line 805  namespace { Line 884  namespace {
884      /**      /**
885       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
886       */       */
887      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
888          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
889          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
890      }      }
# Line 907  namespace { Line 986  namespace {
986                                  }                                  }
987    
988                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
989                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
990                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
991                              }                              }
992                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
993                          break;                          break;
# Line 1429  namespace { Line 1509  namespace {
1509                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1510              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1511              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1512                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1513              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1514              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1515              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1577  namespace { Line 1657  namespace {
1657       */       */
1658      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1659          Instances++;          Instances++;
1660            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1661          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1662          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1663    
# Line 1592  namespace { Line 1673  namespace {
1673                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1674          }          }
1675      }      }
1676        
1677        /**
1678         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1679         * and assign it to this object.
1680         *
1681         * Note that all sample pointers referenced by @a orig are simply copied as
1682         * memory address. Thus the respective samples are shared, not duplicated!
1683         *
1684         * @param orig - original DimensionRegion object to be copied from
1685         */
1686        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1687            CopyAssign(orig, NULL);
1688        }
1689    
1690        /**
1691         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1692         * and assign it to this object.
1693         *
1694         * @param orig - original DimensionRegion object to be copied from
1695         * @param mSamples - crosslink map between the foreign file's samples and
1696         *                   this file's samples
1697         */
1698        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1699            // delete all allocated data first
1700            if (VelocityTable) delete [] VelocityTable;
1701            if (pSampleLoops) delete [] pSampleLoops;
1702            
1703            // backup parent list pointer
1704            RIFF::List* p = pParentList;
1705            
1706            gig::Sample* pOriginalSample = pSample;
1707            gig::Region* pOriginalRegion = pRegion;
1708            
1709            //NOTE: copy code copied from assignment constructor above, see comment there as well
1710            
1711            *this = *orig; // default memberwise shallow copy of all parameters
1712            
1713            // restore members that shall not be altered
1714            pParentList = p; // restore the chunk pointer
1715            pRegion = pOriginalRegion;
1716            
1717            // only take the raw sample reference reference if the
1718            // two DimensionRegion objects are part of the same file
1719            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1720                pSample = pOriginalSample;
1721            }
1722            
1723            if (mSamples && mSamples->count(orig->pSample)) {
1724                pSample = mSamples->find(orig->pSample)->second;
1725            }
1726    
1727            // deep copy of owned structures
1728            if (orig->VelocityTable) {
1729                VelocityTable = new uint8_t[128];
1730                for (int k = 0 ; k < 128 ; k++)
1731                    VelocityTable[k] = orig->VelocityTable[k];
1732            }
1733            if (orig->pSampleLoops) {
1734                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1735                for (int k = 0 ; k < orig->SampleLoops ; k++)
1736                    pSampleLoops[k] = orig->pSampleLoops[k];
1737            }
1738        }
1739    
1740      /**      /**
1741       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1833  namespace { Line 1977  namespace {
1977          }          }
1978    
1979          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1980                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1981          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1982    
1983          // next 2 bytes unknown          // next 2 bytes unknown
1984    
# Line 1881  namespace { Line 2025  namespace {
2025                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2026          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2027    
2028          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2029                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2030          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2031    
# Line 1946  namespace { Line 2090  namespace {
2090          return pRegion;          return pRegion;
2091      }      }
2092    
2093    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2094    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2095    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2096    //#pragma GCC diagnostic push
2097    //#pragma GCC diagnostic error "-Wswitch"
2098    
2099      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2100          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2101          switch (EncodedController) {          switch (EncodedController) {
# Line 2057  namespace { Line 2207  namespace {
2207                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2208                  break;                  break;
2209    
2210                // format extension (these controllers are so far only supported by
2211                // LinuxSampler & gigedit) they will *NOT* work with
2212                // Gigasampler/GigaStudio !
2213                case _lev_ctrl_CC3_EXT:
2214                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2215                    decodedcontroller.controller_number = 3;
2216                    break;
2217                case _lev_ctrl_CC6_EXT:
2218                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2219                    decodedcontroller.controller_number = 6;
2220                    break;
2221                case _lev_ctrl_CC7_EXT:
2222                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2223                    decodedcontroller.controller_number = 7;
2224                    break;
2225                case _lev_ctrl_CC8_EXT:
2226                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2227                    decodedcontroller.controller_number = 8;
2228                    break;
2229                case _lev_ctrl_CC9_EXT:
2230                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2231                    decodedcontroller.controller_number = 9;
2232                    break;
2233                case _lev_ctrl_CC10_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 10;
2236                    break;
2237                case _lev_ctrl_CC11_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 11;
2240                    break;
2241                case _lev_ctrl_CC14_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 14;
2244                    break;
2245                case _lev_ctrl_CC15_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 15;
2248                    break;
2249                case _lev_ctrl_CC20_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 20;
2252                    break;
2253                case _lev_ctrl_CC21_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 21;
2256                    break;
2257                case _lev_ctrl_CC22_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 22;
2260                    break;
2261                case _lev_ctrl_CC23_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 23;
2264                    break;
2265                case _lev_ctrl_CC24_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 24;
2268                    break;
2269                case _lev_ctrl_CC25_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 25;
2272                    break;
2273                case _lev_ctrl_CC26_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 26;
2276                    break;
2277                case _lev_ctrl_CC27_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 27;
2280                    break;
2281                case _lev_ctrl_CC28_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 28;
2284                    break;
2285                case _lev_ctrl_CC29_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 29;
2288                    break;
2289                case _lev_ctrl_CC30_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 30;
2292                    break;
2293                case _lev_ctrl_CC31_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 31;
2296                    break;
2297                case _lev_ctrl_CC68_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 68;
2300                    break;
2301                case _lev_ctrl_CC69_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 69;
2304                    break;
2305                case _lev_ctrl_CC70_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 70;
2308                    break;
2309                case _lev_ctrl_CC71_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 71;
2312                    break;
2313                case _lev_ctrl_CC72_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 72;
2316                    break;
2317                case _lev_ctrl_CC73_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 73;
2320                    break;
2321                case _lev_ctrl_CC74_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 74;
2324                    break;
2325                case _lev_ctrl_CC75_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 75;
2328                    break;
2329                case _lev_ctrl_CC76_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 76;
2332                    break;
2333                case _lev_ctrl_CC77_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 77;
2336                    break;
2337                case _lev_ctrl_CC78_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 78;
2340                    break;
2341                case _lev_ctrl_CC79_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 79;
2344                    break;
2345                case _lev_ctrl_CC84_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 84;
2348                    break;
2349                case _lev_ctrl_CC85_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 85;
2352                    break;
2353                case _lev_ctrl_CC86_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 86;
2356                    break;
2357                case _lev_ctrl_CC87_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 87;
2360                    break;
2361                case _lev_ctrl_CC89_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 89;
2364                    break;
2365                case _lev_ctrl_CC90_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 90;
2368                    break;
2369                case _lev_ctrl_CC96_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 96;
2372                    break;
2373                case _lev_ctrl_CC97_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 97;
2376                    break;
2377                case _lev_ctrl_CC102_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 102;
2380                    break;
2381                case _lev_ctrl_CC103_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 103;
2384                    break;
2385                case _lev_ctrl_CC104_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 104;
2388                    break;
2389                case _lev_ctrl_CC105_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 105;
2392                    break;
2393                case _lev_ctrl_CC106_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 106;
2396                    break;
2397                case _lev_ctrl_CC107_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 107;
2400                    break;
2401                case _lev_ctrl_CC108_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 108;
2404                    break;
2405                case _lev_ctrl_CC109_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 109;
2408                    break;
2409                case _lev_ctrl_CC110_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 110;
2412                    break;
2413                case _lev_ctrl_CC111_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 111;
2416                    break;
2417                case _lev_ctrl_CC112_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 112;
2420                    break;
2421                case _lev_ctrl_CC113_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 113;
2424                    break;
2425                case _lev_ctrl_CC114_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 114;
2428                    break;
2429                case _lev_ctrl_CC115_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 115;
2432                    break;
2433                case _lev_ctrl_CC116_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 116;
2436                    break;
2437                case _lev_ctrl_CC117_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 117;
2440                    break;
2441                case _lev_ctrl_CC118_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 118;
2444                    break;
2445                case _lev_ctrl_CC119_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 119;
2448                    break;
2449    
2450              // unknown controller type              // unknown controller type
2451              default:              default:
2452                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2453          }          }
2454          return decodedcontroller;          return decodedcontroller;
2455      }      }
2456        
2457    // see above (diagnostic push not supported prior GCC 4.6)
2458    //#pragma GCC diagnostic pop
2459    
2460      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2461          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2150  namespace { Line 2543  namespace {
2543                      case 95:                      case 95:
2544                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2545                          break;                          break;
2546    
2547                        // format extension (these controllers are so far only
2548                        // supported by LinuxSampler & gigedit) they will *NOT*
2549                        // work with Gigasampler/GigaStudio !
2550                        case 3:
2551                            encodedcontroller = _lev_ctrl_CC3_EXT;
2552                            break;
2553                        case 6:
2554                            encodedcontroller = _lev_ctrl_CC6_EXT;
2555                            break;
2556                        case 7:
2557                            encodedcontroller = _lev_ctrl_CC7_EXT;
2558                            break;
2559                        case 8:
2560                            encodedcontroller = _lev_ctrl_CC8_EXT;
2561                            break;
2562                        case 9:
2563                            encodedcontroller = _lev_ctrl_CC9_EXT;
2564                            break;
2565                        case 10:
2566                            encodedcontroller = _lev_ctrl_CC10_EXT;
2567                            break;
2568                        case 11:
2569                            encodedcontroller = _lev_ctrl_CC11_EXT;
2570                            break;
2571                        case 14:
2572                            encodedcontroller = _lev_ctrl_CC14_EXT;
2573                            break;
2574                        case 15:
2575                            encodedcontroller = _lev_ctrl_CC15_EXT;
2576                            break;
2577                        case 20:
2578                            encodedcontroller = _lev_ctrl_CC20_EXT;
2579                            break;
2580                        case 21:
2581                            encodedcontroller = _lev_ctrl_CC21_EXT;
2582                            break;
2583                        case 22:
2584                            encodedcontroller = _lev_ctrl_CC22_EXT;
2585                            break;
2586                        case 23:
2587                            encodedcontroller = _lev_ctrl_CC23_EXT;
2588                            break;
2589                        case 24:
2590                            encodedcontroller = _lev_ctrl_CC24_EXT;
2591                            break;
2592                        case 25:
2593                            encodedcontroller = _lev_ctrl_CC25_EXT;
2594                            break;
2595                        case 26:
2596                            encodedcontroller = _lev_ctrl_CC26_EXT;
2597                            break;
2598                        case 27:
2599                            encodedcontroller = _lev_ctrl_CC27_EXT;
2600                            break;
2601                        case 28:
2602                            encodedcontroller = _lev_ctrl_CC28_EXT;
2603                            break;
2604                        case 29:
2605                            encodedcontroller = _lev_ctrl_CC29_EXT;
2606                            break;
2607                        case 30:
2608                            encodedcontroller = _lev_ctrl_CC30_EXT;
2609                            break;
2610                        case 31:
2611                            encodedcontroller = _lev_ctrl_CC31_EXT;
2612                            break;
2613                        case 68:
2614                            encodedcontroller = _lev_ctrl_CC68_EXT;
2615                            break;
2616                        case 69:
2617                            encodedcontroller = _lev_ctrl_CC69_EXT;
2618                            break;
2619                        case 70:
2620                            encodedcontroller = _lev_ctrl_CC70_EXT;
2621                            break;
2622                        case 71:
2623                            encodedcontroller = _lev_ctrl_CC71_EXT;
2624                            break;
2625                        case 72:
2626                            encodedcontroller = _lev_ctrl_CC72_EXT;
2627                            break;
2628                        case 73:
2629                            encodedcontroller = _lev_ctrl_CC73_EXT;
2630                            break;
2631                        case 74:
2632                            encodedcontroller = _lev_ctrl_CC74_EXT;
2633                            break;
2634                        case 75:
2635                            encodedcontroller = _lev_ctrl_CC75_EXT;
2636                            break;
2637                        case 76:
2638                            encodedcontroller = _lev_ctrl_CC76_EXT;
2639                            break;
2640                        case 77:
2641                            encodedcontroller = _lev_ctrl_CC77_EXT;
2642                            break;
2643                        case 78:
2644                            encodedcontroller = _lev_ctrl_CC78_EXT;
2645                            break;
2646                        case 79:
2647                            encodedcontroller = _lev_ctrl_CC79_EXT;
2648                            break;
2649                        case 84:
2650                            encodedcontroller = _lev_ctrl_CC84_EXT;
2651                            break;
2652                        case 85:
2653                            encodedcontroller = _lev_ctrl_CC85_EXT;
2654                            break;
2655                        case 86:
2656                            encodedcontroller = _lev_ctrl_CC86_EXT;
2657                            break;
2658                        case 87:
2659                            encodedcontroller = _lev_ctrl_CC87_EXT;
2660                            break;
2661                        case 89:
2662                            encodedcontroller = _lev_ctrl_CC89_EXT;
2663                            break;
2664                        case 90:
2665                            encodedcontroller = _lev_ctrl_CC90_EXT;
2666                            break;
2667                        case 96:
2668                            encodedcontroller = _lev_ctrl_CC96_EXT;
2669                            break;
2670                        case 97:
2671                            encodedcontroller = _lev_ctrl_CC97_EXT;
2672                            break;
2673                        case 102:
2674                            encodedcontroller = _lev_ctrl_CC102_EXT;
2675                            break;
2676                        case 103:
2677                            encodedcontroller = _lev_ctrl_CC103_EXT;
2678                            break;
2679                        case 104:
2680                            encodedcontroller = _lev_ctrl_CC104_EXT;
2681                            break;
2682                        case 105:
2683                            encodedcontroller = _lev_ctrl_CC105_EXT;
2684                            break;
2685                        case 106:
2686                            encodedcontroller = _lev_ctrl_CC106_EXT;
2687                            break;
2688                        case 107:
2689                            encodedcontroller = _lev_ctrl_CC107_EXT;
2690                            break;
2691                        case 108:
2692                            encodedcontroller = _lev_ctrl_CC108_EXT;
2693                            break;
2694                        case 109:
2695                            encodedcontroller = _lev_ctrl_CC109_EXT;
2696                            break;
2697                        case 110:
2698                            encodedcontroller = _lev_ctrl_CC110_EXT;
2699                            break;
2700                        case 111:
2701                            encodedcontroller = _lev_ctrl_CC111_EXT;
2702                            break;
2703                        case 112:
2704                            encodedcontroller = _lev_ctrl_CC112_EXT;
2705                            break;
2706                        case 113:
2707                            encodedcontroller = _lev_ctrl_CC113_EXT;
2708                            break;
2709                        case 114:
2710                            encodedcontroller = _lev_ctrl_CC114_EXT;
2711                            break;
2712                        case 115:
2713                            encodedcontroller = _lev_ctrl_CC115_EXT;
2714                            break;
2715                        case 116:
2716                            encodedcontroller = _lev_ctrl_CC116_EXT;
2717                            break;
2718                        case 117:
2719                            encodedcontroller = _lev_ctrl_CC117_EXT;
2720                            break;
2721                        case 118:
2722                            encodedcontroller = _lev_ctrl_CC118_EXT;
2723                            break;
2724                        case 119:
2725                            encodedcontroller = _lev_ctrl_CC119_EXT;
2726                            break;
2727    
2728                      default:                      default:
2729                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2730                  }                  }
# Line 2372  namespace { Line 2947  namespace {
2947    
2948          // Actual Loading          // Actual Loading
2949    
2950            if (!file->GetAutoLoad()) return;
2951    
2952          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2953    
2954          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2415  namespace { Line 2992  namespace {
2992              else              else
2993                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2994    
2995              // load sample references              // load sample references (if auto loading is enabled)
2996              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2997                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2998                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2999                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3000                    }
3001                    GetSample(); // load global region sample reference
3002              }              }
             GetSample(); // load global region sample reference  
3003          } else {          } else {
3004              DimensionRegions = 0;              DimensionRegions = 0;
3005              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2477  namespace { Line 3056  namespace {
3056              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3057    
3058              // move 3prg to last position              // move 3prg to last position
3059              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3060          }          }
3061    
3062          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2623  namespace { Line 3202  namespace {
3202       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3203       */       */
3204      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3205            // some initial sanity checks of the given dimension definition
3206            if (pDimDef->zones < 2)
3207                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3208            if (pDimDef->bits < 1)
3209                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3210            if (pDimDef->dimension == dimension_samplechannel) {
3211                if (pDimDef->zones != 2)
3212                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3213                if (pDimDef->bits != 1)
3214                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3215            }
3216    
3217          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3218          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3219          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2798  namespace { Line 3389  namespace {
3389          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3390      }      }
3391    
3392        /** @brief Delete one split zone of a dimension (decrement zone amount).
3393         *
3394         * Instead of deleting an entire dimensions, this method will only delete
3395         * one particular split zone given by @a zone of the Region's dimension
3396         * given by @a type. So this method will simply decrement the amount of
3397         * zones by one of the dimension in question. To be able to do that, the
3398         * respective dimension must exist on this Region and it must have at least
3399         * 3 zones. All DimensionRegion objects associated with the zone will be
3400         * deleted.
3401         *
3402         * @param type - identifies the dimension where a zone shall be deleted
3403         * @param zone - index of the dimension split zone that shall be deleted
3404         * @throws gig::Exception if requested zone could not be deleted
3405         */
3406        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3407            dimension_def_t* oldDef = GetDimensionDefinition(type);
3408            if (!oldDef)
3409                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3410            if (oldDef->zones <= 2)
3411                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3412            if (zone < 0 || zone >= oldDef->zones)
3413                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3414    
3415            const int newZoneSize = oldDef->zones - 1;
3416    
3417            // create a temporary Region which just acts as a temporary copy
3418            // container and will be deleted at the end of this function and will
3419            // also not be visible through the API during this process
3420            gig::Region* tempRgn = NULL;
3421            {
3422                // adding these temporary chunks is probably not even necessary
3423                Instrument* instr = static_cast<Instrument*>(GetParent());
3424                RIFF::List* pCkInstrument = instr->pCkInstrument;
3425                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3426                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3427                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3428                tempRgn = new Region(instr, rgn);
3429            }
3430    
3431            // copy this region's dimensions (with already the dimension split size
3432            // requested by the arguments of this method call) to the temporary
3433            // region, and don't use Region::CopyAssign() here for this task, since
3434            // it would also alter fast lookup helper variables here and there
3435            dimension_def_t newDef;
3436            for (int i = 0; i < Dimensions; ++i) {
3437                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3438                // is this the dimension requested by the method arguments? ...
3439                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3440                    def.zones = newZoneSize;
3441                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3442                    newDef = def;
3443                }
3444                tempRgn->AddDimension(&def);
3445            }
3446    
3447            // find the dimension index in the tempRegion which is the dimension
3448            // type passed to this method (paranoidly expecting different order)
3449            int tempReducedDimensionIndex = -1;
3450            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3451                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3452                    tempReducedDimensionIndex = d;
3453                    break;
3454                }
3455            }
3456    
3457            // copy dimension regions from this region to the temporary region
3458            for (int iDst = 0; iDst < 256; ++iDst) {
3459                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3460                if (!dstDimRgn) continue;
3461                std::map<dimension_t,int> dimCase;
3462                bool isValidZone = true;
3463                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3464                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3465                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3466                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3467                    baseBits += dstBits;
3468                    // there are also DimensionRegion objects of unused zones, skip them
3469                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3470                        isValidZone = false;
3471                        break;
3472                    }
3473                }
3474                if (!isValidZone) continue;
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3478                if (dimCase[type] >= zone) dimCase[type]++;
3479                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3480                dstDimRgn->CopyAssign(srcDimRgn);
3481                // if this is the upper most zone of the dimension passed to this
3482                // method, then correct (raise) its upper limit to 127
3483                if (newDef.split_type == split_type_normal && isLastZone)
3484                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3485            }
3486    
3487            // now tempRegion's dimensions and DimensionRegions basically reflect
3488            // what we wanted to get for this actual Region here, so we now just
3489            // delete and recreate the dimension in question with the new amount
3490            // zones and then copy back from tempRegion      
3491            DeleteDimension(oldDef);
3492            AddDimension(&newDef);
3493            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3494                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3495                if (!srcDimRgn) continue;
3496                std::map<dimension_t,int> dimCase;
3497                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3498                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3499                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3500                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3501                    baseBits += srcBits;
3502                }
3503                // a bit paranoid: cope with the chance that the dimensions would
3504                // have different order in source and destination regions
3505                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3506                if (!dstDimRgn) continue;
3507                dstDimRgn->CopyAssign(srcDimRgn);
3508            }
3509    
3510            // delete temporary region
3511            delete tempRgn;
3512    
3513            UpdateVelocityTable();
3514        }
3515    
3516        /** @brief Divide split zone of a dimension in two (increment zone amount).
3517         *
3518         * This will increment the amount of zones for the dimension (given by
3519         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3520         * in the middle of its zone range in two. So the two zones resulting from
3521         * the zone being splitted, will be an equivalent copy regarding all their
3522         * articulation informations and sample reference. The two zones will only
3523         * differ in their zone's upper limit
3524         * (DimensionRegion::DimensionUpperLimits).
3525         *
3526         * @param type - identifies the dimension where a zone shall be splitted
3527         * @param zone - index of the dimension split zone that shall be splitted
3528         * @throws gig::Exception if requested zone could not be splitted
3529         */
3530        void Region::SplitDimensionZone(dimension_t type, int zone) {
3531            dimension_def_t* oldDef = GetDimensionDefinition(type);
3532            if (!oldDef)
3533                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3534            if (zone < 0 || zone >= oldDef->zones)
3535                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3536    
3537            const int newZoneSize = oldDef->zones + 1;
3538    
3539            // create a temporary Region which just acts as a temporary copy
3540            // container and will be deleted at the end of this function and will
3541            // also not be visible through the API during this process
3542            gig::Region* tempRgn = NULL;
3543            {
3544                // adding these temporary chunks is probably not even necessary
3545                Instrument* instr = static_cast<Instrument*>(GetParent());
3546                RIFF::List* pCkInstrument = instr->pCkInstrument;
3547                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3548                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3549                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3550                tempRgn = new Region(instr, rgn);
3551            }
3552    
3553            // copy this region's dimensions (with already the dimension split size
3554            // requested by the arguments of this method call) to the temporary
3555            // region, and don't use Region::CopyAssign() here for this task, since
3556            // it would also alter fast lookup helper variables here and there
3557            dimension_def_t newDef;
3558            for (int i = 0; i < Dimensions; ++i) {
3559                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3560                // is this the dimension requested by the method arguments? ...
3561                if (def.dimension == type) { // ... if yes, increment zone amount by one
3562                    def.zones = newZoneSize;
3563                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3564                    newDef = def;
3565                }
3566                tempRgn->AddDimension(&def);
3567            }
3568    
3569            // find the dimension index in the tempRegion which is the dimension
3570            // type passed to this method (paranoidly expecting different order)
3571            int tempIncreasedDimensionIndex = -1;
3572            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3573                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3574                    tempIncreasedDimensionIndex = d;
3575                    break;
3576                }
3577            }
3578    
3579            // copy dimension regions from this region to the temporary region
3580            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3581                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3582                if (!srcDimRgn) continue;
3583                std::map<dimension_t,int> dimCase;
3584                bool isValidZone = true;
3585                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3586                    const int srcBits = pDimensionDefinitions[d].bits;
3587                    dimCase[pDimensionDefinitions[d].dimension] =
3588                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3589                    // there are also DimensionRegion objects for unused zones, skip them
3590                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3591                        isValidZone = false;
3592                        break;
3593                    }
3594                    baseBits += srcBits;
3595                }
3596                if (!isValidZone) continue;
3597                // a bit paranoid: cope with the chance that the dimensions would
3598                // have different order in source and destination regions            
3599                if (dimCase[type] > zone) dimCase[type]++;
3600                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3601                dstDimRgn->CopyAssign(srcDimRgn);
3602                // if this is the requested zone to be splitted, then also copy
3603                // the source DimensionRegion to the newly created target zone
3604                // and set the old zones upper limit lower
3605                if (dimCase[type] == zone) {
3606                    // lower old zones upper limit
3607                    if (newDef.split_type == split_type_normal) {
3608                        const int high =
3609                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3610                        int low = 0;
3611                        if (zone > 0) {
3612                            std::map<dimension_t,int> lowerCase = dimCase;
3613                            lowerCase[type]--;
3614                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3615                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3616                        }
3617                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3618                    }
3619                    // fill the newly created zone of the divided zone as well
3620                    dimCase[type]++;
3621                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3622                    dstDimRgn->CopyAssign(srcDimRgn);
3623                }
3624            }
3625    
3626            // now tempRegion's dimensions and DimensionRegions basically reflect
3627            // what we wanted to get for this actual Region here, so we now just
3628            // delete and recreate the dimension in question with the new amount
3629            // zones and then copy back from tempRegion      
3630            DeleteDimension(oldDef);
3631            AddDimension(&newDef);
3632            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3633                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3634                if (!srcDimRgn) continue;
3635                std::map<dimension_t,int> dimCase;
3636                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3637                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3638                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3639                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3640                    baseBits += srcBits;
3641                }
3642                // a bit paranoid: cope with the chance that the dimensions would
3643                // have different order in source and destination regions
3644                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3645                if (!dstDimRgn) continue;
3646                dstDimRgn->CopyAssign(srcDimRgn);
3647            }
3648    
3649            // delete temporary region
3650            delete tempRgn;
3651    
3652            UpdateVelocityTable();
3653        }
3654    
3655        /** @brief Change type of an existing dimension.
3656         *
3657         * Alters the dimension type of a dimension already existing on this
3658         * region. If there is currently no dimension on this Region with type
3659         * @a oldType, then this call with throw an Exception. Likewise there are
3660         * cases where the requested dimension type cannot be performed. For example
3661         * if the new dimension type shall be gig::dimension_samplechannel, and the
3662         * current dimension has more than 2 zones. In such cases an Exception is
3663         * thrown as well.
3664         *
3665         * @param oldType - identifies the existing dimension to be changed
3666         * @param newType - to which dimension type it should be changed to
3667         * @throws gig::Exception if requested change cannot be performed
3668         */
3669        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3670            if (oldType == newType) return;
3671            dimension_def_t* def = GetDimensionDefinition(oldType);
3672            if (!def)
3673                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3674            if (newType == dimension_samplechannel && def->zones != 2)
3675                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3676            if (GetDimensionDefinition(newType))
3677                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3678            def->dimension  = newType;
3679            def->split_type = __resolveSplitType(newType);
3680        }
3681    
3682        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3683            uint8_t bits[8] = {};
3684            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3685                 it != DimCase.end(); ++it)
3686            {
3687                for (int d = 0; d < Dimensions; ++d) {
3688                    if (pDimensionDefinitions[d].dimension == it->first) {
3689                        bits[d] = it->second;
3690                        goto nextDimCaseSlice;
3691                    }
3692                }
3693                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3694                nextDimCaseSlice:
3695                ; // noop
3696            }
3697            return GetDimensionRegionByBit(bits);
3698        }
3699    
3700        /**
3701         * Searches in the current Region for a dimension of the given dimension
3702         * type and returns the precise configuration of that dimension in this
3703         * Region.
3704         *
3705         * @param type - dimension type of the sought dimension
3706         * @returns dimension definition or NULL if there is no dimension with
3707         *          sought type in this Region.
3708         */
3709        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3710            for (int i = 0; i < Dimensions; ++i)
3711                if (pDimensionDefinitions[i].dimension == type)
3712                    return &pDimensionDefinitions[i];
3713            return NULL;
3714        }
3715    
3716      Region::~Region() {      Region::~Region() {
3717          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3718              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2855  namespace { Line 3770  namespace {
3770              }              }
3771              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3772          }          }
3773          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3774            if (!dimreg) return NULL;
3775          if (veldim != -1) {          if (veldim != -1) {
3776              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3777              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3778                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3779              else // normal split type              else // normal split type
3780                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3781    
3782              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3783              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3784                dimreg = pDimensionRegions[dimregidx & 255];
3785          }          }
3786          return dimreg;          return dimreg;
3787      }      }
3788    
3789        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3790            uint8_t bits;
3791            int veldim = -1;
3792            int velbitpos;
3793            int bitpos = 0;
3794            int dimregidx = 0;
3795            for (uint i = 0; i < Dimensions; i++) {
3796                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3797                    // the velocity dimension must be handled after the other dimensions
3798                    veldim = i;
3799                    velbitpos = bitpos;
3800                } else {
3801                    switch (pDimensionDefinitions[i].split_type) {
3802                        case split_type_normal:
3803                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3804                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3805                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3806                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3807                                }
3808                            } else {
3809                                // gig2: evenly sized zones
3810                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3811                            }
3812                            break;
3813                        case split_type_bit: // the value is already the sought dimension bit number
3814                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3815                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3816                            break;
3817                    }
3818                    dimregidx |= bits << bitpos;
3819                }
3820                bitpos += pDimensionDefinitions[i].bits;
3821            }
3822            dimregidx &= 255;
3823            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3824            if (!dimreg) return -1;
3825            if (veldim != -1) {
3826                // (dimreg is now the dimension region for the lowest velocity)
3827                if (dimreg->VelocityTable) // custom defined zone ranges
3828                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3829                else // normal split type
3830                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3831    
3832                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3833                dimregidx |= (bits & limiter_mask) << velbitpos;
3834                dimregidx &= 255;
3835            }
3836            return dimregidx;
3837        }
3838    
3839      /**      /**
3840       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3841       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2917  namespace { Line 3884  namespace {
3884          }          }
3885          return NULL;          return NULL;
3886      }      }
3887        
3888        /**
3889         * Make a (semi) deep copy of the Region object given by @a orig
3890         * and assign it to this object.
3891         *
3892         * Note that all sample pointers referenced by @a orig are simply copied as
3893         * memory address. Thus the respective samples are shared, not duplicated!
3894         *
3895         * @param orig - original Region object to be copied from
3896         */
3897        void Region::CopyAssign(const Region* orig) {
3898            CopyAssign(orig, NULL);
3899        }
3900        
3901        /**
3902         * Make a (semi) deep copy of the Region object given by @a orig and
3903         * assign it to this object
3904         *
3905         * @param mSamples - crosslink map between the foreign file's samples and
3906         *                   this file's samples
3907         */
3908        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3909            // handle base classes
3910            DLS::Region::CopyAssign(orig);
3911            
3912            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3913                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3914            }
3915            
3916            // handle own member variables
3917            for (int i = Dimensions - 1; i >= 0; --i) {
3918                DeleteDimension(&pDimensionDefinitions[i]);
3919            }
3920            Layers = 0; // just to be sure
3921            for (int i = 0; i < orig->Dimensions; i++) {
3922                // we need to copy the dim definition here, to avoid the compiler
3923                // complaining about const-ness issue
3924                dimension_def_t def = orig->pDimensionDefinitions[i];
3925                AddDimension(&def);
3926            }
3927            for (int i = 0; i < 256; i++) {
3928                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3929                    pDimensionRegions[i]->CopyAssign(
3930                        orig->pDimensionRegions[i],
3931                        mSamples
3932                    );
3933                }
3934            }
3935            Layers = orig->Layers;
3936        }
3937    
3938    
3939    // *************** MidiRule ***************
3940    // *
3941    
3942        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3943            _3ewg->SetPos(36);
3944            Triggers = _3ewg->ReadUint8();
3945            _3ewg->SetPos(40);
3946            ControllerNumber = _3ewg->ReadUint8();
3947            _3ewg->SetPos(46);
3948            for (int i = 0 ; i < Triggers ; i++) {
3949                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3950                pTriggers[i].Descending = _3ewg->ReadUint8();
3951                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3952                pTriggers[i].Key = _3ewg->ReadUint8();
3953                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3954                pTriggers[i].Velocity = _3ewg->ReadUint8();
3955                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3956                _3ewg->ReadUint8();
3957            }
3958        }
3959    
3960        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3961            ControllerNumber(0),
3962            Triggers(0) {
3963        }
3964    
3965        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3966            pData[32] = 4;
3967            pData[33] = 16;
3968            pData[36] = Triggers;
3969            pData[40] = ControllerNumber;
3970            for (int i = 0 ; i < Triggers ; i++) {
3971                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3972                pData[47 + i * 8] = pTriggers[i].Descending;
3973                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3974                pData[49 + i * 8] = pTriggers[i].Key;
3975                pData[50 + i * 8] = pTriggers[i].NoteOff;
3976                pData[51 + i * 8] = pTriggers[i].Velocity;
3977                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3978            }
3979        }
3980    
3981        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3982            _3ewg->SetPos(36);
3983            LegatoSamples = _3ewg->ReadUint8(); // always 12
3984            _3ewg->SetPos(40);
3985            BypassUseController = _3ewg->ReadUint8();
3986            BypassKey = _3ewg->ReadUint8();
3987            BypassController = _3ewg->ReadUint8();
3988            ThresholdTime = _3ewg->ReadUint16();
3989            _3ewg->ReadInt16();
3990            ReleaseTime = _3ewg->ReadUint16();
3991            _3ewg->ReadInt16();
3992            KeyRange.low = _3ewg->ReadUint8();
3993            KeyRange.high = _3ewg->ReadUint8();
3994            _3ewg->SetPos(64);
3995            ReleaseTriggerKey = _3ewg->ReadUint8();
3996            AltSustain1Key = _3ewg->ReadUint8();
3997            AltSustain2Key = _3ewg->ReadUint8();
3998        }
3999    
4000        MidiRuleLegato::MidiRuleLegato() :
4001            LegatoSamples(12),
4002            BypassUseController(false),
4003            BypassKey(0),
4004            BypassController(1),
4005            ThresholdTime(20),
4006            ReleaseTime(20),
4007            ReleaseTriggerKey(0),
4008            AltSustain1Key(0),
4009            AltSustain2Key(0)
4010        {
4011            KeyRange.low = KeyRange.high = 0;
4012        }
4013    
4014        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4015            pData[32] = 0;
4016            pData[33] = 16;
4017            pData[36] = LegatoSamples;
4018            pData[40] = BypassUseController;
4019            pData[41] = BypassKey;
4020            pData[42] = BypassController;
4021            store16(&pData[43], ThresholdTime);
4022            store16(&pData[47], ReleaseTime);
4023            pData[51] = KeyRange.low;
4024            pData[52] = KeyRange.high;
4025            pData[64] = ReleaseTriggerKey;
4026            pData[65] = AltSustain1Key;
4027            pData[66] = AltSustain2Key;
4028        }
4029    
4030        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4031            _3ewg->SetPos(36);
4032            Articulations = _3ewg->ReadUint8();
4033            int flags = _3ewg->ReadUint8();
4034            Polyphonic = flags & 8;
4035            Chained = flags & 4;
4036            Selector = (flags & 2) ? selector_controller :
4037                (flags & 1) ? selector_key_switch : selector_none;
4038            Patterns = _3ewg->ReadUint8();
4039            _3ewg->ReadUint8(); // chosen row
4040            _3ewg->ReadUint8(); // unknown
4041            _3ewg->ReadUint8(); // unknown
4042            _3ewg->ReadUint8(); // unknown
4043            KeySwitchRange.low = _3ewg->ReadUint8();
4044            KeySwitchRange.high = _3ewg->ReadUint8();
4045            Controller = _3ewg->ReadUint8();
4046            PlayRange.low = _3ewg->ReadUint8();
4047            PlayRange.high = _3ewg->ReadUint8();
4048    
4049            int n = std::min(int(Articulations), 32);
4050            for (int i = 0 ; i < n ; i++) {
4051                _3ewg->ReadString(pArticulations[i], 32);
4052            }
4053            _3ewg->SetPos(1072);
4054            n = std::min(int(Patterns), 32);
4055            for (int i = 0 ; i < n ; i++) {
4056                _3ewg->ReadString(pPatterns[i].Name, 16);
4057                pPatterns[i].Size = _3ewg->ReadUint8();
4058                _3ewg->Read(&pPatterns[i][0], 1, 32);
4059            }
4060        }
4061    
4062        MidiRuleAlternator::MidiRuleAlternator() :
4063            Articulations(0),
4064            Patterns(0),
4065            Selector(selector_none),
4066            Controller(0),
4067            Polyphonic(false),
4068            Chained(false)
4069        {
4070            PlayRange.low = PlayRange.high = 0;
4071            KeySwitchRange.low = KeySwitchRange.high = 0;
4072        }
4073    
4074        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4075            pData[32] = 3;
4076            pData[33] = 16;
4077            pData[36] = Articulations;
4078            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4079                (Selector == selector_controller ? 2 :
4080                 (Selector == selector_key_switch ? 1 : 0));
4081            pData[38] = Patterns;
4082    
4083            pData[43] = KeySwitchRange.low;
4084            pData[44] = KeySwitchRange.high;
4085            pData[45] = Controller;
4086            pData[46] = PlayRange.low;
4087            pData[47] = PlayRange.high;
4088    
4089            char* str = reinterpret_cast<char*>(pData);
4090            int pos = 48;
4091            int n = std::min(int(Articulations), 32);
4092            for (int i = 0 ; i < n ; i++, pos += 32) {
4093                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4094            }
4095    
4096            pos = 1072;
4097            n = std::min(int(Patterns), 32);
4098            for (int i = 0 ; i < n ; i++, pos += 49) {
4099                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4100                pData[pos + 16] = pPatterns[i].Size;
4101                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4102            }
4103        }
4104    
4105    // *************** Script ***************
4106    // *
4107    
4108        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4109            pGroup = group;
4110            pChunk = ckScri;
4111            if (ckScri) { // object is loaded from file ...
4112                // read header
4113                uint32_t headerSize = ckScri->ReadUint32();
4114                Compression = (Compression_t) ckScri->ReadUint32();
4115                Encoding    = (Encoding_t) ckScri->ReadUint32();
4116                Language    = (Language_t) ckScri->ReadUint32();
4117                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4118                crc         = ckScri->ReadUint32();
4119                uint32_t nameSize = ckScri->ReadUint32();
4120                Name.resize(nameSize, ' ');
4121                for (int i = 0; i < nameSize; ++i)
4122                    Name[i] = ckScri->ReadUint8();
4123                // to handle potential future extensions of the header
4124                ckScri->SetPos(sizeof(int32_t) + headerSize);
4125                // read actual script data
4126                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4127                data.resize(scriptSize);
4128                for (int i = 0; i < scriptSize; ++i)
4129                    data[i] = ckScri->ReadUint8();
4130            } else { // this is a new script object, so just initialize it as such ...
4131                Compression = COMPRESSION_NONE;
4132                Encoding = ENCODING_ASCII;
4133                Language = LANGUAGE_NKSP;
4134                Bypass   = false;
4135                crc      = 0;
4136                Name     = "Unnamed Script";
4137            }
4138        }
4139    
4140        Script::~Script() {
4141        }
4142    
4143        /**
4144         * Returns the current script (i.e. as source code) in text format.
4145         */
4146        String Script::GetScriptAsText() {
4147            String s;
4148            s.resize(data.size(), ' ');
4149            memcpy(&s[0], &data[0], data.size());
4150            return s;
4151        }
4152    
4153        /**
4154         * Replaces the current script with the new script source code text given
4155         * by @a text.
4156         *
4157         * @param text - new script source code
4158         */
4159        void Script::SetScriptAsText(const String& text) {
4160            data.resize(text.size());
4161            memcpy(&data[0], &text[0], text.size());
4162        }
4163    
4164        void Script::UpdateChunks() {
4165            // recalculate CRC32 check sum
4166            __resetCRC(crc);
4167            __calculateCRC(&data[0], data.size(), crc);
4168            __encodeCRC(crc);
4169            // make sure chunk exists and has the required size
4170            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4171            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4172            else pChunk->Resize(chunkSize);
4173            // fill the chunk data to be written to disk
4174            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4175            int pos = 0;
4176            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4177            pos += sizeof(int32_t);
4178            store32(&pData[pos], Compression);
4179            pos += sizeof(int32_t);
4180            store32(&pData[pos], Encoding);
4181            pos += sizeof(int32_t);
4182            store32(&pData[pos], Language);
4183            pos += sizeof(int32_t);
4184            store32(&pData[pos], Bypass ? 1 : 0);
4185            pos += sizeof(int32_t);
4186            store32(&pData[pos], crc);
4187            pos += sizeof(int32_t);
4188            store32(&pData[pos], Name.size());
4189            pos += sizeof(int32_t);
4190            for (int i = 0; i < Name.size(); ++i, ++pos)
4191                pData[pos] = Name[i];
4192            for (int i = 0; i < data.size(); ++i, ++pos)
4193                pData[pos] = data[i];
4194        }
4195    
4196        /**
4197         * Move this script from its current ScriptGroup to another ScriptGroup
4198         * given by @a pGroup.
4199         *
4200         * @param pGroup - script's new group
4201         */
4202        void Script::SetGroup(ScriptGroup* pGroup) {
4203            if (this->pGroup = pGroup) return;
4204            if (pChunk)
4205                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4206            this->pGroup = pGroup;
4207        }
4208    
4209        /**
4210         * Returns the script group this script currently belongs to. Each script
4211         * is a member of exactly one ScriptGroup.
4212         *
4213         * @returns current script group
4214         */
4215        ScriptGroup* Script::GetGroup() const {
4216            return pGroup;
4217        }
4218    
4219        void Script::RemoveAllScriptReferences() {
4220            File* pFile = pGroup->pFile;
4221            for (int i = 0; pFile->GetInstrument(i); ++i) {
4222                Instrument* instr = pFile->GetInstrument(i);
4223                instr->RemoveScript(this);
4224            }
4225        }
4226    
4227    // *************** ScriptGroup ***************
4228    // *
4229    
4230        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4231            pFile = file;
4232            pList = lstRTIS;
4233            pScripts = NULL;
4234            if (lstRTIS) {
4235                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4236                ::LoadString(ckName, Name);
4237            } else {
4238                Name = "Default Group";
4239            }
4240        }
4241    
4242        ScriptGroup::~ScriptGroup() {
4243            if (pScripts) {
4244                std::list<Script*>::iterator iter = pScripts->begin();
4245                std::list<Script*>::iterator end  = pScripts->end();
4246                while (iter != end) {
4247                    delete *iter;
4248                    ++iter;
4249                }
4250                delete pScripts;
4251            }
4252        }
4253    
4254        void ScriptGroup::UpdateChunks() {
4255            if (pScripts) {
4256                if (!pList)
4257                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4258    
4259                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4260                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4261    
4262                for (std::list<Script*>::iterator it = pScripts->begin();
4263                     it != pScripts->end(); ++it)
4264                {
4265                    (*it)->UpdateChunks();
4266                }
4267            }
4268        }
4269    
4270        /** @brief Get instrument script.
4271         *
4272         * Returns the real-time instrument script with the given index.
4273         *
4274         * @param index - number of the sought script (0..n)
4275         * @returns sought script or NULL if there's no such script
4276         */
4277        Script* ScriptGroup::GetScript(uint index) {
4278            if (!pScripts) LoadScripts();
4279            std::list<Script*>::iterator it = pScripts->begin();
4280            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4281                if (i == index) return *it;
4282            return NULL;
4283        }
4284    
4285        /** @brief Add new instrument script.
4286         *
4287         * Adds a new real-time instrument script to the file. The script is not
4288         * actually used / executed unless it is referenced by an instrument to be
4289         * used. This is similar to samples, which you can add to a file, without
4290         * an instrument necessarily actually using it.
4291         *
4292         * You have to call Save() to make this persistent to the file.
4293         *
4294         * @return new empty script object
4295         */
4296        Script* ScriptGroup::AddScript() {
4297            if (!pScripts) LoadScripts();
4298            Script* pScript = new Script(this, NULL);
4299            pScripts->push_back(pScript);
4300            return pScript;
4301        }
4302    
4303        /** @brief Delete an instrument script.
4304         *
4305         * This will delete the given real-time instrument script. References of
4306         * instruments that are using that script will be removed accordingly.
4307         *
4308         * You have to call Save() to make this persistent to the file.
4309         *
4310         * @param pScript - script to delete
4311         * @throws gig::Exception if given script could not be found
4312         */
4313        void ScriptGroup::DeleteScript(Script* pScript) {
4314            if (!pScripts) LoadScripts();
4315            std::list<Script*>::iterator iter =
4316                find(pScripts->begin(), pScripts->end(), pScript);
4317            if (iter == pScripts->end())
4318                throw gig::Exception("Could not delete script, could not find given script");
4319            pScripts->erase(iter);
4320            pScript->RemoveAllScriptReferences();
4321            if (pScript->pChunk)
4322                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4323            delete pScript;
4324        }
4325    
4326        void ScriptGroup::LoadScripts() {
4327            if (pScripts) return;
4328            pScripts = new std::list<Script*>;
4329            if (!pList) return;
4330    
4331            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4332                 ck = pList->GetNextSubChunk())
4333            {
4334                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4335                    pScripts->push_back(new Script(this, ck));
4336                }
4337            }
4338        }
4339    
4340  // *************** Instrument ***************  // *************** Instrument ***************
4341  // *  // *
# Line 2940  namespace { Line 4357  namespace {
4357          PianoReleaseMode = false;          PianoReleaseMode = false;
4358          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4359          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4360            pMidiRules = new MidiRule*[3];
4361            pMidiRules[0] = NULL;
4362            pScriptRefs = NULL;
4363    
4364          // Loading          // Loading
4365          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2954  namespace { Line 4374  namespace {
4374                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4375                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4376                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4377    
4378                    if (_3ewg->GetSize() > 32) {
4379                        // read MIDI rules
4380                        int i = 0;
4381                        _3ewg->SetPos(32);
4382                        uint8_t id1 = _3ewg->ReadUint8();
4383                        uint8_t id2 = _3ewg->ReadUint8();
4384    
4385                        if (id2 == 16) {
4386                            if (id1 == 4) {
4387                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4388                            } else if (id1 == 0) {
4389                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4390                            } else if (id1 == 3) {
4391                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4392                            } else {
4393                                pMidiRules[i++] = new MidiRuleUnknown;
4394                            }
4395                        }
4396                        else if (id1 != 0 || id2 != 0) {
4397                            pMidiRules[i++] = new MidiRuleUnknown;
4398                        }
4399                        //TODO: all the other types of rules
4400    
4401                        pMidiRules[i] = NULL;
4402                    }
4403                }
4404            }
4405    
4406            if (pFile->GetAutoLoad()) {
4407                if (!pRegions) pRegions = new RegionList;
4408                RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4409                if (lrgn) {
4410                    RIFF::List* rgn = lrgn->GetFirstSubList();
4411                    while (rgn) {
4412                        if (rgn->GetListType() == LIST_TYPE_RGN) {
4413                            __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4414                            pRegions->push_back(new Region(this, rgn));
4415                        }
4416                        rgn = lrgn->GetNextSubList();
4417                    }
4418                    // Creating Region Key Table for fast lookup
4419                    UpdateRegionKeyTable();
4420              }              }
4421          }          }
4422    
4423          if (!pRegions) pRegions = new RegionList;          // own gig format extensions
4424          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4425          if (lrgn) {          if (lst3LS) {
4426              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4427              while (rgn) {              if (ckSCSL) {
4428                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  int headerSize = ckSCSL->ReadUint32();
4429                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                  int slotCount  = ckSCSL->ReadUint32();
4430                      pRegions->push_back(new Region(this, rgn));                  if (slotCount) {
4431                        int slotSize  = ckSCSL->ReadUint32();
4432                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4433                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4434                        for (int i = 0; i < slotCount; ++i) {
4435                            _ScriptPooolEntry e;
4436                            e.fileOffset = ckSCSL->ReadUint32();
4437                            e.bypass     = ckSCSL->ReadUint32() & 1;
4438                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4439                            scriptPoolFileOffsets.push_back(e);
4440                        }
4441                  }                  }
                 rgn = lrgn->GetNextSubList();  
4442              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4443          }          }
4444    
4445          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
# Line 2988  namespace { Line 4458  namespace {
4458      }      }
4459    
4460      Instrument::~Instrument() {      Instrument::~Instrument() {
4461            for (int i = 0 ; pMidiRules[i] ; i++) {
4462                delete pMidiRules[i];
4463            }
4464            delete[] pMidiRules;
4465            if (pScriptRefs) delete pScriptRefs;
4466      }      }
4467    
4468      /**      /**
# Line 3034  namespace { Line 4509  namespace {
4509                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4510          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4511          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4512    
4513            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4514                pData[32] = 0;
4515                pData[33] = 0;
4516            } else {
4517                for (int i = 0 ; pMidiRules[i] ; i++) {
4518                    pMidiRules[i]->UpdateChunks(pData);
4519                }
4520            }
4521    
4522            // own gig format extensions
4523           if (pScriptRefs) {
4524               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4525               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4526               const int slotCount = pScriptRefs->size();
4527               const int headerSize = 3 * sizeof(uint32_t);
4528               const int slotSize  = 2 * sizeof(uint32_t);
4529               const int totalChunkSize = headerSize + slotCount * slotSize;
4530               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4531               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4532               else ckSCSL->Resize(totalChunkSize);
4533               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4534               int pos = 0;
4535               store32(&pData[pos], headerSize);
4536               pos += sizeof(uint32_t);
4537               store32(&pData[pos], slotCount);
4538               pos += sizeof(uint32_t);
4539               store32(&pData[pos], slotSize);
4540               pos += sizeof(uint32_t);
4541               for (int i = 0; i < slotCount; ++i) {
4542                   // arbitrary value, the actual file offset will be updated in
4543                   // UpdateScriptFileOffsets() after the file has been resized
4544                   int bogusFileOffset = 0;
4545                   store32(&pData[pos], bogusFileOffset);
4546                   pos += sizeof(uint32_t);
4547                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4548                   pos += sizeof(uint32_t);
4549               }
4550           }
4551        }
4552    
4553        void Instrument::UpdateScriptFileOffsets() {
4554           // own gig format extensions
4555           if (pScriptRefs) {
4556               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4557               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4558               const int slotCount = pScriptRefs->size();
4559               const int headerSize = 3 * sizeof(uint32_t);
4560               ckSCSL->SetPos(headerSize);
4561               for (int i = 0; i < slotCount; ++i) {
4562                   uint32_t fileOffset =
4563                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4564                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4565                        CHUNK_HEADER_SIZE;
4566                   ckSCSL->WriteUint32(&fileOffset);
4567                   // jump over flags entry (containing the bypass flag)
4568                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4569               }
4570           }        
4571      }      }
4572    
4573      /**      /**
# Line 3102  namespace { Line 4636  namespace {
4636          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4637      }      }
4638    
4639        /**
4640         * Returns a MIDI rule of the instrument.
4641         *
4642         * The list of MIDI rules, at least in gig v3, always contains at
4643         * most two rules. The second rule can only be the DEF filter
4644         * (which currently isn't supported by libgig).
4645         *
4646         * @param i - MIDI rule number
4647         * @returns   pointer address to MIDI rule number i or NULL if there is none
4648         */
4649        MidiRule* Instrument::GetMidiRule(int i) {
4650            return pMidiRules[i];
4651        }
4652    
4653        /**
4654         * Adds the "controller trigger" MIDI rule to the instrument.
4655         *
4656         * @returns the new MIDI rule
4657         */
4658        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4659            delete pMidiRules[0];
4660            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4661            pMidiRules[0] = r;
4662            pMidiRules[1] = 0;
4663            return r;
4664        }
4665    
4666        /**
4667         * Adds the legato MIDI rule to the instrument.
4668         *
4669         * @returns the new MIDI rule
4670         */
4671        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4672            delete pMidiRules[0];
4673            MidiRuleLegato* r = new MidiRuleLegato;
4674            pMidiRules[0] = r;
4675            pMidiRules[1] = 0;
4676            return r;
4677        }
4678    
4679        /**
4680         * Adds the alternator MIDI rule to the instrument.
4681         *
4682         * @returns the new MIDI rule
4683         */
4684        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4685            delete pMidiRules[0];
4686            MidiRuleAlternator* r = new MidiRuleAlternator;
4687            pMidiRules[0] = r;
4688            pMidiRules[1] = 0;
4689            return r;
4690        }
4691    
4692        /**
4693         * Deletes a MIDI rule from the instrument.
4694         *
4695         * @param i - MIDI rule number
4696         */
4697        void Instrument::DeleteMidiRule(int i) {
4698            delete pMidiRules[i];
4699            pMidiRules[i] = 0;
4700        }
4701    
4702        void Instrument::LoadScripts() {
4703            if (pScriptRefs) return;
4704            pScriptRefs = new std::vector<_ScriptPooolRef>;
4705            if (scriptPoolFileOffsets.empty()) return;
4706            File* pFile = (File*) GetParent();
4707            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4708                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4709                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4710                    ScriptGroup* group = pFile->GetScriptGroup(i);
4711                    for (uint s = 0; group->GetScript(s); ++s) {
4712                        Script* script = group->GetScript(s);
4713                        if (script->pChunk) {
4714                            uint32_t offset = script->pChunk->GetFilePos() -
4715                                              script->pChunk->GetPos() -
4716                                              CHUNK_HEADER_SIZE;
4717                            if (offset == soughtOffset)
4718                            {
4719                                _ScriptPooolRef ref;
4720                                ref.script = script;
4721                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4722                                pScriptRefs->push_back(ref);
4723                                break;
4724                            }
4725                        }
4726                    }
4727                }
4728            }
4729            // we don't need that anymore
4730            scriptPoolFileOffsets.clear();
4731        }
4732    
4733        /** @brief Get instrument script (gig format extension).
4734         *
4735         * Returns the real-time instrument script of instrument script slot
4736         * @a index.
4737         *
4738         * @note This is an own format extension which did not exist i.e. in the
4739         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4740         * gigedit.
4741         *
4742         * @param index - instrument script slot index
4743         * @returns script or NULL if index is out of bounds
4744         */
4745        Script* Instrument::GetScriptOfSlot(uint index) {
4746            LoadScripts();
4747            if (index >= pScriptRefs->size()) return NULL;
4748            return pScriptRefs->at(index).script;
4749        }
4750    
4751        /** @brief Add new instrument script slot (gig format extension).
4752         *
4753         * Add the given real-time instrument script reference to this instrument,
4754         * which shall be executed by the sampler for for this instrument. The
4755         * script will be added to the end of the script list of this instrument.
4756         * The positions of the scripts in the Instrument's Script list are
4757         * relevant, because they define in which order they shall be executed by
4758         * the sampler. For this reason it is also legal to add the same script
4759         * twice to an instrument, for example you might have a script called
4760         * "MyFilter" which performs an event filter task, and you might have
4761         * another script called "MyNoteTrigger" which triggers new notes, then you
4762         * might for example have the following list of scripts on the instrument:
4763         *
4764         * 1. Script "MyFilter"
4765         * 2. Script "MyNoteTrigger"
4766         * 3. Script "MyFilter"
4767         *
4768         * Which would make sense, because the 2nd script launched new events, which
4769         * you might need to filter as well.
4770         *
4771         * There are two ways to disable / "bypass" scripts. You can either disable
4772         * a script locally for the respective script slot on an instrument (i.e. by
4773         * passing @c false to the 2nd argument of this method, or by calling
4774         * SetScriptBypassed()). Or you can disable a script globally for all slots
4775         * and all instruments by setting Script::Bypass.
4776         *
4777         * @note This is an own format extension which did not exist i.e. in the
4778         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4779         * gigedit.
4780         *
4781         * @param pScript - script that shall be executed for this instrument
4782         * @param bypass  - if enabled, the sampler shall skip executing this
4783         *                  script (in the respective list position)
4784         * @see SetScriptBypassed()
4785         */
4786        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4787            LoadScripts();
4788            _ScriptPooolRef ref = { pScript, bypass };
4789            pScriptRefs->push_back(ref);
4790        }
4791    
4792        /** @brief Flip two script slots with each other (gig format extension).
4793         *
4794         * Swaps the position of the two given scripts in the Instrument's Script
4795         * list. The positions of the scripts in the Instrument's Script list are
4796         * relevant, because they define in which order they shall be executed by
4797         * the sampler.
4798         *
4799         * @note This is an own format extension which did not exist i.e. in the
4800         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4801         * gigedit.
4802         *
4803         * @param index1 - index of the first script slot to swap
4804         * @param index2 - index of the second script slot to swap
4805         */
4806        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4807            LoadScripts();
4808            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4809                return;
4810            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4811            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4812            (*pScriptRefs)[index2] = tmp;
4813        }
4814    
4815        /** @brief Remove script slot.
4816         *
4817         * Removes the script slot with the given slot index.
4818         *
4819         * @param index - index of script slot to remove
4820         */
4821        void Instrument::RemoveScriptSlot(uint index) {
4822            LoadScripts();
4823            if (index >= pScriptRefs->size()) return;
4824            pScriptRefs->erase( pScriptRefs->begin() + index );
4825        }
4826    
4827        /** @brief Remove reference to given Script (gig format extension).
4828         *
4829         * This will remove all script slots on the instrument which are referencing
4830         * the given script.
4831         *
4832         * @note This is an own format extension which did not exist i.e. in the
4833         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4834         * gigedit.
4835         *
4836         * @param pScript - script reference to remove from this instrument
4837         * @see RemoveScriptSlot()
4838         */
4839        void Instrument::RemoveScript(Script* pScript) {
4840            LoadScripts();
4841            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4842                if ((*pScriptRefs)[i].script == pScript) {
4843                    pScriptRefs->erase( pScriptRefs->begin() + i );
4844                }
4845            }
4846        }
4847    
4848        /** @brief Instrument's amount of script slots.
4849         *
4850         * This method returns the amount of script slots this instrument currently
4851         * uses.
4852         *
4853         * A script slot is a reference of a real-time instrument script to be
4854         * executed by the sampler. The scripts will be executed by the sampler in
4855         * sequence of the slots. One (same) script may be referenced multiple
4856         * times in different slots.
4857         *
4858         * @note This is an own format extension which did not exist i.e. in the
4859         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4860         * gigedit.
4861         */
4862        uint Instrument::ScriptSlotCount() const {
4863            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4864        }
4865    
4866        /** @brief Whether script execution shall be skipped.
4867         *
4868         * Defines locally for the Script reference slot in the Instrument's Script
4869         * list, whether the script shall be skipped by the sampler regarding
4870         * execution.
4871         *
4872         * It is also possible to ignore exeuction of the script globally, for all
4873         * slots and for all instruments by setting Script::Bypass.
4874         *
4875         * @note This is an own format extension which did not exist i.e. in the
4876         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4877         * gigedit.
4878         *
4879         * @param index - index of the script slot on this instrument
4880         * @see Script::Bypass
4881         */
4882        bool Instrument::IsScriptSlotBypassed(uint index) {
4883            if (index >= ScriptSlotCount()) return false;
4884            return pScriptRefs ? pScriptRefs->at(index).bypass
4885                               : scriptPoolFileOffsets.at(index).bypass;
4886            
4887        }
4888    
4889        /** @brief Defines whether execution shall be skipped.
4890         *
4891         * You can call this method to define locally whether or whether not the
4892         * given script slot shall be executed by the sampler.
4893         *
4894         * @note This is an own format extension which did not exist i.e. in the
4895         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4896         * gigedit.
4897         *
4898         * @param index - script slot index on this instrument
4899         * @param bBypass - if true, the script slot will be skipped by the sampler
4900         * @see Script::Bypass
4901         */
4902        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4903            if (index >= ScriptSlotCount()) return;
4904            if (pScriptRefs)
4905                pScriptRefs->at(index).bypass = bBypass;
4906            else
4907                scriptPoolFileOffsets.at(index).bypass = bBypass;
4908        }
4909    
4910        /**
4911         * Make a (semi) deep copy of the Instrument object given by @a orig
4912         * and assign it to this object.
4913         *
4914         * Note that all sample pointers referenced by @a orig are simply copied as
4915         * memory address. Thus the respective samples are shared, not duplicated!
4916         *
4917         * @param orig - original Instrument object to be copied from
4918         */
4919        void Instrument::CopyAssign(const Instrument* orig) {
4920            CopyAssign(orig, NULL);
4921        }
4922            
4923        /**
4924         * Make a (semi) deep copy of the Instrument object given by @a orig
4925         * and assign it to this object.
4926         *
4927         * @param orig - original Instrument object to be copied from
4928         * @param mSamples - crosslink map between the foreign file's samples and
4929         *                   this file's samples
4930         */
4931        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4932            // handle base class
4933            // (without copying DLS region stuff)
4934            DLS::Instrument::CopyAssignCore(orig);
4935            
4936            // handle own member variables
4937            Attenuation = orig->Attenuation;
4938            EffectSend = orig->EffectSend;
4939            FineTune = orig->FineTune;
4940            PitchbendRange = orig->PitchbendRange;
4941            PianoReleaseMode = orig->PianoReleaseMode;
4942            DimensionKeyRange = orig->DimensionKeyRange;
4943            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
4944            pScriptRefs = orig->pScriptRefs;
4945            
4946            // free old midi rules
4947            for (int i = 0 ; pMidiRules[i] ; i++) {
4948                delete pMidiRules[i];
4949            }
4950            //TODO: MIDI rule copying
4951            pMidiRules[0] = NULL;
4952            
4953            // delete all old regions
4954            while (Regions) DeleteRegion(GetFirstRegion());
4955            // create new regions and copy them from original
4956            {
4957                RegionList::const_iterator it = orig->pRegions->begin();
4958                for (int i = 0; i < orig->Regions; ++i, ++it) {
4959                    Region* dstRgn = AddRegion();
4960                    //NOTE: Region does semi-deep copy !
4961                    dstRgn->CopyAssign(
4962                        static_cast<gig::Region*>(*it),
4963                        mSamples
4964                    );
4965                }
4966            }
4967    
4968            UpdateRegionKeyTable();
4969        }
4970    
4971    
4972  // *************** Group ***************  // *************** Group ***************
# Line 3259  namespace { Line 5124  namespace {
5124      };      };
5125    
5126      File::File() : DLS::File() {      File::File() : DLS::File() {
5127            bAutoLoad = true;
5128          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5129          pGroups = NULL;          pGroups = NULL;
5130            pScriptGroups = NULL;
5131          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5132          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5133    
# Line 3274  namespace { Line 5141  namespace {
5141      }      }
5142    
5143      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5144            bAutoLoad = true;
5145          pGroups = NULL;          pGroups = NULL;
5146            pScriptGroups = NULL;
5147          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5148      }      }
5149    
# Line 3288  namespace { Line 5157  namespace {
5157              }              }
5158              delete pGroups;              delete pGroups;
5159          }          }
5160            if (pScriptGroups) {
5161                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5162                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5163                while (iter != end) {
5164                    delete *iter;
5165                    ++iter;
5166                }
5167                delete pScriptGroups;
5168            }
5169      }      }
5170    
5171      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3302  namespace { Line 5180  namespace {
5180          SamplesIterator++;          SamplesIterator++;
5181          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5182      }      }
5183        
5184        /**
5185         * Returns Sample object of @a index.
5186         *
5187         * @returns sample object or NULL if index is out of bounds
5188         */
5189        Sample* File::GetSample(uint index) {
5190            if (!pSamples) LoadSamples();
5191            if (!pSamples) return NULL;
5192            DLS::File::SampleList::iterator it = pSamples->begin();
5193            for (int i = 0; i < index; ++i) {
5194                ++it;
5195                if (it == pSamples->end()) return NULL;
5196            }
5197            if (it == pSamples->end()) return NULL;
5198            return static_cast<gig::Sample*>( *it );
5199        }
5200    
5201      /** @brief Add a new sample.      /** @brief Add a new sample.
5202       *       *
# Line 3343  namespace { Line 5238  namespace {
5238          pSamples->erase(iter);          pSamples->erase(iter);
5239          delete pSample;          delete pSample;
5240    
5241            SampleList::iterator tmp = SamplesIterator;
5242          // remove all references to the sample          // remove all references to the sample
5243          for (Instrument* instrument = GetFirstInstrument() ; instrument ;          for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5244               instrument = GetNextInstrument()) {               instrument = GetNextInstrument()) {
# Line 3357  namespace { Line 5253  namespace {
5253                  }                  }
5254              }              }
5255          }          }
5256            SamplesIterator = tmp; // restore iterator
5257      }      }
5258    
5259      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3447  namespace { Line 5344  namespace {
5344              progress_t subprogress;              progress_t subprogress;
5345              __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
5346              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5347              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5348                    GetFirstSample(&subprogress); // now force all samples to be loaded
5349              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5350    
5351              // instrument loading subtask              // instrument loading subtask
# Line 3496  namespace { Line 5394  namespace {
5394         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5395         return pInstrument;         return pInstrument;
5396      }      }
5397        
5398        /** @brief Add a duplicate of an existing instrument.
5399         *
5400         * Duplicates the instrument definition given by @a orig and adds it
5401         * to this file. This allows in an instrument editor application to
5402         * easily create variations of an instrument, which will be stored in
5403         * the same .gig file, sharing i.e. the same samples.
5404         *
5405         * Note that all sample pointers referenced by @a orig are simply copied as
5406         * memory address. Thus the respective samples are shared, not duplicated!
5407         *
5408         * You have to call Save() to make this persistent to the file.
5409         *
5410         * @param orig - original instrument to be copied
5411         * @returns duplicated copy of the given instrument
5412         */
5413        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5414            Instrument* instr = AddInstrument();
5415            instr->CopyAssign(orig);
5416            return instr;
5417        }
5418        
5419        /** @brief Add content of another existing file.
5420         *
5421         * Duplicates the samples, groups and instruments of the original file
5422         * given by @a pFile and adds them to @c this File. In case @c this File is
5423         * a new one that you haven't saved before, then you have to call
5424         * SetFileName() before calling AddContentOf(), because this method will
5425         * automatically save this file during operation, which is required for
5426         * writing the sample waveform data by disk streaming.
5427         *
5428         * @param pFile - original file whose's content shall be copied from
5429         */
5430        void File::AddContentOf(File* pFile) {
5431            static int iCallCount = -1;
5432            iCallCount++;
5433            std::map<Group*,Group*> mGroups;
5434            std::map<Sample*,Sample*> mSamples;
5435            
5436            // clone sample groups
5437            for (int i = 0; pFile->GetGroup(i); ++i) {
5438                Group* g = AddGroup();
5439                g->Name =
5440                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5441                mGroups[pFile->GetGroup(i)] = g;
5442            }
5443            
5444            // clone samples (not waveform data here yet)
5445            for (int i = 0; pFile->GetSample(i); ++i) {
5446                Sample* s = AddSample();
5447                s->CopyAssignMeta(pFile->GetSample(i));
5448                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5449                mSamples[pFile->GetSample(i)] = s;
5450            }
5451            
5452            //BUG: For some reason this method only works with this additional
5453            //     Save() call in between here.
5454            //
5455            // Important: The correct one of the 2 Save() methods has to be called
5456            // here, depending on whether the file is completely new or has been
5457            // saved to disk already, otherwise it will result in data corruption.
5458            if (pRIFF->IsNew())
5459                Save(GetFileName());
5460            else
5461                Save();
5462            
5463            // clone instruments
5464            // (passing the crosslink table here for the cloned samples)
5465            for (int i = 0; pFile->GetInstrument(i); ++i) {
5466                Instrument* instr = AddInstrument();
5467                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5468            }
5469            
5470            // Mandatory: file needs to be saved to disk at this point, so this
5471            // file has the correct size and data layout for writing the samples'
5472            // waveform data to disk.
5473            Save();
5474            
5475            // clone samples' waveform data
5476            // (using direct read & write disk streaming)
5477            for (int i = 0; pFile->GetSample(i); ++i) {
5478                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5479            }
5480        }
5481    
5482      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5483       *       *
# Line 3598  namespace { Line 5580  namespace {
5580          return NULL;          return NULL;
5581      }      }
5582    
5583        /**
5584         * Returns the group with the given group name.
5585         *
5586         * Note: group names don't have to be unique in the gig format! So there
5587         * can be multiple groups with the same name. This method will simply
5588         * return the first group found with the given name.
5589         *
5590         * @param name - name of the sought group
5591         * @returns sought group or NULL if there's no group with that name
5592         */
5593        Group* File::GetGroup(String name) {
5594            if (!pGroups) LoadGroups();
5595            GroupsIterator = pGroups->begin();
5596            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5597                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5598            return NULL;
5599        }
5600    
5601      Group* File::AddGroup() {      Group* File::AddGroup() {
5602          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5603          // there must always be at least one group          // there must always be at least one group
# Line 3678  namespace { Line 5678  namespace {
5678          }          }
5679      }      }
5680    
5681        /** @brief Get instrument script group (by index).
5682         *
5683         * Returns the real-time instrument script group with the given index.
5684         *
5685         * @param index - number of the sought group (0..n)
5686         * @returns sought script group or NULL if there's no such group
5687         */
5688        ScriptGroup* File::GetScriptGroup(uint index) {
5689            if (!pScriptGroups) LoadScriptGroups();
5690            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5691            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5692                if (i == index) return *it;
5693            return NULL;
5694        }
5695    
5696        /** @brief Get instrument script group (by name).
5697         *
5698         * Returns the first real-time instrument script group found with the given
5699         * group name. Note that group names may not necessarily be unique.
5700         *
5701         * @param name - name of the sought script group
5702         * @returns sought script group or NULL if there's no such group
5703         */
5704        ScriptGroup* File::GetScriptGroup(const String& name) {
5705            if (!pScriptGroups) LoadScriptGroups();
5706            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5707            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5708                if ((*it)->Name == name) return *it;
5709            return NULL;
5710        }
5711    
5712        /** @brief Add new instrument script group.
5713         *
5714         * Adds a new, empty real-time instrument script group to the file.
5715         *
5716         * You have to call Save() to make this persistent to the file.
5717         *
5718         * @return new empty script group
5719         */
5720        ScriptGroup* File::AddScriptGroup() {
5721            if (!pScriptGroups) LoadScriptGroups();
5722            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5723            pScriptGroups->push_back(pScriptGroup);
5724            return pScriptGroup;
5725        }
5726    
5727        /** @brief Delete an instrument script group.
5728         *
5729         * This will delete the given real-time instrument script group and all its
5730         * instrument scripts it contains. References inside instruments that are
5731         * using the deleted scripts will be removed from the respective instruments
5732         * accordingly.
5733         *
5734         * You have to call Save() to make this persistent to the file.
5735         *
5736         * @param pScriptGroup - script group to delete
5737         * @throws gig::Exception if given script group could not be found
5738         */
5739        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5740            if (!pScriptGroups) LoadScriptGroups();
5741            std::list<ScriptGroup*>::iterator iter =
5742                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5743            if (iter == pScriptGroups->end())
5744                throw gig::Exception("Could not delete script group, could not find given script group");
5745            pScriptGroups->erase(iter);
5746            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5747                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5748            if (pScriptGroup->pList)
5749                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5750            delete pScriptGroup;
5751        }
5752    
5753        void File::LoadScriptGroups() {
5754            if (pScriptGroups) return;
5755            pScriptGroups = new std::list<ScriptGroup*>;
5756            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5757            if (lstLS) {
5758                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5759                     lst = lstLS->GetNextSubList())
5760                {
5761                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5762                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5763                    }
5764                }
5765            }
5766        }
5767    
5768      /**      /**
5769       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
5770       * to the respective RIFF chunks. You have to call Save() to make changes       * to the respective RIFF chunks. You have to call Save() to make changes
# Line 3693  namespace { Line 5780  namespace {
5780    
5781          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5782    
5783            // update own gig format extension chunks
5784            // (not part of the GigaStudio 4 format)
5785            //
5786            // This must be performed before writing the chunks for instruments,
5787            // because the instruments' script slots will write the file offsets
5788            // of the respective instrument script chunk as reference.
5789            if (pScriptGroups) {
5790                RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5791                if (pScriptGroups->empty()) {
5792                    if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5793                } else {
5794                    if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5795    
5796                    // Update instrument script (group) chunks.
5797    
5798                    for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5799                         it != pScriptGroups->end(); ++it)
5800                    {
5801                        (*it)->UpdateChunks();
5802                    }
5803                }
5804            }
5805    
5806          // first update base class's chunks          // first update base class's chunks
5807          DLS::File::UpdateChunks();          DLS::File::UpdateChunks();
5808    
# Line 3708  namespace { Line 5818  namespace {
5818    
5819          // update group's chunks          // update group's chunks
5820          if (pGroups) {          if (pGroups) {
5821              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
5822              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
5823              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5824                  (*iter)->UpdateChunks();              if (!_3gri) {
5825                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5826                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5827              }              }
5828                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5829                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5830    
5831              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
5832                // (before updating the Group chunks)
5833              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
5834                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5835                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
5836                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5837                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5838                  }                  }
5839              }              }
5840    
5841                std::list<Group*>::iterator iter = pGroups->begin();
5842                std::list<Group*>::iterator end  = pGroups->end();
5843                for (; iter != end; ++iter) {
5844                    (*iter)->UpdateChunks();
5845                }
5846          }          }
5847    
5848          // update einf chunk          // update einf chunk
# Line 3853  namespace { Line 5973  namespace {
5973              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5974          }          }
5975      }      }
5976        
5977        void File::UpdateFileOffsets() {
5978            DLS::File::UpdateFileOffsets();
5979    
5980            for (Instrument* instrument = GetFirstInstrument(); instrument;
5981                 instrument = GetNextInstrument())
5982            {
5983                instrument->UpdateScriptFileOffsets();
5984            }
5985        }
5986    
5987        /**
5988         * Enable / disable automatic loading. By default this properyt is
5989         * enabled and all informations are loaded automatically. However
5990         * loading all Regions, DimensionRegions and especially samples might
5991         * take a long time for large .gig files, and sometimes one might only
5992         * be interested in retrieving very superficial informations like the
5993         * amount of instruments and their names. In this case one might disable
5994         * automatic loading to avoid very slow response times.
5995         *
5996         * @e CAUTION: by disabling this property many pointers (i.e. sample
5997         * references) and informations will have invalid or even undefined
5998         * data! This feature is currently only intended for retrieving very
5999         * superficial informations in a very fast way. Don't use it to retrieve
6000         * details like synthesis informations or even to modify .gig files!
6001         */
6002        void File::SetAutoLoad(bool b) {
6003            bAutoLoad = b;
6004        }
6005    
6006        /**
6007         * Returns whether automatic loading is enabled.
6008         * @see SetAutoLoad()
6009         */
6010        bool File::GetAutoLoad() {
6011            return bAutoLoad;
6012        }
6013    
6014    
6015    

Legend:
Removed from v.1416  
changed lines
  Added in v.2640

  ViewVC Help
Powered by ViewVC