/[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 1627 by persson, Sun Jan 6 10:53:53 2008 UTC revision 2484 by schoenebeck, Tue Dec 31 00:13:20 2013 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2013 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    
# Line 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 513  namespace { Line 581  namespace {
581          // update '3gix' chunk          // update '3gix' chunk
582          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
583          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
584    
585            // if the library user toggled the "Compressed" attribute from true to
586            // false, then the EWAV chunk associated with compressed samples needs
587            // to be deleted
588            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
589            if (ewav && !Compressed) {
590                pWaveList->DeleteSubChunk(ewav);
591            }
592      }      }
593    
594      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 676  namespace { Line 752  namespace {
752          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
753          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
754          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
755            SetPos(0); // reset read position to begin of sample
756          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
757          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
758          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 713  namespace { Line 790  namespace {
790          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
791          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
792          RAMCache.Size   = 0;          RAMCache.Size   = 0;
793            RAMCache.NullExtensionSize = 0;
794      }      }
795    
796      /** @brief Resize sample.      /** @brief Resize sample.
# Line 805  namespace { Line 883  namespace {
883      /**      /**
884       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
885       */       */
886      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
887          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
888          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
889      }      }
# Line 907  namespace { Line 985  namespace {
985                                  }                                  }
986    
987                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
988                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
989                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
990                              }                              }
991                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
992                          break;                          break;
# Line 1429  namespace { Line 1508  namespace {
1508                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1509              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1510              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1511                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1512              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1513              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1514              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1577  namespace { Line 1656  namespace {
1656       */       */
1657      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1658          Instances++;          Instances++;
1659            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1660          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1661          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1662    
# Line 1592  namespace { Line 1672  namespace {
1672                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1673          }          }
1674      }      }
1675        
1676        /**
1677         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1678         * and assign it to this object.
1679         *
1680         * Note that all sample pointers referenced by @a orig are simply copied as
1681         * memory address. Thus the respective samples are shared, not duplicated!
1682         *
1683         * @param orig - original DimensionRegion object to be copied from
1684         */
1685        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1686            CopyAssign(orig, NULL);
1687        }
1688    
1689        /**
1690         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1691         * and assign it to this object.
1692         *
1693         * @param orig - original DimensionRegion object to be copied from
1694         * @param mSamples - crosslink map between the foreign file's samples and
1695         *                   this file's samples
1696         */
1697        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1698            // delete all allocated data first
1699            if (VelocityTable) delete [] VelocityTable;
1700            if (pSampleLoops) delete [] pSampleLoops;
1701            
1702            // backup parent list pointer
1703            RIFF::List* p = pParentList;
1704            
1705            gig::Sample* pOriginalSample = pSample;
1706            gig::Region* pOriginalRegion = pRegion;
1707            
1708            //NOTE: copy code copied from assignment constructor above, see comment there as well
1709            
1710            *this = *orig; // default memberwise shallow copy of all parameters
1711            pParentList = p; // restore the chunk pointer
1712            
1713            // only take the raw sample reference & parent region reference if the
1714            // two DimensionRegion objects are part of the same file
1715            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1716                pRegion = pOriginalRegion;
1717                pSample = pOriginalSample;
1718            }
1719            
1720            if (mSamples && mSamples->count(orig->pSample)) {
1721                pSample = mSamples->find(orig->pSample)->second;
1722            }
1723    
1724            // deep copy of owned structures
1725            if (orig->VelocityTable) {
1726                VelocityTable = new uint8_t[128];
1727                for (int k = 0 ; k < 128 ; k++)
1728                    VelocityTable[k] = orig->VelocityTable[k];
1729            }
1730            if (orig->pSampleLoops) {
1731                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1732                for (int k = 0 ; k < orig->SampleLoops ; k++)
1733                    pSampleLoops[k] = orig->pSampleLoops[k];
1734            }
1735        }
1736    
1737      /**      /**
1738       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1833  namespace { Line 1974  namespace {
1974          }          }
1975    
1976          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1977                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1978          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1979    
1980          // next 2 bytes unknown          // next 2 bytes unknown
1981    
# Line 1881  namespace { Line 2022  namespace {
2022                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2023          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2024    
2025          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2026                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2027          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2028    
# Line 2921  namespace { Line 3062  namespace {
3062          }          }
3063          return NULL;          return NULL;
3064      }      }
3065        
3066        /**
3067         * Make a (semi) deep copy of the Region object given by @a orig
3068         * and assign it to this object.
3069         *
3070         * Note that all sample pointers referenced by @a orig are simply copied as
3071         * memory address. Thus the respective samples are shared, not duplicated!
3072         *
3073         * @param orig - original Region object to be copied from
3074         */
3075        void Region::CopyAssign(const Region* orig) {
3076            CopyAssign(orig, NULL);
3077        }
3078        
3079        /**
3080         * Make a (semi) deep copy of the Region object given by @a orig and
3081         * assign it to this object
3082         *
3083         * @param mSamples - crosslink map between the foreign file's samples and
3084         *                   this file's samples
3085         */
3086        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3087            // handle base classes
3088            DLS::Region::CopyAssign(orig);
3089            
3090            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3091                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3092            }
3093            
3094            // handle own member variables
3095            for (int i = Dimensions - 1; i >= 0; --i) {
3096                DeleteDimension(&pDimensionDefinitions[i]);
3097            }
3098            Layers = 0; // just to be sure
3099            for (int i = 0; i < orig->Dimensions; i++) {
3100                // we need to copy the dim definition here, to avoid the compiler
3101                // complaining about const-ness issue
3102                dimension_def_t def = orig->pDimensionDefinitions[i];
3103                AddDimension(&def);
3104            }
3105            for (int i = 0; i < 256; i++) {
3106                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3107                    pDimensionRegions[i]->CopyAssign(
3108                        orig->pDimensionRegions[i],
3109                        mSamples
3110                    );
3111                }
3112            }
3113            Layers = orig->Layers;
3114        }
3115    
3116    
3117  // *************** MidiRule ***************  // *************** MidiRule ***************
3118  // *  // *
3119    
3120  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {      MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3121      _3ewg->SetPos(36);          _3ewg->SetPos(36);
3122      Triggers = _3ewg->ReadUint8();          Triggers = _3ewg->ReadUint8();
3123      _3ewg->SetPos(40);          _3ewg->SetPos(40);
3124      ControllerNumber = _3ewg->ReadUint8();          ControllerNumber = _3ewg->ReadUint8();
3125      _3ewg->SetPos(46);          _3ewg->SetPos(46);
3126      for (int i = 0 ; i < Triggers ; i++) {          for (int i = 0 ; i < Triggers ; i++) {
3127          pTriggers[i].TriggerPoint = _3ewg->ReadUint8();              pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3128          pTriggers[i].Descending = _3ewg->ReadUint8();              pTriggers[i].Descending = _3ewg->ReadUint8();
3129          pTriggers[i].VelSensitivity = _3ewg->ReadUint8();              pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3130          pTriggers[i].Key = _3ewg->ReadUint8();              pTriggers[i].Key = _3ewg->ReadUint8();
3131          pTriggers[i].NoteOff = _3ewg->ReadUint8();              pTriggers[i].NoteOff = _3ewg->ReadUint8();
3132          pTriggers[i].Velocity = _3ewg->ReadUint8();              pTriggers[i].Velocity = _3ewg->ReadUint8();
3133          pTriggers[i].OverridePedal = _3ewg->ReadUint8();              pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3134          _3ewg->ReadUint8();              _3ewg->ReadUint8();
3135            }
3136        }
3137    
3138        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3139            ControllerNumber(0),
3140            Triggers(0) {
3141        }
3142    
3143        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3144            pData[32] = 4;
3145            pData[33] = 16;
3146            pData[36] = Triggers;
3147            pData[40] = ControllerNumber;
3148            for (int i = 0 ; i < Triggers ; i++) {
3149                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3150                pData[47 + i * 8] = pTriggers[i].Descending;
3151                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3152                pData[49 + i * 8] = pTriggers[i].Key;
3153                pData[50 + i * 8] = pTriggers[i].NoteOff;
3154                pData[51 + i * 8] = pTriggers[i].Velocity;
3155                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3156            }
3157        }
3158    
3159        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3160            _3ewg->SetPos(36);
3161            LegatoSamples = _3ewg->ReadUint8(); // always 12
3162            _3ewg->SetPos(40);
3163            BypassUseController = _3ewg->ReadUint8();
3164            BypassKey = _3ewg->ReadUint8();
3165            BypassController = _3ewg->ReadUint8();
3166            ThresholdTime = _3ewg->ReadUint16();
3167            _3ewg->ReadInt16();
3168            ReleaseTime = _3ewg->ReadUint16();
3169            _3ewg->ReadInt16();
3170            KeyRange.low = _3ewg->ReadUint8();
3171            KeyRange.high = _3ewg->ReadUint8();
3172            _3ewg->SetPos(64);
3173            ReleaseTriggerKey = _3ewg->ReadUint8();
3174            AltSustain1Key = _3ewg->ReadUint8();
3175            AltSustain2Key = _3ewg->ReadUint8();
3176        }
3177    
3178        MidiRuleLegato::MidiRuleLegato() :
3179            LegatoSamples(12),
3180            BypassUseController(false),
3181            BypassKey(0),
3182            BypassController(1),
3183            ThresholdTime(20),
3184            ReleaseTime(20),
3185            ReleaseTriggerKey(0),
3186            AltSustain1Key(0),
3187            AltSustain2Key(0)
3188        {
3189            KeyRange.low = KeyRange.high = 0;
3190      }      }
 }  
3191    
3192        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3193            pData[32] = 0;
3194            pData[33] = 16;
3195            pData[36] = LegatoSamples;
3196            pData[40] = BypassUseController;
3197            pData[41] = BypassKey;
3198            pData[42] = BypassController;
3199            store16(&pData[43], ThresholdTime);
3200            store16(&pData[47], ReleaseTime);
3201            pData[51] = KeyRange.low;
3202            pData[52] = KeyRange.high;
3203            pData[64] = ReleaseTriggerKey;
3204            pData[65] = AltSustain1Key;
3205            pData[66] = AltSustain2Key;
3206        }
3207    
3208        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3209            _3ewg->SetPos(36);
3210            Articulations = _3ewg->ReadUint8();
3211            int flags = _3ewg->ReadUint8();
3212            Polyphonic = flags & 8;
3213            Chained = flags & 4;
3214            Selector = (flags & 2) ? selector_controller :
3215                (flags & 1) ? selector_key_switch : selector_none;
3216            Patterns = _3ewg->ReadUint8();
3217            _3ewg->ReadUint8(); // chosen row
3218            _3ewg->ReadUint8(); // unknown
3219            _3ewg->ReadUint8(); // unknown
3220            _3ewg->ReadUint8(); // unknown
3221            KeySwitchRange.low = _3ewg->ReadUint8();
3222            KeySwitchRange.high = _3ewg->ReadUint8();
3223            Controller = _3ewg->ReadUint8();
3224            PlayRange.low = _3ewg->ReadUint8();
3225            PlayRange.high = _3ewg->ReadUint8();
3226    
3227            int n = std::min(int(Articulations), 32);
3228            for (int i = 0 ; i < n ; i++) {
3229                _3ewg->ReadString(pArticulations[i], 32);
3230            }
3231            _3ewg->SetPos(1072);
3232            n = std::min(int(Patterns), 32);
3233            for (int i = 0 ; i < n ; i++) {
3234                _3ewg->ReadString(pPatterns[i].Name, 16);
3235                pPatterns[i].Size = _3ewg->ReadUint8();
3236                _3ewg->Read(&pPatterns[i][0], 1, 32);
3237            }
3238        }
3239    
3240        MidiRuleAlternator::MidiRuleAlternator() :
3241            Articulations(0),
3242            Patterns(0),
3243            Selector(selector_none),
3244            Controller(0),
3245            Polyphonic(false),
3246            Chained(false)
3247        {
3248            PlayRange.low = PlayRange.high = 0;
3249            KeySwitchRange.low = KeySwitchRange.high = 0;
3250        }
3251    
3252        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3253            pData[32] = 3;
3254            pData[33] = 16;
3255            pData[36] = Articulations;
3256            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3257                (Selector == selector_controller ? 2 :
3258                 (Selector == selector_key_switch ? 1 : 0));
3259            pData[38] = Patterns;
3260    
3261            pData[43] = KeySwitchRange.low;
3262            pData[44] = KeySwitchRange.high;
3263            pData[45] = Controller;
3264            pData[46] = PlayRange.low;
3265            pData[47] = PlayRange.high;
3266    
3267            char* str = reinterpret_cast<char*>(pData);
3268            int pos = 48;
3269            int n = std::min(int(Articulations), 32);
3270            for (int i = 0 ; i < n ; i++, pos += 32) {
3271                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3272            }
3273    
3274            pos = 1072;
3275            n = std::min(int(Patterns), 32);
3276            for (int i = 0 ; i < n ; i++, pos += 49) {
3277                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3278                pData[pos + 16] = pPatterns[i].Size;
3279                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3280            }
3281        }
3282    
3283  // *************** Instrument ***************  // *************** Instrument ***************
3284  // *  // *
# Line 2965  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3300  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3300          PianoReleaseMode = false;          PianoReleaseMode = false;
3301          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
3302          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
3303            pMidiRules = new MidiRule*[3];
3304            pMidiRules[0] = NULL;
3305    
3306          // Loading          // Loading
3307          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2982  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3319  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3319    
3320                  if (_3ewg->GetSize() > 32) {                  if (_3ewg->GetSize() > 32) {
3321                      // read MIDI rules                      // read MIDI rules
3322                        int i = 0;
3323                      _3ewg->SetPos(32);                      _3ewg->SetPos(32);
3324                      uint8_t id1 = _3ewg->ReadUint8();                      uint8_t id1 = _3ewg->ReadUint8();
3325                      uint8_t id2 = _3ewg->ReadUint8();                      uint8_t id2 = _3ewg->ReadUint8();
3326    
3327                      if (id1 == 4 && id2 == 16) {                      if (id2 == 16) {
3328                          MidiRules.push_back(new MidiRuleCtrlTrigger(_3ewg));                          if (id1 == 4) {
3329                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3330                            } else if (id1 == 0) {
3331                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3332                            } else if (id1 == 3) {
3333                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3334                            } else {
3335                                pMidiRules[i++] = new MidiRuleUnknown;
3336                            }
3337                        }
3338                        else if (id1 != 0 || id2 != 0) {
3339                            pMidiRules[i++] = new MidiRuleUnknown;
3340                      }                      }
3341                      //TODO: all the other types of rules                      //TODO: all the other types of rules
3342    
3343                        pMidiRules[i] = NULL;
3344                  }                  }
3345              }              }
3346          }          }
# Line 3027  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3378  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3378      }      }
3379    
3380      Instrument::~Instrument() {      Instrument::~Instrument() {
3381            for (int i = 0 ; pMidiRules[i] ; i++) {
3382                delete pMidiRules[i];
3383            }
3384            delete[] pMidiRules;
3385      }      }
3386    
3387      /**      /**
# Line 3073  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3428  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3428                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3429          pData[10] = dimkeystart;          pData[10] = dimkeystart;
3430          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
3431    
3432            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3433                pData[32] = 0;
3434                pData[33] = 0;
3435            } else {
3436                for (int i = 0 ; pMidiRules[i] ; i++) {
3437                    pMidiRules[i]->UpdateChunks(pData);
3438                }
3439            }
3440      }      }
3441    
3442      /**      /**
# Line 3142  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3506  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3506      }      }
3507    
3508      /**      /**
3509       * Returns the first MIDI rule of the instrument. You have to call       * Returns a MIDI rule of the instrument.
      * this method once before you use GetNextMidiRule().  
3510       *       *
3511       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
3512       * most two rules. The second rule can only be the DEF filter       * most two rules. The second rule can only be the DEF filter
3513       * (which currently isn't supported by libgig).       * (which currently isn't supported by libgig).
3514       *       *
3515       * @returns  pointer address to first MIDI rule or NULL if there is none       * @param i - MIDI rule number
3516       * @see      GetNextMidiRule()       * @returns   pointer address to MIDI rule number i or NULL if there is none
3517         */
3518        MidiRule* Instrument::GetMidiRule(int i) {
3519            return pMidiRules[i];
3520        }
3521    
3522        /**
3523         * Adds the "controller trigger" MIDI rule to the instrument.
3524         *
3525         * @returns the new MIDI rule
3526         */
3527        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3528            delete pMidiRules[0];
3529            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3530            pMidiRules[0] = r;
3531            pMidiRules[1] = 0;
3532            return r;
3533        }
3534    
3535        /**
3536         * Adds the legato MIDI rule to the instrument.
3537         *
3538         * @returns the new MIDI rule
3539       */       */
3540      MidiRule* Instrument::GetFirstMidiRule() {      MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3541          MidiRulesIterator = MidiRules.begin();          delete pMidiRules[0];
3542          return MidiRulesIterator != MidiRules.end() ? *MidiRulesIterator : NULL;          MidiRuleLegato* r = new MidiRuleLegato;
3543            pMidiRules[0] = r;
3544            pMidiRules[1] = 0;
3545            return r;
3546      }      }
3547    
3548      /**      /**
3549       * Returns the next MIDI rule of the instrument. You have to call       * Adds the alternator MIDI rule to the instrument.
      * GetFirstMidiRule() once before you can use this method. By  
      * calling this method multiple times it iterates through the  
      * available rules.  
3550       *       *
3551       * @returns  pointer address to the next MIDI rule or NULL if end reached       * @returns the new MIDI rule
      * @see      GetFirstMidiRule()  
3552       */       */
3553      MidiRule* Instrument::GetNextMidiRule() {      MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3554          MidiRulesIterator++;          delete pMidiRules[0];
3555          return MidiRulesIterator != MidiRules.end() ? *MidiRulesIterator : NULL;          MidiRuleAlternator* r = new MidiRuleAlternator;
3556            pMidiRules[0] = r;
3557            pMidiRules[1] = 0;
3558            return r;
3559        }
3560    
3561        /**
3562         * Deletes a MIDI rule from the instrument.
3563         *
3564         * @param i - MIDI rule number
3565         */
3566        void Instrument::DeleteMidiRule(int i) {
3567            delete pMidiRules[i];
3568            pMidiRules[i] = 0;
3569        }
3570    
3571        /**
3572         * Make a (semi) deep copy of the Instrument object given by @a orig
3573         * and assign it to this object.
3574         *
3575         * Note that all sample pointers referenced by @a orig are simply copied as
3576         * memory address. Thus the respective samples are shared, not duplicated!
3577         *
3578         * @param orig - original Instrument object to be copied from
3579         */
3580        void Instrument::CopyAssign(const Instrument* orig) {
3581            CopyAssign(orig, NULL);
3582        }
3583            
3584        /**
3585         * Make a (semi) deep copy of the Instrument object given by @a orig
3586         * and assign it to this object.
3587         *
3588         * @param orig - original Instrument object to be copied from
3589         * @param mSamples - crosslink map between the foreign file's samples and
3590         *                   this file's samples
3591         */
3592        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3593            // handle base class
3594            // (without copying DLS region stuff)
3595            DLS::Instrument::CopyAssignCore(orig);
3596            
3597            // handle own member variables
3598            Attenuation = orig->Attenuation;
3599            EffectSend = orig->EffectSend;
3600            FineTune = orig->FineTune;
3601            PitchbendRange = orig->PitchbendRange;
3602            PianoReleaseMode = orig->PianoReleaseMode;
3603            DimensionKeyRange = orig->DimensionKeyRange;
3604            
3605            // free old midi rules
3606            for (int i = 0 ; pMidiRules[i] ; i++) {
3607                delete pMidiRules[i];
3608            }
3609            //TODO: MIDI rule copying
3610            pMidiRules[0] = NULL;
3611            
3612            // delete all old regions
3613            while (Regions) DeleteRegion(GetFirstRegion());
3614            // create new regions and copy them from original
3615            {
3616                RegionList::const_iterator it = orig->pRegions->begin();
3617                for (int i = 0; i < orig->Regions; ++i, ++it) {
3618                    Region* dstRgn = AddRegion();
3619                    //NOTE: Region does semi-deep copy !
3620                    dstRgn->CopyAssign(
3621                        static_cast<gig::Region*>(*it),
3622                        mSamples
3623                    );
3624                }
3625            }
3626    
3627            UpdateRegionKeyTable();
3628      }      }
3629    
3630    
# Line 3372  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3828  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3828          SamplesIterator++;          SamplesIterator++;
3829          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3830      }      }
3831        
3832        /**
3833         * Returns Sample object of @a index.
3834         *
3835         * @returns sample object or NULL if index is out of bounds
3836         */
3837        Sample* File::GetSample(uint index) {
3838            if (!pSamples) LoadSamples();
3839            if (!pSamples) return NULL;
3840            DLS::File::SampleList::iterator it = pSamples->begin();
3841            for (int i = 0; i < index; ++i) {
3842                ++it;
3843                if (it == pSamples->end()) return NULL;
3844            }
3845            if (it == pSamples->end()) return NULL;
3846            return static_cast<gig::Sample*>( *it );
3847        }
3848    
3849      /** @brief Add a new sample.      /** @brief Add a new sample.
3850       *       *
# Line 3413  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3886  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3886          pSamples->erase(iter);          pSamples->erase(iter);
3887          delete pSample;          delete pSample;
3888    
3889            SampleList::iterator tmp = SamplesIterator;
3890          // remove all references to the sample          // remove all references to the sample
3891          for (Instrument* instrument = GetFirstInstrument() ; instrument ;          for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3892               instrument = GetNextInstrument()) {               instrument = GetNextInstrument()) {
# Line 3427  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 3901  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
3901                  }                  }
3902              }              }
3903          }          }
3904            SamplesIterator = tmp; // restore iterator
3905      }      }
3906    
3907      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3567  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4042  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4042         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4043         return pInstrument;         return pInstrument;
4044      }      }
4045        
4046        /** @brief Add a duplicate of an existing instrument.
4047         *
4048         * Duplicates the instrument definition given by @a orig and adds it
4049         * to this file. This allows in an instrument editor application to
4050         * easily create variations of an instrument, which will be stored in
4051         * the same .gig file, sharing i.e. the same samples.
4052         *
4053         * Note that all sample pointers referenced by @a orig are simply copied as
4054         * memory address. Thus the respective samples are shared, not duplicated!
4055         *
4056         * You have to call Save() to make this persistent to the file.
4057         *
4058         * @param orig - original instrument to be copied
4059         * @returns duplicated copy of the given instrument
4060         */
4061        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4062            Instrument* instr = AddInstrument();
4063            instr->CopyAssign(orig);
4064            return instr;
4065        }
4066        
4067        /** @brief Add content of another existing file.
4068         *
4069         * Duplicates the samples, groups and instruments of the original file
4070         * given by @a pFile and adds them to @c this File. In case @c this File is
4071         * a new one that you haven't saved before, then you have to call
4072         * SetFileName() before calling AddContentOf(), because this method will
4073         * automatically save this file during operation, which is required for
4074         * writing the sample waveform data by disk streaming.
4075         *
4076         * @param pFile - original file whose's content shall be copied from
4077         */
4078        void File::AddContentOf(File* pFile) {
4079            static int iCallCount = -1;
4080            iCallCount++;
4081            std::map<Group*,Group*> mGroups;
4082            std::map<Sample*,Sample*> mSamples;
4083            
4084            // clone sample groups
4085            for (int i = 0; pFile->GetGroup(i); ++i) {
4086                Group* g = AddGroup();
4087                g->Name =
4088                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4089                mGroups[pFile->GetGroup(i)] = g;
4090            }
4091            
4092            // clone samples (not waveform data here yet)
4093            for (int i = 0; pFile->GetSample(i); ++i) {
4094                Sample* s = AddSample();
4095                s->CopyAssignMeta(pFile->GetSample(i));
4096                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4097                mSamples[pFile->GetSample(i)] = s;
4098            }
4099            
4100            //BUG: For some reason this method only works with this additional
4101            //     Save() call in between here.
4102            //
4103            // Important: The correct one of the 2 Save() methods has to be called
4104            // here, depending on whether the file is completely new or has been
4105            // saved to disk already, otherwise it will result in data corruption.
4106            if (pRIFF->IsNew())
4107                Save(GetFileName());
4108            else
4109                Save();
4110            
4111            // clone instruments
4112            // (passing the crosslink table here for the cloned samples)
4113            for (int i = 0; pFile->GetInstrument(i); ++i) {
4114                Instrument* instr = AddInstrument();
4115                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4116            }
4117            
4118            // Mandatory: file needs to be saved to disk at this point, so this
4119            // file has the correct size and data layout for writing the samples'
4120            // waveform data to disk.
4121            Save();
4122            
4123            // clone samples' waveform data
4124            // (using direct read & write disk streaming)
4125            for (int i = 0; pFile->GetSample(i); ++i) {
4126                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4127            }
4128        }
4129    
4130      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4131       *       *
# Line 3779  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4338  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4338    
4339          // update group's chunks          // update group's chunks
4340          if (pGroups) {          if (pGroups) {
4341              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
4342              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
4343              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4344                  (*iter)->UpdateChunks();              if (!_3gri) {
4345                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4346                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4347              }              }
4348                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4349                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4350    
4351              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
4352                // (before updating the Group chunks)
4353              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
4354                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4355                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
4356                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4357                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4358                  }                  }
4359              }              }
4360    
4361                std::list<Group*>::iterator iter = pGroups->begin();
4362                std::list<Group*>::iterator end  = pGroups->end();
4363                for (; iter != end; ++iter) {
4364                    (*iter)->UpdateChunks();
4365                }
4366          }          }
4367    
4368          // update einf chunk          // update einf chunk

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

  ViewVC Help
Powered by ViewVC