/[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 2482 by schoenebeck, Mon Nov 25 02:22:38 2013 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2013 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    
# Line 453  namespace { Line 454  namespace {
454      }      }
455    
456      /**      /**
457         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518            }
519            pOrig->SetPos(restorePos);
520            delete [] buf;
521        }
522    
523        /**
524       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
525       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
526       *       *
# Line 676  namespace { Line 744  namespace {
744          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
745          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
746          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
747            SetPos(0); // reset read position to begin of sample
748          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
749          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
750          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 713  namespace { Line 782  namespace {
782          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
783          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
784          RAMCache.Size   = 0;          RAMCache.Size   = 0;
785            RAMCache.NullExtensionSize = 0;
786      }      }
787    
788      /** @brief Resize sample.      /** @brief Resize sample.
# Line 805  namespace { Line 875  namespace {
875      /**      /**
876       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
877       */       */
878      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
879          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
880          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
881      }      }
# Line 907  namespace { Line 977  namespace {
977                                  }                                  }
978    
979                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
980                                  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!
981                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
982                              }                              }
983                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
984                          break;                          break;
# Line 1429  namespace { Line 1500  namespace {
1500                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1501              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1502              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1503                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1504              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1505              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1506              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1577  namespace { Line 1648  namespace {
1648       */       */
1649      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1650          Instances++;          Instances++;
1651            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1652          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1653          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1654    
# Line 1592  namespace { Line 1664  namespace {
1664                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1665          }          }
1666      }      }
1667        
1668        /**
1669         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1670         * and assign it to this object.
1671         *
1672         * Note that all sample pointers referenced by @a orig are simply copied as
1673         * memory address. Thus the respective samples are shared, not duplicated!
1674         *
1675         * @param orig - original DimensionRegion object to be copied from
1676         */
1677        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1678            CopyAssign(orig, NULL);
1679        }
1680    
1681        /**
1682         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1683         * and assign it to this object.
1684         *
1685         * @param orig - original DimensionRegion object to be copied from
1686         * @param mSamples - crosslink map between the foreign file's samples and
1687         *                   this file's samples
1688         */
1689        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1690            // delete all allocated data first
1691            if (VelocityTable) delete [] VelocityTable;
1692            if (pSampleLoops) delete [] pSampleLoops;
1693            
1694            // backup parent list pointer
1695            RIFF::List* p = pParentList;
1696            
1697            gig::Sample* pOriginalSample = pSample;
1698            gig::Region* pOriginalRegion = pRegion;
1699            
1700            //NOTE: copy code copied from assignment constructor above, see comment there as well
1701            
1702            *this = *orig; // default memberwise shallow copy of all parameters
1703            pParentList = p; // restore the chunk pointer
1704            
1705            // only take the raw sample reference & parent region reference if the
1706            // two DimensionRegion objects are part of the same file
1707            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1708                pRegion = pOriginalRegion;
1709                pSample = pOriginalSample;
1710            }
1711            
1712            if (mSamples && mSamples->count(orig->pSample)) {
1713                pSample = mSamples->find(orig->pSample)->second;
1714            }
1715    
1716            // deep copy of owned structures
1717            if (orig->VelocityTable) {
1718                VelocityTable = new uint8_t[128];
1719                for (int k = 0 ; k < 128 ; k++)
1720                    VelocityTable[k] = orig->VelocityTable[k];
1721            }
1722            if (orig->pSampleLoops) {
1723                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1724                for (int k = 0 ; k < orig->SampleLoops ; k++)
1725                    pSampleLoops[k] = orig->pSampleLoops[k];
1726            }
1727        }
1728    
1729      /**      /**
1730       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1833  namespace { Line 1966  namespace {
1966          }          }
1967    
1968          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1969                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1970          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1971    
1972          // next 2 bytes unknown          // next 2 bytes unknown
1973    
# Line 1881  namespace { Line 2014  namespace {
2014                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2015          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2016    
2017          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2018                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2019          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2020    
# Line 2372  namespace { Line 2505  namespace {
2505    
2506          // Actual Loading          // Actual Loading
2507    
2508            if (!file->GetAutoLoad()) return;
2509    
2510          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2511    
2512          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2415  namespace { Line 2550  namespace {
2550              else              else
2551                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2552    
2553              // load sample references              // load sample references (if auto loading is enabled)
2554              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2555                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2556                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2557                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2558                    }
2559                    GetSample(); // load global region sample reference
2560              }              }
             GetSample(); // load global region sample reference  
2561          } else {          } else {
2562              DimensionRegions = 0;              DimensionRegions = 0;
2563              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2917  namespace { Line 3054  namespace {
3054          }          }
3055          return NULL;          return NULL;
3056      }      }
3057        
3058        /**
3059         * Make a (semi) deep copy of the Region object given by @a orig
3060         * and assign it to this object.
3061         *
3062         * Note that all sample pointers referenced by @a orig are simply copied as
3063         * memory address. Thus the respective samples are shared, not duplicated!
3064         *
3065         * @param orig - original Region object to be copied from
3066         */
3067        void Region::CopyAssign(const Region* orig) {
3068            CopyAssign(orig, NULL);
3069        }
3070        
3071        /**
3072         * Make a (semi) deep copy of the Region object given by @a orig and
3073         * assign it to this object
3074         *
3075         * @param mSamples - crosslink map between the foreign file's samples and
3076         *                   this file's samples
3077         */
3078        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3079            // handle base classes
3080            DLS::Region::CopyAssign(orig);
3081            
3082            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3083                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3084            }
3085            
3086            // handle own member variables
3087            for (int i = Dimensions - 1; i >= 0; --i) {
3088                DeleteDimension(&pDimensionDefinitions[i]);
3089            }
3090            Layers = 0; // just to be sure
3091            for (int i = 0; i < orig->Dimensions; i++) {
3092                // we need to copy the dim definition here, to avoid the compiler
3093                // complaining about const-ness issue
3094                dimension_def_t def = orig->pDimensionDefinitions[i];
3095                AddDimension(&def);
3096            }
3097            for (int i = 0; i < 256; i++) {
3098                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3099                    pDimensionRegions[i]->CopyAssign(
3100                        orig->pDimensionRegions[i],
3101                        mSamples
3102                    );
3103                }
3104            }
3105            Layers = orig->Layers;
3106        }
3107    
3108    
3109    // *************** MidiRule ***************
3110    // *
3111    
3112        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3113            _3ewg->SetPos(36);
3114            Triggers = _3ewg->ReadUint8();
3115            _3ewg->SetPos(40);
3116            ControllerNumber = _3ewg->ReadUint8();
3117            _3ewg->SetPos(46);
3118            for (int i = 0 ; i < Triggers ; i++) {
3119                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3120                pTriggers[i].Descending = _3ewg->ReadUint8();
3121                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3122                pTriggers[i].Key = _3ewg->ReadUint8();
3123                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3124                pTriggers[i].Velocity = _3ewg->ReadUint8();
3125                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3126                _3ewg->ReadUint8();
3127            }
3128        }
3129    
3130        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3131            ControllerNumber(0),
3132            Triggers(0) {
3133        }
3134    
3135        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3136            pData[32] = 4;
3137            pData[33] = 16;
3138            pData[36] = Triggers;
3139            pData[40] = ControllerNumber;
3140            for (int i = 0 ; i < Triggers ; i++) {
3141                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3142                pData[47 + i * 8] = pTriggers[i].Descending;
3143                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3144                pData[49 + i * 8] = pTriggers[i].Key;
3145                pData[50 + i * 8] = pTriggers[i].NoteOff;
3146                pData[51 + i * 8] = pTriggers[i].Velocity;
3147                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3148            }
3149        }
3150    
3151        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3152            _3ewg->SetPos(36);
3153            LegatoSamples = _3ewg->ReadUint8(); // always 12
3154            _3ewg->SetPos(40);
3155            BypassUseController = _3ewg->ReadUint8();
3156            BypassKey = _3ewg->ReadUint8();
3157            BypassController = _3ewg->ReadUint8();
3158            ThresholdTime = _3ewg->ReadUint16();
3159            _3ewg->ReadInt16();
3160            ReleaseTime = _3ewg->ReadUint16();
3161            _3ewg->ReadInt16();
3162            KeyRange.low = _3ewg->ReadUint8();
3163            KeyRange.high = _3ewg->ReadUint8();
3164            _3ewg->SetPos(64);
3165            ReleaseTriggerKey = _3ewg->ReadUint8();
3166            AltSustain1Key = _3ewg->ReadUint8();
3167            AltSustain2Key = _3ewg->ReadUint8();
3168        }
3169    
3170        MidiRuleLegato::MidiRuleLegato() :
3171            LegatoSamples(12),
3172            BypassUseController(false),
3173            BypassKey(0),
3174            BypassController(1),
3175            ThresholdTime(20),
3176            ReleaseTime(20),
3177            ReleaseTriggerKey(0),
3178            AltSustain1Key(0),
3179            AltSustain2Key(0)
3180        {
3181            KeyRange.low = KeyRange.high = 0;
3182        }
3183    
3184        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3185            pData[32] = 0;
3186            pData[33] = 16;
3187            pData[36] = LegatoSamples;
3188            pData[40] = BypassUseController;
3189            pData[41] = BypassKey;
3190            pData[42] = BypassController;
3191            store16(&pData[43], ThresholdTime);
3192            store16(&pData[47], ReleaseTime);
3193            pData[51] = KeyRange.low;
3194            pData[52] = KeyRange.high;
3195            pData[64] = ReleaseTriggerKey;
3196            pData[65] = AltSustain1Key;
3197            pData[66] = AltSustain2Key;
3198        }
3199    
3200        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3201            _3ewg->SetPos(36);
3202            Articulations = _3ewg->ReadUint8();
3203            int flags = _3ewg->ReadUint8();
3204            Polyphonic = flags & 8;
3205            Chained = flags & 4;
3206            Selector = (flags & 2) ? selector_controller :
3207                (flags & 1) ? selector_key_switch : selector_none;
3208            Patterns = _3ewg->ReadUint8();
3209            _3ewg->ReadUint8(); // chosen row
3210            _3ewg->ReadUint8(); // unknown
3211            _3ewg->ReadUint8(); // unknown
3212            _3ewg->ReadUint8(); // unknown
3213            KeySwitchRange.low = _3ewg->ReadUint8();
3214            KeySwitchRange.high = _3ewg->ReadUint8();
3215            Controller = _3ewg->ReadUint8();
3216            PlayRange.low = _3ewg->ReadUint8();
3217            PlayRange.high = _3ewg->ReadUint8();
3218    
3219            int n = std::min(int(Articulations), 32);
3220            for (int i = 0 ; i < n ; i++) {
3221                _3ewg->ReadString(pArticulations[i], 32);
3222            }
3223            _3ewg->SetPos(1072);
3224            n = std::min(int(Patterns), 32);
3225            for (int i = 0 ; i < n ; i++) {
3226                _3ewg->ReadString(pPatterns[i].Name, 16);
3227                pPatterns[i].Size = _3ewg->ReadUint8();
3228                _3ewg->Read(&pPatterns[i][0], 1, 32);
3229            }
3230        }
3231    
3232        MidiRuleAlternator::MidiRuleAlternator() :
3233            Articulations(0),
3234            Patterns(0),
3235            Selector(selector_none),
3236            Controller(0),
3237            Polyphonic(false),
3238            Chained(false)
3239        {
3240            PlayRange.low = PlayRange.high = 0;
3241            KeySwitchRange.low = KeySwitchRange.high = 0;
3242        }
3243    
3244        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3245            pData[32] = 3;
3246            pData[33] = 16;
3247            pData[36] = Articulations;
3248            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3249                (Selector == selector_controller ? 2 :
3250                 (Selector == selector_key_switch ? 1 : 0));
3251            pData[38] = Patterns;
3252    
3253            pData[43] = KeySwitchRange.low;
3254            pData[44] = KeySwitchRange.high;
3255            pData[45] = Controller;
3256            pData[46] = PlayRange.low;
3257            pData[47] = PlayRange.high;
3258    
3259            char* str = reinterpret_cast<char*>(pData);
3260            int pos = 48;
3261            int n = std::min(int(Articulations), 32);
3262            for (int i = 0 ; i < n ; i++, pos += 32) {
3263                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3264            }
3265    
3266            pos = 1072;
3267            n = std::min(int(Patterns), 32);
3268            for (int i = 0 ; i < n ; i++, pos += 49) {
3269                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3270                pData[pos + 16] = pPatterns[i].Size;
3271                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3272            }
3273        }
3274    
3275  // *************** Instrument ***************  // *************** Instrument ***************
3276  // *  // *
# Line 2940  namespace { Line 3292  namespace {
3292          PianoReleaseMode = false;          PianoReleaseMode = false;
3293          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
3294          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
3295            pMidiRules = new MidiRule*[3];
3296            pMidiRules[0] = NULL;
3297    
3298          // Loading          // Loading
3299          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2954  namespace { Line 3308  namespace {
3308                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3309                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3310                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3311    
3312                    if (_3ewg->GetSize() > 32) {
3313                        // read MIDI rules
3314                        int i = 0;
3315                        _3ewg->SetPos(32);
3316                        uint8_t id1 = _3ewg->ReadUint8();
3317                        uint8_t id2 = _3ewg->ReadUint8();
3318    
3319                        if (id2 == 16) {
3320                            if (id1 == 4) {
3321                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3322                            } else if (id1 == 0) {
3323                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3324                            } else if (id1 == 3) {
3325                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3326                            } else {
3327                                pMidiRules[i++] = new MidiRuleUnknown;
3328                            }
3329                        }
3330                        else if (id1 != 0 || id2 != 0) {
3331                            pMidiRules[i++] = new MidiRuleUnknown;
3332                        }
3333                        //TODO: all the other types of rules
3334    
3335                        pMidiRules[i] = NULL;
3336                    }
3337              }              }
3338          }          }
3339    
3340          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3341          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3342          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3343              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3344              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3345                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3346                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3347                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3348                            pRegions->push_back(new Region(this, rgn));
3349                        }
3350                        rgn = lrgn->GetNextSubList();
3351                  }                  }
3352                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3353                    UpdateRegionKeyTable();
3354              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3355          }          }
3356    
3357          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
# Line 2988  namespace { Line 3370  namespace {
3370      }      }
3371    
3372      Instrument::~Instrument() {      Instrument::~Instrument() {
3373            for (int i = 0 ; pMidiRules[i] ; i++) {
3374                delete pMidiRules[i];
3375            }
3376            delete[] pMidiRules;
3377      }      }
3378    
3379      /**      /**
# Line 3034  namespace { Line 3420  namespace {
3420                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3421          pData[10] = dimkeystart;          pData[10] = dimkeystart;
3422          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
3423    
3424            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3425                pData[32] = 0;
3426                pData[33] = 0;
3427            } else {
3428                for (int i = 0 ; pMidiRules[i] ; i++) {
3429                    pMidiRules[i]->UpdateChunks(pData);
3430                }
3431            }
3432      }      }
3433    
3434      /**      /**
# Line 3102  namespace { Line 3497  namespace {
3497          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3498      }      }
3499    
3500        /**
3501         * Returns a MIDI rule of the instrument.
3502         *
3503         * The list of MIDI rules, at least in gig v3, always contains at
3504         * most two rules. The second rule can only be the DEF filter
3505         * (which currently isn't supported by libgig).
3506         *
3507         * @param i - MIDI rule number
3508         * @returns   pointer address to MIDI rule number i or NULL if there is none
3509         */
3510        MidiRule* Instrument::GetMidiRule(int i) {
3511            return pMidiRules[i];
3512        }
3513    
3514        /**
3515         * Adds the "controller trigger" MIDI rule to the instrument.
3516         *
3517         * @returns the new MIDI rule
3518         */
3519        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3520            delete pMidiRules[0];
3521            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3522            pMidiRules[0] = r;
3523            pMidiRules[1] = 0;
3524            return r;
3525        }
3526    
3527        /**
3528         * Adds the legato MIDI rule to the instrument.
3529         *
3530         * @returns the new MIDI rule
3531         */
3532        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3533            delete pMidiRules[0];
3534            MidiRuleLegato* r = new MidiRuleLegato;
3535            pMidiRules[0] = r;
3536            pMidiRules[1] = 0;
3537            return r;
3538        }
3539    
3540        /**
3541         * Adds the alternator MIDI rule to the instrument.
3542         *
3543         * @returns the new MIDI rule
3544         */
3545        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3546            delete pMidiRules[0];
3547            MidiRuleAlternator* r = new MidiRuleAlternator;
3548            pMidiRules[0] = r;
3549            pMidiRules[1] = 0;
3550            return r;
3551        }
3552    
3553        /**
3554         * Deletes a MIDI rule from the instrument.
3555         *
3556         * @param i - MIDI rule number
3557         */
3558        void Instrument::DeleteMidiRule(int i) {
3559            delete pMidiRules[i];
3560            pMidiRules[i] = 0;
3561        }
3562    
3563        /**
3564         * Make a (semi) deep copy of the Instrument object given by @a orig
3565         * and assign it to this object.
3566         *
3567         * Note that all sample pointers referenced by @a orig are simply copied as
3568         * memory address. Thus the respective samples are shared, not duplicated!
3569         *
3570         * @param orig - original Instrument object to be copied from
3571         */
3572        void Instrument::CopyAssign(const Instrument* orig) {
3573            CopyAssign(orig, NULL);
3574        }
3575            
3576        /**
3577         * Make a (semi) deep copy of the Instrument object given by @a orig
3578         * and assign it to this object.
3579         *
3580         * @param orig - original Instrument object to be copied from
3581         * @param mSamples - crosslink map between the foreign file's samples and
3582         *                   this file's samples
3583         */
3584        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3585            // handle base class
3586            // (without copying DLS region stuff)
3587            DLS::Instrument::CopyAssignCore(orig);
3588            
3589            // handle own member variables
3590            Attenuation = orig->Attenuation;
3591            EffectSend = orig->EffectSend;
3592            FineTune = orig->FineTune;
3593            PitchbendRange = orig->PitchbendRange;
3594            PianoReleaseMode = orig->PianoReleaseMode;
3595            DimensionKeyRange = orig->DimensionKeyRange;
3596            
3597            // free old midi rules
3598            for (int i = 0 ; pMidiRules[i] ; i++) {
3599                delete pMidiRules[i];
3600            }
3601            //TODO: MIDI rule copying
3602            pMidiRules[0] = NULL;
3603            
3604            // delete all old regions
3605            while (Regions) DeleteRegion(GetFirstRegion());
3606            // create new regions and copy them from original
3607            {
3608                RegionList::const_iterator it = orig->pRegions->begin();
3609                for (int i = 0; i < orig->Regions; ++i, ++it) {
3610                    Region* dstRgn = AddRegion();
3611                    //NOTE: Region does semi-deep copy !
3612                    dstRgn->CopyAssign(
3613                        static_cast<gig::Region*>(*it),
3614                        mSamples
3615                    );
3616                }
3617            }
3618    
3619            UpdateRegionKeyTable();
3620        }
3621    
3622    
3623  // *************** Group ***************  // *************** Group ***************
# Line 3259  namespace { Line 3775  namespace {
3775      };      };
3776    
3777      File::File() : DLS::File() {      File::File() : DLS::File() {
3778            bAutoLoad = true;
3779          *pVersion = VERSION_3;          *pVersion = VERSION_3;
3780          pGroups = NULL;          pGroups = NULL;
3781          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
# Line 3274  namespace { Line 3791  namespace {
3791      }      }
3792    
3793      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3794            bAutoLoad = true;
3795          pGroups = NULL;          pGroups = NULL;
3796          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3797      }      }
# Line 3302  namespace { Line 3820  namespace {
3820          SamplesIterator++;          SamplesIterator++;
3821          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3822      }      }
3823        
3824        /**
3825         * Returns Sample object of @a index.
3826         *
3827         * @returns sample object or NULL if index is out of bounds
3828         */
3829        Sample* File::GetSample(uint index) {
3830            if (!pSamples) LoadSamples();
3831            if (!pSamples) return NULL;
3832            DLS::File::SampleList::iterator it = pSamples->begin();
3833            for (int i = 0; i < index; ++i) {
3834                ++it;
3835                if (it == pSamples->end()) return NULL;
3836            }
3837            if (it == pSamples->end()) return NULL;
3838            return static_cast<gig::Sample*>( *it );
3839        }
3840    
3841      /** @brief Add a new sample.      /** @brief Add a new sample.
3842       *       *
# Line 3343  namespace { Line 3878  namespace {
3878          pSamples->erase(iter);          pSamples->erase(iter);
3879          delete pSample;          delete pSample;
3880    
3881            SampleList::iterator tmp = SamplesIterator;
3882          // remove all references to the sample          // remove all references to the sample
3883          for (Instrument* instrument = GetFirstInstrument() ; instrument ;          for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3884               instrument = GetNextInstrument()) {               instrument = GetNextInstrument()) {
# Line 3357  namespace { Line 3893  namespace {
3893                  }                  }
3894              }              }
3895          }          }
3896            SamplesIterator = tmp; // restore iterator
3897      }      }
3898    
3899      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3447  namespace { Line 3984  namespace {
3984              progress_t subprogress;              progress_t subprogress;
3985              __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
3986              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3987              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3988                    GetFirstSample(&subprogress); // now force all samples to be loaded
3989              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3990    
3991              // instrument loading subtask              // instrument loading subtask
# Line 3496  namespace { Line 4034  namespace {
4034         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4035         return pInstrument;         return pInstrument;
4036      }      }
4037        
4038        /** @brief Add a duplicate of an existing instrument.
4039         *
4040         * Duplicates the instrument definition given by @a orig and adds it
4041         * to this file. This allows in an instrument editor application to
4042         * easily create variations of an instrument, which will be stored in
4043         * the same .gig file, sharing i.e. the same samples.
4044         *
4045         * Note that all sample pointers referenced by @a orig are simply copied as
4046         * memory address. Thus the respective samples are shared, not duplicated!
4047         *
4048         * You have to call Save() to make this persistent to the file.
4049         *
4050         * @param orig - original instrument to be copied
4051         * @returns duplicated copy of the given instrument
4052         */
4053        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4054            Instrument* instr = AddInstrument();
4055            instr->CopyAssign(orig);
4056            return instr;
4057        }
4058        
4059        /** @brief Add content of another existing file.
4060         *
4061         * Duplicates the samples, groups and instruments of the original file
4062         * given by @a pFile and adds them to @c this File. In case @c this File is
4063         * a new one that you haven't saved before, then you have to call
4064         * SetFileName() before calling AddContentOf(), because this method will
4065         * automatically save this file during operation, which is required for
4066         * writing the sample waveform data by disk streaming.
4067         *
4068         * @param pFile - original file whose's content shall be copied from
4069         */
4070        void File::AddContentOf(File* pFile) {
4071            static int iCallCount = -1;
4072            iCallCount++;
4073            std::map<Group*,Group*> mGroups;
4074            std::map<Sample*,Sample*> mSamples;
4075            
4076            // clone sample groups
4077            for (int i = 0; pFile->GetGroup(i); ++i) {
4078                Group* g = AddGroup();
4079                g->Name =
4080                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4081                mGroups[pFile->GetGroup(i)] = g;
4082            }
4083            
4084            // clone samples (not waveform data here yet)
4085            for (int i = 0; pFile->GetSample(i); ++i) {
4086                Sample* s = AddSample();
4087                s->CopyAssignMeta(pFile->GetSample(i));
4088                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4089                mSamples[pFile->GetSample(i)] = s;
4090            }
4091            
4092            //BUG: For some reason this method only works with this additional
4093            //     Save() call in between here.
4094            //
4095            // Important: The correct one of the 2 Save() methods has to be called
4096            // here, depending on whether the file is completely new or has been
4097            // saved to disk already, otherwise it will result in data corruption.
4098            if (pRIFF->IsNew())
4099                Save(GetFileName());
4100            else
4101                Save();
4102            
4103            // clone instruments
4104            // (passing the crosslink table here for the cloned samples)
4105            for (int i = 0; pFile->GetInstrument(i); ++i) {
4106                Instrument* instr = AddInstrument();
4107                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4108            }
4109            
4110            // Mandatory: file needs to be saved to disk at this point, so this
4111            // file has the correct size and data layout for writing the samples'
4112            // waveform data to disk.
4113            Save();
4114            
4115            // clone samples' waveform data
4116            // (using direct read & write disk streaming)
4117            for (int i = 0; pFile->GetSample(i); ++i) {
4118                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4119            }
4120        }
4121    
4122      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4123       *       *
# Line 3708  namespace { Line 4330  namespace {
4330    
4331          // update group's chunks          // update group's chunks
4332          if (pGroups) {          if (pGroups) {
4333              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
4334              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
4335              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4336                  (*iter)->UpdateChunks();              if (!_3gri) {
4337                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4338                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4339              }              }
4340                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4341                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4342    
4343              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
4344                // (before updating the Group chunks)
4345              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
4346                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4347                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
4348                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4349                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4350                  }                  }
4351              }              }
4352    
4353                std::list<Group*>::iterator iter = pGroups->begin();
4354                std::list<Group*>::iterator end  = pGroups->end();
4355                for (; iter != end; ++iter) {
4356                    (*iter)->UpdateChunks();
4357                }
4358          }          }
4359    
4360          // update einf chunk          // update einf chunk
# Line 3854  namespace { Line 4486  namespace {
4486          }          }
4487      }      }
4488    
4489        /**
4490         * Enable / disable automatic loading. By default this properyt is
4491         * enabled and all informations are loaded automatically. However
4492         * loading all Regions, DimensionRegions and especially samples might
4493         * take a long time for large .gig files, and sometimes one might only
4494         * be interested in retrieving very superficial informations like the
4495         * amount of instruments and their names. In this case one might disable
4496         * automatic loading to avoid very slow response times.
4497         *
4498         * @e CAUTION: by disabling this property many pointers (i.e. sample
4499         * references) and informations will have invalid or even undefined
4500         * data! This feature is currently only intended for retrieving very
4501         * superficial informations in a very fast way. Don't use it to retrieve
4502         * details like synthesis informations or even to modify .gig files!
4503         */
4504        void File::SetAutoLoad(bool b) {
4505            bAutoLoad = b;
4506        }
4507    
4508        /**
4509         * Returns whether automatic loading is enabled.
4510         * @see SetAutoLoad()
4511         */
4512        bool File::GetAutoLoad() {
4513            return bAutoLoad;
4514        }
4515    
4516    
4517    
4518  // *************** Exception ***************  // *************** Exception ***************

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

  ViewVC Help
Powered by ViewVC