/[svn]/linuxsampler/trunk/src/engines/gig/Voice.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/gig/Voice.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 245 by schoenebeck, Sat Sep 18 14:12:36 2004 UTC revision 2012 by iliev, Fri Oct 23 17:53:17 2009 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 - 2009 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 20  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24  #include "EGADSR.h"  #include "../../common/Features.h"
25  #include "Manipulator.h"  #include "Synthesizer.h"
26    #include "Profiler.h"
27    #include "Engine.h"
28    #include "EngineChannel.h"
29    
30  #include "Voice.h"  #include "Voice.h"
31    
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
     const float Voice::FILTER_CUTOFF_COEFF(CalculateFilterCutoffCoeff());  
   
     const int Voice::FILTER_UPDATE_MASK(CalculateFilterUpdateMask());  
   
     float Voice::CalculateFilterCutoffCoeff() {  
         return log(FILTER_CUTOFF_MIN / FILTER_CUTOFF_MAX);  
     }  
   
     int Voice::CalculateFilterUpdateMask() {  
         if (FILTER_UPDATE_PERIOD <= 0) return 0;  
         int power_of_two;  
         for (power_of_two = 0; 1<<power_of_two < FILTER_UPDATE_PERIOD; power_of_two++);  
         return (1 << power_of_two) - 1;  
     }  
   
34      Voice::Voice() {      Voice::Voice() {
35          pEngine     = NULL;          pEngine     = NULL;
36          pDiskThread = NULL;          pDiskThread = NULL;
37          Active = false;          PlaybackState = playback_state_end;
38          pEG1   = NULL;          pLFO1 = new LFOUnsigned(1.0f);  // amplitude EG (0..1 range)
39          pEG2   = NULL;          pLFO2 = new LFOUnsigned(1.0f);  // filter EG (0..1 range)
40          pEG3   = NULL;          pLFO3 = new LFOSigned(1200.0f); // pitch EG (-1200..+1200 range)
         pVCAManipulator  = NULL;  
         pVCFCManipulator = NULL;  
         pVCOManipulator  = NULL;  
         pLFO1  = NULL;  
         pLFO2  = NULL;  
         pLFO3  = NULL;  
41          KeyGroup = 0;          KeyGroup = 0;
42            SynthesisMode = 0; // set all mode bits to 0 first
43            // select synthesis implementation (asm core is not supported ATM)
44            #if 0 // CONFIG_ASM && ARCH_X86
45            SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
46            #else
47            SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);
48            #endif
49            SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, Profiler::isEnabled());
50    
51            finalSynthesisParameters.filterLeft.Reset();
52            finalSynthesisParameters.filterRight.Reset();
53      }      }
54    
55      Voice::~Voice() {      Voice::~Voice() {
         if (pEG1)  delete pEG1;  
         if (pEG2)  delete pEG2;  
         if (pEG3)  delete pEG3;  
56          if (pLFO1) delete pLFO1;          if (pLFO1) delete pLFO1;
57          if (pLFO2) delete pLFO2;          if (pLFO2) delete pLFO2;
58          if (pLFO3) delete pLFO3;          if (pLFO3) delete pLFO3;
         if (pVCAManipulator)  delete pVCAManipulator;  
         if (pVCFCManipulator) delete pVCFCManipulator;  
         if (pVCOManipulator)  delete pVCOManipulator;  
59      }      }
60    
61      void Voice::SetEngine(Engine* pEngine) {      void Voice::SetEngine(LinuxSampler::Engine* pEngine) {
62          this->pEngine = pEngine;          Engine* engine = static_cast<Engine*>(pEngine);
63            this->pEngine     = engine;
64          // delete old objects          this->pDiskThread = engine->pDiskThread;
         if (pEG1) delete pEG1;  
         if (pEG2) delete pEG2;  
         if (pEG3) delete pEG3;  
         if (pVCAManipulator)  delete pVCAManipulator;  
         if (pVCFCManipulator) delete pVCFCManipulator;  
         if (pVCOManipulator)  delete pVCOManipulator;  
         if (pLFO1) delete pLFO1;  
         if (pLFO2) delete pLFO2;  
         if (pLFO3) delete pLFO3;  
   
         // create new ones  
         pEG1   = new EGADSR(pEngine, Event::destination_vca);  
         pEG2   = new EGADSR(pEngine, Event::destination_vcfc);  
         pEG3   = new EGDecay(pEngine, Event::destination_vco);  
         pVCAManipulator  = new VCAManipulator(pEngine);  
         pVCFCManipulator = new VCFCManipulator(pEngine);  
         pVCOManipulator  = new VCOManipulator(pEngine);  
         pLFO1  = new LFO<gig::VCAManipulator>(0.0f, 1.0f, LFO<VCAManipulator>::propagation_top_down, pVCAManipulator, pEngine->pEventPool);  
         pLFO2  = new LFO<gig::VCFCManipulator>(0.0f, 1.0f, LFO<VCFCManipulator>::propagation_top_down, pVCFCManipulator, pEngine->pEventPool);  
         pLFO3  = new LFO<gig::VCOManipulator>(-1200.0f, 1200.0f, LFO<VCOManipulator>::propagation_middle_balanced, pVCOManipulator, pEngine->pEventPool); // +-1 octave (+-1200 cents) max.  
   
         this->pDiskThread = pEngine->pDiskThread;  
65          dmsg(6,("Voice::SetEngine()\n"));          dmsg(6,("Voice::SetEngine()\n"));
66      }      }
67    
# Line 103  namespace LinuxSampler { namespace gig { Line 69  namespace LinuxSampler { namespace gig {
69       *  Initializes and triggers the voice, a disk stream will be launched if       *  Initializes and triggers the voice, a disk stream will be launched if
70       *  needed.       *  needed.
71       *       *
72       *  @param pNoteOnEvent        - event that caused triggering of this voice       *  @param pEngineChannel - engine channel on which this voice was ordered
73       *  @param PitchBend           - MIDI detune factor (-8192 ... +8191)       *  @param itNoteOnEvent  - event that caused triggering of this voice
74       *  @param pInstrument         - points to the loaded instrument which provides sample wave(s) and articulation data       *  @param PitchBend      - MIDI detune factor (-8192 ... +8191)
75       *  @param iLayer              - layer number this voice refers to (only if this is a layered sound of course)       *  @param pDimRgn        - points to the dimension region which provides sample wave(s) and articulation data
76       *  @param ReleaseTriggerVoice - if this new voice is a release trigger voice (optional, default = false)       *  @param VoiceType      - type of this voice
77       *  @returns 0 on success, a value < 0 if something failed       *  @param iKeyGroup      - a value > 0 defines a key group in which this voice is member of
78         *  @returns 0 on success, a value < 0 if the voice wasn't triggered
79         *           (either due to an error or e.g. because no region is
80         *           defined for the given key)
81       */       */
82      int Voice::Trigger(Event* pNoteOnEvent, int PitchBend, ::gig::Instrument* pInstrument, int iLayer, bool ReleaseTriggerVoice) {      int Voice::Trigger(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int PitchBend, ::gig::DimensionRegion* pDimRgn, type_t VoiceType, int iKeyGroup) {
83          if (!pInstrument) {          this->pEngineChannel = pEngineChannel;
84             dmsg(1,("voice::trigger: !pInstrument\n"));          this->pDimRgn        = pDimRgn;
85             exit(EXIT_FAILURE);          Orphan = false;
86          }  
87            #if CONFIG_DEVMODE
88          Type            = type_normal;          if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging
89          Active          = true;              dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
90          MIDIKey         = pNoteOnEvent->Key;          }
91          pRegion         = pInstrument->GetRegion(MIDIKey);          #endif // CONFIG_DEVMODE
92          PlaybackState   = playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed  
93          Delay           = pNoteOnEvent->FragmentPos();          Type            = VoiceType;
94          pTriggerEvent   = pNoteOnEvent;          MIDIKey         = itNoteOnEvent->Param.Note.Key;
95          pKillEvent      = NULL;          PlaybackState   = playback_state_init; // mark voice as triggered, but no audio rendered yet
96            Delay           = itNoteOnEvent->FragmentPos();
97          if (!pRegion) {          itTriggerEvent  = itNoteOnEvent;
98              std::cerr << "gig::Voice: No Region defined for MIDI key " << MIDIKey << std::endl << std::flush;          itKillEvent     = Pool<Event>::Iterator();
99              KillImmediately();          KeyGroup        = iKeyGroup;
100              return -1;          pSample         = pDimRgn->pSample; // sample won't change until the voice is finished
101          }  
102            // calculate volume
103          KeyGroup = pRegion->KeyGroup;          const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
104    
105          // get current dimension values to select the right dimension region          // For 16 bit samples, we downscale by 32768 to convert from
106          //FIXME: controller values for selecting the dimension region here are currently not sample accurate          // int16 value range to DSP value range (which is
107          uint DimValues[5] = {0,0,0,0,0};          // -1.0..1.0). For 24 bit, we downscale from int32.
108          for (int i = pRegion->Dimensions - 1; i >= 0; i--) {          float volume = velocityAttenuation / (pSample->BitDepth == 16 ? 32768.0f : 32768.0f * 65536.0f);
109              switch (pRegion->pDimensionDefinitions[i].dimension) {  
110                  case ::gig::dimension_samplechannel:          volume *= pDimRgn->SampleAttenuation * pEngineChannel->GlobalVolume * GLOBAL_VOLUME;
111                      DimValues[i] = 0; //TODO: we currently ignore this dimension  
112                      break;          // the volume of release triggered samples depends on note length
113                  case ::gig::dimension_layer:          if (Type == type_release_trigger) {
114                      DimValues[i] = iLayer;              float noteLength = float(pEngine->FrameTime + Delay -
115                      // if this is the 1st layer then spawn further voices for all the other layers                                       pEngineChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime) / pEngine->SampleRate;
116                      if (iLayer == 0)              float attenuation = 1 - 0.01053 * (256 >> pDimRgn->ReleaseTriggerDecay) * noteLength;
117                          for (int iNewLayer = 1; iNewLayer < pRegion->pDimensionDefinitions[i].zones; iNewLayer++)              if (attenuation <= 0) return -1;
118                              pEngine->LaunchVoice(pNoteOnEvent, iNewLayer, ReleaseTriggerVoice);              volume *= attenuation;
119                      break;          }
120                  case ::gig::dimension_velocity:  
121                      DimValues[i] = pNoteOnEvent->Velocity;          // select channel mode (mono or stereo)
122                      break;          SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, pSample->Channels == 2);
123                  case ::gig::dimension_channelaftertouch:          // select bit depth (16 or 24)
124                      DimValues[i] = 0; //TODO: we currently ignore this dimension          SYNTHESIS_MODE_SET_BITDEPTH24(SynthesisMode, pSample->BitDepth == 24);
                     break;  
                 case ::gig::dimension_releasetrigger:  
                     Type = (ReleaseTriggerVoice) ? type_release_trigger : (!iLayer) ? type_release_trigger_required : type_normal;  
                     DimValues[i] = (uint) ReleaseTriggerVoice;  
                     break;  
                 case ::gig::dimension_keyboard:  
                     DimValues[i] = (uint) pNoteOnEvent->Key;  
                     break;  
                 case ::gig::dimension_modwheel:  
                     DimValues[i] = pEngine->ControllerTable[1];  
                     break;  
                 case ::gig::dimension_breath:  
                     DimValues[i] = pEngine->ControllerTable[2];  
                     break;  
                 case ::gig::dimension_foot:  
                     DimValues[i] = pEngine->ControllerTable[4];  
                     break;  
                 case ::gig::dimension_portamentotime:  
                     DimValues[i] = pEngine->ControllerTable[5];  
                     break;  
                 case ::gig::dimension_effect1:  
                     DimValues[i] = pEngine->ControllerTable[12];  
                     break;  
                 case ::gig::dimension_effect2:  
                     DimValues[i] = pEngine->ControllerTable[13];  
                     break;  
                 case ::gig::dimension_genpurpose1:  
                     DimValues[i] = pEngine->ControllerTable[16];  
                     break;  
                 case ::gig::dimension_genpurpose2:  
                     DimValues[i] = pEngine->ControllerTable[17];  
                     break;  
                 case ::gig::dimension_genpurpose3:  
                     DimValues[i] = pEngine->ControllerTable[18];  
                     break;  
                 case ::gig::dimension_genpurpose4:  
                     DimValues[i] = pEngine->ControllerTable[19];  
                     break;  
                 case ::gig::dimension_sustainpedal:  
                     DimValues[i] = pEngine->ControllerTable[64];  
                     break;  
                 case ::gig::dimension_portamento:  
                     DimValues[i] = pEngine->ControllerTable[65];  
                     break;  
                 case ::gig::dimension_sostenutopedal:  
                     DimValues[i] = pEngine->ControllerTable[66];  
                     break;  
                 case ::gig::dimension_softpedal:  
                     DimValues[i] = pEngine->ControllerTable[67];  
                     break;  
                 case ::gig::dimension_genpurpose5:  
                     DimValues[i] = pEngine->ControllerTable[80];  
                     break;  
                 case ::gig::dimension_genpurpose6:  
                     DimValues[i] = pEngine->ControllerTable[81];  
                     break;  
                 case ::gig::dimension_genpurpose7:  
                     DimValues[i] = pEngine->ControllerTable[82];  
                     break;  
                 case ::gig::dimension_genpurpose8:  
                     DimValues[i] = pEngine->ControllerTable[83];  
                     break;  
                 case ::gig::dimension_effect1depth:  
                     DimValues[i] = pEngine->ControllerTable[91];  
                     break;  
                 case ::gig::dimension_effect2depth:  
                     DimValues[i] = pEngine->ControllerTable[92];  
                     break;  
                 case ::gig::dimension_effect3depth:  
                     DimValues[i] = pEngine->ControllerTable[93];  
                     break;  
                 case ::gig::dimension_effect4depth:  
                     DimValues[i] = pEngine->ControllerTable[94];  
                     break;  
                 case ::gig::dimension_effect5depth:  
                     DimValues[i] = pEngine->ControllerTable[95];  
                     break;  
                 case ::gig::dimension_none:  
                     std::cerr << "gig::Voice::Trigger() Error: dimension=none\n" << std::flush;  
                     break;  
                 default:  
                     std::cerr << "gig::Voice::Trigger() Error: Unknown dimension\n" << std::flush;  
             }  
         }  
         pDimRgn = pRegion->GetDimensionRegionByValue(DimValues[4],DimValues[3],DimValues[2],DimValues[1],DimValues[0]);  
125    
126          // get starting crossfade volume level          // get starting crossfade volume level
127            float crossfadeVolume;
128          switch (pDimRgn->AttenuationController.type) {          switch (pDimRgn->AttenuationController.type) {
129              case ::gig::attenuation_ctrl_t::type_channelaftertouch:              case ::gig::attenuation_ctrl_t::type_channelaftertouch:
130                  CrossfadeVolume = 1.0f; //TODO: aftertouch not supported yet                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[128])];
131                  break;                  break;
132              case ::gig::attenuation_ctrl_t::type_velocity:              case ::gig::attenuation_ctrl_t::type_velocity:
133                  CrossfadeVolume = CrossfadeAttenuation(pNoteOnEvent->Velocity);                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity)];
134                  break;                  break;
135              case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate              case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate
136                  CrossfadeVolume = CrossfadeAttenuation(pEngine->ControllerTable[pDimRgn->AttenuationController.controller_number]);                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number])];
137                  break;                  break;
138              case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined              case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined
139              default:              default:
140                  CrossfadeVolume = 1.0f;                  crossfadeVolume = 1.0f;
141          }          }
142    
143          PanLeft  = float(RTMath::Max(pDimRgn->Pan, 0)) / -64.0f;          VolumeLeft  = volume * Engine::PanCurve[64 - pDimRgn->Pan];
144          PanRight = float(RTMath::Min(pDimRgn->Pan, 0)) /  63.0f;          VolumeRight = volume * Engine::PanCurve[64 + pDimRgn->Pan];
145    
146          pSample = pDimRgn->pSample; // sample won't change until the voice is finished          float subfragmentRate = pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE;
147            CrossfadeSmoother.trigger(crossfadeVolume, subfragmentRate);
148            VolumeSmoother.trigger(pEngineChannel->MidiVolume, subfragmentRate);
149            PanLeftSmoother.trigger(pEngineChannel->GlobalPanLeft, subfragmentRate);
150            PanRightSmoother.trigger(pEngineChannel->GlobalPanRight, subfragmentRate);
151    
152          Pos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)          finalSynthesisParameters.dPos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)
153            Pos = pDimRgn->SampleStartOffset;
154    
155          // Check if the sample needs disk streaming or is too short for that          // Check if the sample needs disk streaming or is too short for that
156          long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;          long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;
157          DiskVoice          = cachedsamples < pSample->SamplesTotal;          DiskVoice          = cachedsamples < pSample->SamplesTotal;
158    
159            const DLS::sample_loop_t& loopinfo = pDimRgn->pSampleLoops[0];
160    
161          if (DiskVoice) { // voice to be streamed from disk          if (DiskVoice) { // voice to be streamed from disk
162              MaxRAMPos = cachedsamples - (pEngine->MaxSamplesPerCycle << MAX_PITCH) / pSample->Channels; //TODO: this calculation is too pessimistic and may better be moved to Render() method, so it calculates MaxRAMPos dependent to the current demand of sample points to be rendered (e.g. in case of JACK)              if (cachedsamples > (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH)) {
163                    MaxRAMPos = cachedsamples - (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH) / pSample->Channels; //TODO: this calculation is too pessimistic and may better be moved to Render() method, so it calculates MaxRAMPos dependent to the current demand of sample points to be rendered (e.g. in case of JACK)
164                } else {
165                    // The cache is too small to fit a max sample buffer.
166                    // Setting MaxRAMPos to 0 will probably cause a click
167                    // in the audio, but it's better than not handling
168                    // this case at all, which would have caused the
169                    // unsigned MaxRAMPos to be set to a negative number.
170                    MaxRAMPos = 0;
171                }
172    
173              // check if there's a loop defined which completely fits into the cached (RAM) part of the sample              // check if there's a loop defined which completely fits into the cached (RAM) part of the sample
174              if (pSample->Loops && pSample->LoopEnd <= MaxRAMPos) {              RAMLoop = (pDimRgn->SampleLoops && (loopinfo.LoopStart + loopinfo.LoopLength) <= MaxRAMPos);
                 RAMLoop        = true;  
                 LoopCyclesLeft = pSample->LoopPlayCount;  
             }  
             else RAMLoop = false;  
175    
176              if (pDiskThread->OrderNewStream(&DiskStreamRef, pSample, MaxRAMPos, !RAMLoop) < 0) {              if (pDiskThread->OrderNewStream(&DiskStreamRef, pDimRgn, MaxRAMPos, !RAMLoop) < 0) {
177                  dmsg(1,("Disk stream order failed!\n"));                  dmsg(1,("Disk stream order failed!\n"));
178                  KillImmediately();                  KillImmediately();
179                  return -1;                  return -1;
# Line 285  namespace LinuxSampler { namespace gig { Line 182  namespace LinuxSampler { namespace gig {
182          }          }
183          else { // RAM only voice          else { // RAM only voice
184              MaxRAMPos = cachedsamples;              MaxRAMPos = cachedsamples;
185              if (pSample->Loops) {              RAMLoop = (pDimRgn->SampleLoops != 0);
                 RAMLoop        = true;  
                 LoopCyclesLeft = pSample->LoopPlayCount;  
             }  
             else RAMLoop = false;  
186              dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));              dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));
187          }          }
188            if (RAMLoop) {
189                loop.uiTotalCycles = pSample->LoopPlayCount;
190                loop.uiCyclesLeft  = pSample->LoopPlayCount;
191                loop.uiStart       = loopinfo.LoopStart;
192                loop.uiEnd         = loopinfo.LoopStart + loopinfo.LoopLength;
193                loop.uiSize        = loopinfo.LoopLength;
194            }
195    
196          // calculate initial pitch value          // calculate initial pitch value
197          {          {
198              double pitchbasecents = pDimRgn->FineTune * 10 + (int) pEngine->ScaleTuning[MIDIKey % 12];              double pitchbasecents = pEngineChannel->pInstrument->FineTune + pDimRgn->FineTune + pEngine->ScaleTuning[MIDIKey % 12];
             if (pDimRgn->PitchTrack) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;  
             this->PitchBase = RTMath::CentsToFreqRatio(pitchbasecents) * (double(pSample->SamplesPerSecond) / double(pEngine->pAudioOutputDevice->SampleRate()));  
             this->PitchBend = RTMath::CentsToFreqRatio(((double) PitchBend / 8192.0) * 200.0); // pitchbend wheel +-2 semitones = 200 cents  
         }  
199    
200                // GSt behaviour: maximum transpose up is 40 semitones. If
201                // MIDI key is more than 40 semitones above unity note,
202                // the transpose is not done.
203                if (pDimRgn->PitchTrack && (MIDIKey - (int) pDimRgn->UnityNote) < 40) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;
204    
205          Volume = pDimRgn->GetVelocityAttenuation(pNoteOnEvent->Velocity) / 32768.0f; // we downscale by 32768 to convert from int16 value range to DSP value range (which is -1.0..1.0)              this->PitchBase = RTMath::CentsToFreqRatioUnlimited(pitchbasecents) * (double(pSample->SamplesPerSecond) / double(pEngine->SampleRate));
206                this->PitchBendRange = 1.0 / 8192.0 * 100.0 * pEngineChannel->pInstrument->PitchbendRange;
207                this->PitchBend = RTMath::CentsToFreqRatio(PitchBend * PitchBendRange);
208            }
209    
210            // the length of the decay and release curves are dependent on the velocity
211            const double velrelease = 1 / pDimRgn->GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);
212    
213          // setup EG 1 (VCA EG)          // setup EG 1 (VCA EG)
214          {          {
# Line 315  namespace LinuxSampler { namespace gig { Line 219  namespace LinuxSampler { namespace gig {
219                      eg1controllervalue = 0;                      eg1controllervalue = 0;
220                      break;                      break;
221                  case ::gig::eg1_ctrl_t::type_channelaftertouch:                  case ::gig::eg1_ctrl_t::type_channelaftertouch:
222                      eg1controllervalue = 0; // TODO: aftertouch not yet supported                      eg1controllervalue = pEngineChannel->ControllerTable[128];
223                      break;                      break;
224                  case ::gig::eg1_ctrl_t::type_velocity:                  case ::gig::eg1_ctrl_t::type_velocity:
225                      eg1controllervalue = pNoteOnEvent->Velocity;                      eg1controllervalue = itNoteOnEvent->Param.Note.Velocity;
226                      break;                      break;
227                  case ::gig::eg1_ctrl_t::type_controlchange: // MIDI control change controller                  case ::gig::eg1_ctrl_t::type_controlchange: // MIDI control change controller
228                      eg1controllervalue = pEngine->ControllerTable[pDimRgn->EG1Controller.controller_number];                      eg1controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG1Controller.controller_number];
229                      break;                      break;
230              }              }
231              if (pDimRgn->EG1ControllerInvert) eg1controllervalue = 127 - eg1controllervalue;              if (pDimRgn->EG1ControllerInvert) eg1controllervalue = 127 - eg1controllervalue;
232    
233              // calculate influence of EG1 controller on EG1's parameters (TODO: needs to be fine tuned)              // calculate influence of EG1 controller on EG1's parameters
234              double eg1attack  = (pDimRgn->EG1ControllerAttackInfluence)  ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerAttackInfluence)  * eg1controllervalue : 0.0;              // (eg1attack is different from the others)
235              double eg1decay   = (pDimRgn->EG1ControllerDecayInfluence)   ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerDecayInfluence)   * eg1controllervalue : 0.0;              double eg1attack  = (pDimRgn->EG1ControllerAttackInfluence)  ?
236              double eg1release = (pDimRgn->EG1ControllerReleaseInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerReleaseInfluence) * eg1controllervalue : 0.0;                  1 + 0.031 * (double) (pDimRgn->EG1ControllerAttackInfluence == 1 ?
237                                          1 : 1 << pDimRgn->EG1ControllerAttackInfluence) * eg1controllervalue : 1.0;
238              pEG1->Trigger(pDimRgn->EG1PreAttack,              double eg1decay   = (pDimRgn->EG1ControllerDecayInfluence)   ? 1 + 0.00775 * (double) (1 << pDimRgn->EG1ControllerDecayInfluence)   * eg1controllervalue : 1.0;
239                            pDimRgn->EG1Attack + eg1attack,              double eg1release = (pDimRgn->EG1ControllerReleaseInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG1ControllerReleaseInfluence) * eg1controllervalue : 1.0;
240                            pDimRgn->EG1Hold,  
241                            pSample->LoopStart,              EG1.trigger(pDimRgn->EG1PreAttack,
242                            pDimRgn->EG1Decay1 + eg1decay,                          pDimRgn->EG1Attack * eg1attack,
243                            pDimRgn->EG1Decay2 + eg1decay,                          pDimRgn->EG1Hold,
244                            pDimRgn->EG1InfiniteSustain,                          pDimRgn->EG1Decay1 * eg1decay * velrelease,
245                            pDimRgn->EG1Sustain,                          pDimRgn->EG1Decay2 * eg1decay * velrelease,
246                            pDimRgn->EG1Release + eg1release,                          pDimRgn->EG1InfiniteSustain,
247                            Delay);                          pDimRgn->EG1Sustain,
248          }                          pDimRgn->EG1Release * eg1release * velrelease,
249                            velocityAttenuation,
250                            pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
251            }
252    
253    #ifdef CONFIG_INTERPOLATE_VOLUME
254            // setup initial volume in synthesis parameters
255    #ifdef CONFIG_PROCESS_MUTED_CHANNELS
256            if (pEngineChannel->GetMute()) {
257                finalSynthesisParameters.fFinalVolumeLeft  = 0;
258                finalSynthesisParameters.fFinalVolumeRight = 0;
259            }
260            else
261    #else
262            {
263                float finalVolume = pEngineChannel->MidiVolume * crossfadeVolume * EG1.getLevel();
264    
265                finalSynthesisParameters.fFinalVolumeLeft  = finalVolume * VolumeLeft  * pEngineChannel->GlobalPanLeft;
266                finalSynthesisParameters.fFinalVolumeRight = finalVolume * VolumeRight * pEngineChannel->GlobalPanRight;
267            }
268    #endif
269    #endif
270    
     #if ENABLE_FILTER  
271          // setup EG 2 (VCF Cutoff EG)          // setup EG 2 (VCF Cutoff EG)
272          {          {
273              // get current value of EG2 controller              // get current value of EG2 controller
# Line 354  namespace LinuxSampler { namespace gig { Line 277  namespace LinuxSampler { namespace gig {
277                      eg2controllervalue = 0;                      eg2controllervalue = 0;
278                      break;                      break;
279                  case ::gig::eg2_ctrl_t::type_channelaftertouch:                  case ::gig::eg2_ctrl_t::type_channelaftertouch:
280                      eg2controllervalue = 0; // TODO: aftertouch not yet supported                      eg2controllervalue = pEngineChannel->ControllerTable[128];
281                      break;                      break;
282                  case ::gig::eg2_ctrl_t::type_velocity:                  case ::gig::eg2_ctrl_t::type_velocity:
283                      eg2controllervalue = pNoteOnEvent->Velocity;                      eg2controllervalue = itNoteOnEvent->Param.Note.Velocity;
284                      break;                      break;
285                  case ::gig::eg2_ctrl_t::type_controlchange: // MIDI control change controller                  case ::gig::eg2_ctrl_t::type_controlchange: // MIDI control change controller
286                      eg2controllervalue = pEngine->ControllerTable[pDimRgn->EG2Controller.controller_number];                      eg2controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG2Controller.controller_number];
287                      break;                      break;
288              }              }
289              if (pDimRgn->EG2ControllerInvert) eg2controllervalue = 127 - eg2controllervalue;              if (pDimRgn->EG2ControllerInvert) eg2controllervalue = 127 - eg2controllervalue;
290    
291              // calculate influence of EG2 controller on EG2's parameters (TODO: needs to be fine tuned)              // calculate influence of EG2 controller on EG2's parameters
292              double eg2attack  = (pDimRgn->EG2ControllerAttackInfluence)  ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerAttackInfluence)  * eg2controllervalue : 0.0;              double eg2attack  = (pDimRgn->EG2ControllerAttackInfluence)  ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerAttackInfluence)  * eg2controllervalue : 1.0;
293              double eg2decay   = (pDimRgn->EG2ControllerDecayInfluence)   ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerDecayInfluence)   * eg2controllervalue : 0.0;              double eg2decay   = (pDimRgn->EG2ControllerDecayInfluence)   ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerDecayInfluence)   * eg2controllervalue : 1.0;
294              double eg2release = (pDimRgn->EG2ControllerReleaseInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerReleaseInfluence) * eg2controllervalue : 0.0;              double eg2release = (pDimRgn->EG2ControllerReleaseInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerReleaseInfluence) * eg2controllervalue : 1.0;
295    
296              pEG2->Trigger(pDimRgn->EG2PreAttack,              EG2.trigger(pDimRgn->EG2PreAttack,
297                            pDimRgn->EG2Attack + eg2attack,                          pDimRgn->EG2Attack * eg2attack,
298                            false,                          false,
299                            pSample->LoopStart,                          pDimRgn->EG2Decay1 * eg2decay * velrelease,
300                            pDimRgn->EG2Decay1 + eg2decay,                          pDimRgn->EG2Decay2 * eg2decay * velrelease,
301                            pDimRgn->EG2Decay2 + eg2decay,                          pDimRgn->EG2InfiniteSustain,
302                            pDimRgn->EG2InfiniteSustain,                          pDimRgn->EG2Sustain,
303                            pDimRgn->EG2Sustain,                          pDimRgn->EG2Release * eg2release * velrelease,
304                            pDimRgn->EG2Release + eg2release,                          velocityAttenuation,
305                            Delay);                          pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
306          }          }
     #endif // ENABLE_FILTER  
307    
308    
309          // setup EG 3 (VCO EG)          // setup EG 3 (VCO EG)
310          {          {
311            double eg3depth = RTMath::CentsToFreqRatio(pDimRgn->EG3Depth);              // if portamento mode is on, we dedicate EG3 purely for portamento, otherwise if portamento is off we do as told by the patch
312            pEG3->Trigger(eg3depth, pDimRgn->EG3Attack, Delay);              bool  bPortamento = pEngineChannel->PortamentoMode && pEngineChannel->PortamentoPos >= 0.0f;
313                float eg3depth = (bPortamento)
314                                     ? RTMath::CentsToFreqRatio((pEngineChannel->PortamentoPos - (float) MIDIKey) * 100)
315                                     : RTMath::CentsToFreqRatio(pDimRgn->EG3Depth);
316                float eg3time = (bPortamento)
317                                    ? pEngineChannel->PortamentoTime
318                                    : pDimRgn->EG3Attack;
319                EG3.trigger(eg3depth, eg3time, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
320                dmsg(5,("PortamentoPos=%f, depth=%f, time=%f\n", pEngineChannel->PortamentoPos, eg3depth, eg3time));
321          }          }
322    
323    
# Line 398  namespace LinuxSampler { namespace gig { Line 328  namespace LinuxSampler { namespace gig {
328                  case ::gig::lfo1_ctrl_internal:                  case ::gig::lfo1_ctrl_internal:
329                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;
330                      pLFO1->ExtController = 0; // no external controller                      pLFO1->ExtController = 0; // no external controller
331                        bLFO1Enabled         = (lfo1_internal_depth > 0);
332                      break;                      break;
333                  case ::gig::lfo1_ctrl_modwheel:                  case ::gig::lfo1_ctrl_modwheel:
334                      lfo1_internal_depth  = 0;                      lfo1_internal_depth  = 0;
335                      pLFO1->ExtController = 1; // MIDI controller 1                      pLFO1->ExtController = 1; // MIDI controller 1
336                        bLFO1Enabled         = (pDimRgn->LFO1ControlDepth > 0);
337                      break;                      break;
338                  case ::gig::lfo1_ctrl_breath:                  case ::gig::lfo1_ctrl_breath:
339                      lfo1_internal_depth  = 0;                      lfo1_internal_depth  = 0;
340                      pLFO1->ExtController = 2; // MIDI controller 2                      pLFO1->ExtController = 2; // MIDI controller 2
341                        bLFO1Enabled         = (pDimRgn->LFO1ControlDepth > 0);
342                      break;                      break;
343                  case ::gig::lfo1_ctrl_internal_modwheel:                  case ::gig::lfo1_ctrl_internal_modwheel:
344                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;
345                      pLFO1->ExtController = 1; // MIDI controller 1                      pLFO1->ExtController = 1; // MIDI controller 1
346                        bLFO1Enabled         = (lfo1_internal_depth > 0 || pDimRgn->LFO1ControlDepth > 0);
347                      break;                      break;
348                  case ::gig::lfo1_ctrl_internal_breath:                  case ::gig::lfo1_ctrl_internal_breath:
349                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;                      lfo1_internal_depth  = pDimRgn->LFO1InternalDepth;
350                      pLFO1->ExtController = 2; // MIDI controller 2                      pLFO1->ExtController = 2; // MIDI controller 2
351                        bLFO1Enabled         = (lfo1_internal_depth > 0 || pDimRgn->LFO1ControlDepth > 0);
352                      break;                      break;
353                  default:                  default:
354                      lfo1_internal_depth  = 0;                      lfo1_internal_depth  = 0;
355                      pLFO1->ExtController = 0; // no external controller                      pLFO1->ExtController = 0; // no external controller
356                        bLFO1Enabled         = false;
357                }
358                if (bLFO1Enabled) {
359                    pLFO1->trigger(pDimRgn->LFO1Frequency,
360                                   start_level_min,
361                                   lfo1_internal_depth,
362                                   pDimRgn->LFO1ControlDepth,
363                                   pDimRgn->LFO1FlipPhase,
364                                   pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
365                    pLFO1->update(pLFO1->ExtController ? pEngineChannel->ControllerTable[pLFO1->ExtController] : 0);
366              }              }
             pLFO1->Trigger(pDimRgn->LFO1Frequency,  
                           lfo1_internal_depth,  
                           pDimRgn->LFO1ControlDepth,  
                           pEngine->ControllerTable[pLFO1->ExtController],  
                           pDimRgn->LFO1FlipPhase,  
                           pEngine->SampleRate,  
                           Delay);  
367          }          }
368    
369      #if ENABLE_FILTER  
370          // setup LFO 2 (VCF Cutoff LFO)          // setup LFO 2 (VCF Cutoff LFO)
371          {          {
372              uint16_t lfo2_internal_depth;              uint16_t lfo2_internal_depth;
# Line 436  namespace LinuxSampler { namespace gig { Line 374  namespace LinuxSampler { namespace gig {
374                  case ::gig::lfo2_ctrl_internal:                  case ::gig::lfo2_ctrl_internal:
375                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;
376                      pLFO2->ExtController = 0; // no external controller                      pLFO2->ExtController = 0; // no external controller
377                        bLFO2Enabled         = (lfo2_internal_depth > 0);
378                      break;                      break;
379                  case ::gig::lfo2_ctrl_modwheel:                  case ::gig::lfo2_ctrl_modwheel:
380                      lfo2_internal_depth  = 0;                      lfo2_internal_depth  = 0;
381                      pLFO2->ExtController = 1; // MIDI controller 1                      pLFO2->ExtController = 1; // MIDI controller 1
382                        bLFO2Enabled         = (pDimRgn->LFO2ControlDepth > 0);
383                      break;                      break;
384                  case ::gig::lfo2_ctrl_foot:                  case ::gig::lfo2_ctrl_foot:
385                      lfo2_internal_depth  = 0;                      lfo2_internal_depth  = 0;
386                      pLFO2->ExtController = 4; // MIDI controller 4                      pLFO2->ExtController = 4; // MIDI controller 4
387                        bLFO2Enabled         = (pDimRgn->LFO2ControlDepth > 0);
388                      break;                      break;
389                  case ::gig::lfo2_ctrl_internal_modwheel:                  case ::gig::lfo2_ctrl_internal_modwheel:
390                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;
391                      pLFO2->ExtController = 1; // MIDI controller 1                      pLFO2->ExtController = 1; // MIDI controller 1
392                        bLFO2Enabled         = (lfo2_internal_depth > 0 || pDimRgn->LFO2ControlDepth > 0);
393                      break;                      break;
394                  case ::gig::lfo2_ctrl_internal_foot:                  case ::gig::lfo2_ctrl_internal_foot:
395                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;                      lfo2_internal_depth  = pDimRgn->LFO2InternalDepth;
396                      pLFO2->ExtController = 4; // MIDI controller 4                      pLFO2->ExtController = 4; // MIDI controller 4
397                        bLFO2Enabled         = (lfo2_internal_depth > 0 || pDimRgn->LFO2ControlDepth > 0);
398                      break;                      break;
399                  default:                  default:
400                      lfo2_internal_depth  = 0;                      lfo2_internal_depth  = 0;
401                      pLFO2->ExtController = 0; // no external controller                      pLFO2->ExtController = 0; // no external controller
402                        bLFO2Enabled         = false;
403                }
404                if (bLFO2Enabled) {
405                    pLFO2->trigger(pDimRgn->LFO2Frequency,
406                                   start_level_max,
407                                   lfo2_internal_depth,
408                                   pDimRgn->LFO2ControlDepth,
409                                   pDimRgn->LFO2FlipPhase,
410                                   pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
411                    pLFO2->update(pLFO2->ExtController ? pEngineChannel->ControllerTable[pLFO2->ExtController] : 0);
412              }              }
             pLFO2->Trigger(pDimRgn->LFO2Frequency,  
                           lfo2_internal_depth,  
                           pDimRgn->LFO2ControlDepth,  
                           pEngine->ControllerTable[pLFO2->ExtController],  
                           pDimRgn->LFO2FlipPhase,  
                           pEngine->SampleRate,  
                           Delay);  
413          }          }
414      #endif // ENABLE_FILTER  
415    
416          // setup LFO 3 (VCO LFO)          // setup LFO 3 (VCO LFO)
417          {          {
# Line 474  namespace LinuxSampler { namespace gig { Line 420  namespace LinuxSampler { namespace gig {
420                  case ::gig::lfo3_ctrl_internal:                  case ::gig::lfo3_ctrl_internal:
421                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;
422                      pLFO3->ExtController = 0; // no external controller                      pLFO3->ExtController = 0; // no external controller
423                        bLFO3Enabled         = (lfo3_internal_depth > 0);
424                      break;                      break;
425                  case ::gig::lfo3_ctrl_modwheel:                  case ::gig::lfo3_ctrl_modwheel:
426                      lfo3_internal_depth  = 0;                      lfo3_internal_depth  = 0;
427                      pLFO3->ExtController = 1; // MIDI controller 1                      pLFO3->ExtController = 1; // MIDI controller 1
428                        bLFO3Enabled         = (pDimRgn->LFO3ControlDepth > 0);
429                      break;                      break;
430                  case ::gig::lfo3_ctrl_aftertouch:                  case ::gig::lfo3_ctrl_aftertouch:
431                      lfo3_internal_depth  = 0;                      lfo3_internal_depth  = 0;
432                      pLFO3->ExtController = 0; // TODO: aftertouch not implemented yet                      pLFO3->ExtController = 128;
433                        bLFO3Enabled         = true;
434                      break;                      break;
435                  case ::gig::lfo3_ctrl_internal_modwheel:                  case ::gig::lfo3_ctrl_internal_modwheel:
436                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;
437                      pLFO3->ExtController = 1; // MIDI controller 1                      pLFO3->ExtController = 1; // MIDI controller 1
438                        bLFO3Enabled         = (lfo3_internal_depth > 0 || pDimRgn->LFO3ControlDepth > 0);
439                      break;                      break;
440                  case ::gig::lfo3_ctrl_internal_aftertouch:                  case ::gig::lfo3_ctrl_internal_aftertouch:
441                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;                      lfo3_internal_depth  = pDimRgn->LFO3InternalDepth;
442                      pLFO1->ExtController = 0; // TODO: aftertouch not implemented yet                      pLFO1->ExtController = 128;
443                        bLFO3Enabled         = (lfo3_internal_depth > 0 || pDimRgn->LFO3ControlDepth > 0);
444                      break;                      break;
445                  default:                  default:
446                      lfo3_internal_depth  = 0;                      lfo3_internal_depth  = 0;
447                      pLFO3->ExtController = 0; // no external controller                      pLFO3->ExtController = 0; // no external controller
448                        bLFO3Enabled         = false;
449                }
450                if (bLFO3Enabled) {
451                    pLFO3->trigger(pDimRgn->LFO3Frequency,
452                                   start_level_mid,
453                                   lfo3_internal_depth,
454                                   pDimRgn->LFO3ControlDepth,
455                                   false,
456                                   pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
457                    pLFO3->update(pLFO3->ExtController ? pEngineChannel->ControllerTable[pLFO3->ExtController] : 0);
458              }              }
             pLFO3->Trigger(pDimRgn->LFO3Frequency,  
                           lfo3_internal_depth,  
                           pDimRgn->LFO3ControlDepth,  
                           pEngine->ControllerTable[pLFO3->ExtController],  
                           false,  
                           pEngine->SampleRate,  
                           Delay);  
459          }          }
460    
461      #if ENABLE_FILTER  
462          #if FORCE_FILTER_USAGE          #if CONFIG_FORCE_FILTER
463          FilterLeft.Enabled = FilterRight.Enabled = true;          const bool bUseFilter = true;
464          #else // use filter only if instrument file told so          #else // use filter only if instrument file told so
465          FilterLeft.Enabled = FilterRight.Enabled = pDimRgn->VCFEnabled;          const bool bUseFilter = pDimRgn->VCFEnabled;
466          #endif // FORCE_FILTER_USAGE          #endif // CONFIG_FORCE_FILTER
467          if (pDimRgn->VCFEnabled) {          SYNTHESIS_MODE_SET_FILTER(SynthesisMode, bUseFilter);
468              #ifdef OVERRIDE_FILTER_CUTOFF_CTRL          if (bUseFilter) {
469              VCFCutoffCtrl.controller = OVERRIDE_FILTER_CUTOFF_CTRL;              #ifdef CONFIG_OVERRIDE_CUTOFF_CTRL
470                VCFCutoffCtrl.controller = CONFIG_OVERRIDE_CUTOFF_CTRL;
471              #else // use the one defined in the instrument file              #else // use the one defined in the instrument file
472              switch (pDimRgn->VCFCutoffController) {              switch (pDimRgn->VCFCutoffController) {
473                  case ::gig::vcf_cutoff_ctrl_modwheel:                  case ::gig::vcf_cutoff_ctrl_modwheel:
# Line 542  namespace LinuxSampler { namespace gig { Line 497  namespace LinuxSampler { namespace gig {
497                  case ::gig::vcf_cutoff_ctrl_genpurpose8:                  case ::gig::vcf_cutoff_ctrl_genpurpose8:
498                      VCFCutoffCtrl.controller = 83;                      VCFCutoffCtrl.controller = 83;
499                      break;                      break;
500                  case ::gig::vcf_cutoff_ctrl_aftertouch: //TODO: not implemented yet                  case ::gig::vcf_cutoff_ctrl_aftertouch:
501                        VCFCutoffCtrl.controller = 128;
502                        break;
503                  case ::gig::vcf_cutoff_ctrl_none:                  case ::gig::vcf_cutoff_ctrl_none:
504                  default:                  default:
505                      VCFCutoffCtrl.controller = 0;                      VCFCutoffCtrl.controller = 0;
506                      break;                      break;
507              }              }
508              #endif // OVERRIDE_FILTER_CUTOFF_CTRL              #endif // CONFIG_OVERRIDE_CUTOFF_CTRL
509    
510              #ifdef OVERRIDE_FILTER_RES_CTRL              #ifdef CONFIG_OVERRIDE_RESONANCE_CTRL
511              VCFResonanceCtrl.controller = OVERRIDE_FILTER_RES_CTRL;              VCFResonanceCtrl.controller = CONFIG_OVERRIDE_RESONANCE_CTRL;
512              #else // use the one defined in the instrument file              #else // use the one defined in the instrument file
513              switch (pDimRgn->VCFResonanceController) {              switch (pDimRgn->VCFResonanceController) {
514                  case ::gig::vcf_res_ctrl_genpurpose3:                  case ::gig::vcf_res_ctrl_genpurpose3:
# Line 570  namespace LinuxSampler { namespace gig { Line 527  namespace LinuxSampler { namespace gig {
527                  default:                  default:
528                      VCFResonanceCtrl.controller = 0;                      VCFResonanceCtrl.controller = 0;
529              }              }
530              #endif // OVERRIDE_FILTER_RES_CTRL              #endif // CONFIG_OVERRIDE_RESONANCE_CTRL
531    
532              #ifndef OVERRIDE_FILTER_TYPE              #ifndef CONFIG_OVERRIDE_FILTER_TYPE
533              FilterLeft.SetType(pDimRgn->VCFType);              finalSynthesisParameters.filterLeft.SetType(pDimRgn->VCFType);
534              FilterRight.SetType(pDimRgn->VCFType);              finalSynthesisParameters.filterRight.SetType(pDimRgn->VCFType);
535              #else // override filter type              #else // override filter type
536              FilterLeft.SetType(OVERRIDE_FILTER_TYPE);              finalSynthesisParameters.filterLeft.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
537              FilterRight.SetType(OVERRIDE_FILTER_TYPE);              finalSynthesisParameters.filterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
538              #endif // OVERRIDE_FILTER_TYPE              #endif // CONFIG_OVERRIDE_FILTER_TYPE
539    
540              VCFCutoffCtrl.value    = pEngine->ControllerTable[VCFCutoffCtrl.controller];              VCFCutoffCtrl.value    = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
541              VCFResonanceCtrl.value = pEngine->ControllerTable[VCFResonanceCtrl.controller];              VCFResonanceCtrl.value = pEngineChannel->ControllerTable[VCFResonanceCtrl.controller];
542    
543              // calculate cutoff frequency              // calculate cutoff frequency
544              float cutoff = (!VCFCutoffCtrl.controller)              float cutoff = pDimRgn->GetVelocityCutoff(itNoteOnEvent->Param.Note.Velocity);
                 ? exp((float) (127 - pNoteOnEvent->Velocity) * (float) pDimRgn->VCFVelocityScale * 6.2E-5f * FILTER_CUTOFF_COEFF) * FILTER_CUTOFF_MAX  
                 : exp((float) VCFCutoffCtrl.value * 0.00787402f * FILTER_CUTOFF_COEFF) * FILTER_CUTOFF_MAX;  
   
             // calculate resonance  
             float resonance = (float) VCFResonanceCtrl.value * 0.00787f;   // 0.0..1.0  
545              if (pDimRgn->VCFKeyboardTracking) {              if (pDimRgn->VCFKeyboardTracking) {
546                  resonance += (float) (pNoteOnEvent->Key - pDimRgn->VCFKeyboardTrackingBreakpoint) * 0.00787f;                  cutoff *= exp((itNoteOnEvent->Param.Note.Key - pDimRgn->VCFKeyboardTrackingBreakpoint) * 0.057762265f); // (ln(2) / 12)
547              }              }
548              Constrain(resonance, 0.0, 1.0); // correct resonance if outside allowed value range (0.0..1.0)              CutoffBase = cutoff;
549    
550              VCFCutoffCtrl.fvalue    = cutoff - FILTER_CUTOFF_MIN;              int cvalue;
551              VCFResonanceCtrl.fvalue = resonance;              if (VCFCutoffCtrl.controller) {
552                    cvalue = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
553                    if (pDimRgn->VCFCutoffControllerInvert) cvalue = 127 - cvalue;
554                    // VCFVelocityScale in this case means Minimum cutoff
555                    if (cvalue < pDimRgn->VCFVelocityScale) cvalue = pDimRgn->VCFVelocityScale;
556                }
557                else {
558                    cvalue = pDimRgn->VCFCutoff;
559                }
560                cutoff *= float(cvalue);
561                if (cutoff > 127.0f) cutoff = 127.0f;
562    
563              FilterLeft.SetParameters(cutoff,  resonance, pEngine->SampleRate);              // calculate resonance
564              FilterRight.SetParameters(cutoff, resonance, pEngine->SampleRate);              float resonance = (float) (VCFResonanceCtrl.controller ? VCFResonanceCtrl.value : pDimRgn->VCFResonance);
565    
566              FilterUpdateCounter = -1;              VCFCutoffCtrl.fvalue    = cutoff;
567                VCFResonanceCtrl.fvalue = resonance;
568          }          }
569          else {          else {
570              VCFCutoffCtrl.controller    = 0;              VCFCutoffCtrl.controller    = 0;
571              VCFResonanceCtrl.controller = 0;              VCFResonanceCtrl.controller = 0;
572          }          }
     #endif // ENABLE_FILTER  
573    
574          return 0; // success          return 0; // success
575      }      }
# Line 625  namespace LinuxSampler { namespace gig { Line 587  namespace LinuxSampler { namespace gig {
587       */       */
588      void Voice::Render(uint Samples) {      void Voice::Render(uint Samples) {
589    
590          // Reset the synthesis parameter matrix          // select default values for synthesis mode bits
591          pEngine->ResetSynthesisParameters(Event::destination_vca, this->Volume * this->CrossfadeVolume * pEngine->GlobalVolume);          SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);
         pEngine->ResetSynthesisParameters(Event::destination_vco, this->PitchBase);  
     #if ENABLE_FILTER  
         pEngine->ResetSynthesisParameters(Event::destination_vcfc, VCFCutoffCtrl.fvalue);  
         pEngine->ResetSynthesisParameters(Event::destination_vcfr, VCFResonanceCtrl.fvalue);  
     #endif // ENABLE_FILTER  
   
   
         // Apply events to the synthesis parameter matrix  
         ProcessEvents(Samples);  
   
   
         // Let all modulators write their parameter changes to the synthesis parameter matrix for the current audio fragment  
         pEG1->Process(Samples, pEngine->pMIDIKeyInfo[MIDIKey].pEvents, pTriggerEvent, this->Pos, this->PitchBase * this->PitchBend, pKillEvent);  
     #if ENABLE_FILTER  
         pEG2->Process(Samples, pEngine->pMIDIKeyInfo[MIDIKey].pEvents, pTriggerEvent, this->Pos, this->PitchBase * this->PitchBend);  
     #endif // ENABLE_FILTER  
         pEG3->Process(Samples);  
         pLFO1->Process(Samples);  
     #if ENABLE_FILTER  
         pLFO2->Process(Samples);  
     #endif // ENABLE_FILTER  
         pLFO3->Process(Samples);  
   
   
     #if ENABLE_FILTER  
         CalculateBiquadParameters(Samples); // calculate the final biquad filter parameters  
     #endif // ENABLE_FILTER  
   
592    
593          switch (this->PlaybackState) {          switch (this->PlaybackState) {
594    
595                case playback_state_init:
596                    this->PlaybackState = playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed
597                    // no break - continue with playback_state_ram
598    
599              case playback_state_ram: {              case playback_state_ram: {
600                      if (RAMLoop) InterpolateAndLoop(Samples, (sample_t*) pSample->GetCache().pStart, Delay);                      if (RAMLoop) SYNTHESIS_MODE_SET_LOOP(SynthesisMode, true); // enable looping
601                      else         InterpolateNoLoop(Samples, (sample_t*) pSample->GetCache().pStart, Delay);  
602                        // render current fragment
603                        Synthesize(Samples, (sample_t*) pSample->GetCache().pStart, Delay);
604    
605                      if (DiskVoice) {                      if (DiskVoice) {
606                          // check if we reached the allowed limit of the sample RAM cache                          // check if we reached the allowed limit of the sample RAM cache
607                          if (Pos > MaxRAMPos) {                          if (finalSynthesisParameters.dPos > MaxRAMPos) {
608                              dmsg(5,("Voice: switching to disk playback (Pos=%f)\n", Pos));                              dmsg(5,("Voice: switching to disk playback (Pos=%f)\n", finalSynthesisParameters.dPos));
609                              this->PlaybackState = playback_state_disk;                              this->PlaybackState = playback_state_disk;
610                          }                          }
611                      }                      } else if (finalSynthesisParameters.dPos >= pSample->GetCache().Size / pSample->FrameSize) {
                     else if (Pos >= pSample->GetCache().Size / pSample->FrameSize) {  
612                          this->PlaybackState = playback_state_end;                          this->PlaybackState = playback_state_end;
613                      }                      }
614                  }                  }
# Line 683  namespace LinuxSampler { namespace gig { Line 623  namespace LinuxSampler { namespace gig {
623                              KillImmediately();                              KillImmediately();
624                              return;                              return;
625                          }                          }
626                          DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (RTMath::DoubleToInt(Pos) - MaxRAMPos));                          DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (int(finalSynthesisParameters.dPos) - MaxRAMPos));
627                          Pos -= RTMath::DoubleToInt(Pos);                          finalSynthesisParameters.dPos -= int(finalSynthesisParameters.dPos);
628                            RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet
629                      }                      }
630    
631                        const int sampleWordsLeftToRead = DiskStreamRef.pStream->GetReadSpace();
632    
633                      // add silence sample at the end if we reached the end of the stream (for the interpolator)                      // add silence sample at the end if we reached the end of the stream (for the interpolator)
634                      if (DiskStreamRef.State == Stream::state_end && DiskStreamRef.pStream->GetReadSpace() < (pEngine->MaxSamplesPerCycle << MAX_PITCH) / pSample->Channels) {                      if (DiskStreamRef.State == Stream::state_end) {
635                          DiskStreamRef.pStream->WriteSilence((pEngine->MaxSamplesPerCycle << MAX_PITCH) / pSample->Channels);                          const int maxSampleWordsPerCycle = (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH) * pSample->Channels + 6; // +6 for the interpolator algorithm
636                          this->PlaybackState = playback_state_end;                          if (sampleWordsLeftToRead <= maxSampleWordsPerCycle) {
637                                // remember how many sample words there are before any silence has been added
638                                if (RealSampleWordsLeftToRead < 0) RealSampleWordsLeftToRead = sampleWordsLeftToRead;
639                                DiskStreamRef.pStream->WriteSilence(maxSampleWordsPerCycle - sampleWordsLeftToRead);
640                            }
641                      }                      }
642    
643                      sample_t* ptr = DiskStreamRef.pStream->GetReadPtr(); // get the current read_ptr within the ringbuffer where we read the samples from                      sample_t* ptr = (sample_t*)DiskStreamRef.pStream->GetReadPtr(); // get the current read_ptr within the ringbuffer where we read the samples from
644                      InterpolateNoLoop(Samples, ptr, Delay);  
645                      DiskStreamRef.pStream->IncrementReadPos(RTMath::DoubleToInt(Pos) * pSample->Channels);                      // render current audio fragment
646                      Pos -= RTMath::DoubleToInt(Pos);                      Synthesize(Samples, ptr, Delay);
647    
648                        const int iPos = (int) finalSynthesisParameters.dPos;
649                        const int readSampleWords = iPos * pSample->Channels; // amount of sample words actually been read
650                        DiskStreamRef.pStream->IncrementReadPos(readSampleWords);
651                        finalSynthesisParameters.dPos -= iPos; // just keep fractional part of playback position
652    
653                        // change state of voice to 'end' if we really reached the end of the sample data
654                        if (RealSampleWordsLeftToRead >= 0) {
655                            RealSampleWordsLeftToRead -= readSampleWords;
656                            if (RealSampleWordsLeftToRead <= 0) this->PlaybackState = playback_state_end;
657                        }
658                  }                  }
659                  break;                  break;
660    
661              case playback_state_end:              case playback_state_end:
662                  KillImmediately(); // free voice                  std::cerr << "gig::Voice::Render(): entered with playback_state_end, this is a bug!\n" << std::flush;
663                  break;                  break;
664          }          }
665    
   
         // Reset synthesis event lists (except VCO, as VCO events apply channel wide currently)  
         pEngine->pSynthesisEvents[Event::destination_vca]->clear();  
     #if ENABLE_FILTER  
         pEngine->pSynthesisEvents[Event::destination_vcfc]->clear();  
         pEngine->pSynthesisEvents[Event::destination_vcfr]->clear();  
     #endif // ENABLE_FILTER  
   
666          // Reset delay          // Reset delay
667          Delay = 0;          Delay = 0;
668    
669          pTriggerEvent = NULL;          itTriggerEvent = Pool<Event>::Iterator();
670    
671          // If release stage finished, let the voice be killed          // If sample stream or release stage finished, kill the voice
672          if (pEG1->GetStage() == EGADSR::stage_end) this->PlaybackState = playback_state_end;          if (PlaybackState == playback_state_end || EG1.getSegmentType() == EGADSR::segment_end) KillImmediately();
673      }      }
674    
675      /**      /**
# Line 727  namespace LinuxSampler { namespace gig { Line 677  namespace LinuxSampler { namespace gig {
677       *  suspended / not running.       *  suspended / not running.
678       */       */
679      void Voice::Reset() {      void Voice::Reset() {
680          pLFO1->Reset();          finalSynthesisParameters.filterLeft.Reset();
681          pLFO2->Reset();          finalSynthesisParameters.filterRight.Reset();
         pLFO3->Reset();  
682          DiskStreamRef.pStream = NULL;          DiskStreamRef.pStream = NULL;
683          DiskStreamRef.hStream = 0;          DiskStreamRef.hStream = 0;
684          DiskStreamRef.State   = Stream::state_unused;          DiskStreamRef.State   = Stream::state_unused;
685          DiskStreamRef.OrderID = 0;          DiskStreamRef.OrderID = 0;
686          Active = false;          PlaybackState = playback_state_end;
687            itTriggerEvent = Pool<Event>::Iterator();
688            itKillEvent    = Pool<Event>::Iterator();
689      }      }
690    
691      /**      /**
692       *  Process the control change event lists of the engine for the current       * Process given list of MIDI note on, note off and sustain pedal events
693       *  audio fragment. Event values will be applied to the synthesis parameter       * for the given time.
      *  matrix.  
694       *       *
695       *  @param Samples - number of samples to be rendered in this audio fragment cycle       * @param itEvent - iterator pointing to the next event to be processed
696         * @param End     - youngest time stamp where processing should be stopped
697       */       */
698      void Voice::ProcessEvents(uint Samples) {      void Voice::processTransitionEvents(RTList<Event>::Iterator& itEvent, uint End) {
699            for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
700                if (itEvent->Type == Event::type_release) {
701                    EG1.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
702                    EG2.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
703                } else if (itEvent->Type == Event::type_cancel_release) {
704                    EG1.update(EGADSR::event_cancel_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
705                    EG2.update(EGADSR::event_cancel_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
706                }
707            }
708        }
709    
710          // dispatch control change events      /**
711          Event* pCCEvent = pEngine->pCCEvents->first();       * Process given list of MIDI control change and pitch bend events for
712          if (Delay) { // skip events that happened before this voice was triggered       * the given time.
713              while (pCCEvent && pCCEvent->FragmentPos() <= Delay) pCCEvent = pEngine->pCCEvents->next();       *
714          }       * @param itEvent - iterator pointing to the next event to be processed
715          while (pCCEvent) {       * @param End     - youngest time stamp where processing should be stopped
716              if (pCCEvent->Controller) { // if valid MIDI controller       */
717                  #if ENABLE_FILTER      void Voice::processCCEvents(RTList<Event>::Iterator& itEvent, uint End) {
718                  if (pCCEvent->Controller == VCFCutoffCtrl.controller) {          for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
719                      pEngine->pSynthesisEvents[Event::destination_vcfc]->alloc_assign(*pCCEvent);              if (itEvent->Type == Event::type_control_change &&
720                  }                  itEvent->Param.CC.Controller) { // if (valid) MIDI control change event
721                  if (pCCEvent->Controller == VCFResonanceCtrl.controller) {                  if (itEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {
722                      pEngine->pSynthesisEvents[Event::destination_vcfr]->alloc_assign(*pCCEvent);                      processCutoffEvent(itEvent);
723                    }
724                    if (itEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {
725                        processResonanceEvent(itEvent);
726                  }                  }
727                  #endif // ENABLE_FILTER                  if (itEvent->Param.CC.Controller == pLFO1->ExtController) {
728                  if (pCCEvent->Controller == pLFO1->ExtController) {                      pLFO1->update(itEvent->Param.CC.Value);
                     pLFO1->SendEvent(pCCEvent);  
729                  }                  }
730                  #if ENABLE_FILTER                  if (itEvent->Param.CC.Controller == pLFO2->ExtController) {
731                  if (pCCEvent->Controller == pLFO2->ExtController) {                      pLFO2->update(itEvent->Param.CC.Value);
                     pLFO2->SendEvent(pCCEvent);  
732                  }                  }
733                  #endif // ENABLE_FILTER                  if (itEvent->Param.CC.Controller == pLFO3->ExtController) {
734                  if (pCCEvent->Controller == pLFO3->ExtController) {                      pLFO3->update(itEvent->Param.CC.Value);
                     pLFO3->SendEvent(pCCEvent);  
735                  }                  }
736                  if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&                  if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&
737                      pCCEvent->Controller == pDimRgn->AttenuationController.controller_number) { // if crossfade event                      itEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) {
738                      pEngine->pSynthesisEvents[Event::destination_vca]->alloc_assign(*pCCEvent);                      CrossfadeSmoother.update(Engine::CrossfadeCurve[CrossfadeAttenuation(itEvent->Param.CC.Value)]);
739                    }
740                    if (itEvent->Param.CC.Controller == 7) { // volume
741                        VolumeSmoother.update(Engine::VolumeCurve[itEvent->Param.CC.Value]);
742                    } else if (itEvent->Param.CC.Controller == 10) { // panpot
743                        PanLeftSmoother.update(Engine::PanCurve[128 - itEvent->Param.CC.Value]);
744                        PanRightSmoother.update(Engine::PanCurve[itEvent->Param.CC.Value]);
745                  }                  }
746                } else if (itEvent->Type == Event::type_pitchbend) { // if pitch bend event
747                    processPitchEvent(itEvent);
748              }              }
   
             pCCEvent = pEngine->pCCEvents->next();  
749          }          }
750        }
751    
752        void Voice::processPitchEvent(RTList<Event>::Iterator& itEvent) {
753            PitchBend = RTMath::CentsToFreqRatio(itEvent->Param.Pitch.Pitch * PitchBendRange);
754        }
755    
756          // process pitch events      void Voice::processCutoffEvent(RTList<Event>::Iterator& itEvent) {
757          {          int ccvalue = itEvent->Param.CC.Value;
758              RTEList<Event>* pVCOEventList = pEngine->pSynthesisEvents[Event::destination_vco];          if (VCFCutoffCtrl.value == ccvalue) return;
759              Event* pVCOEvent = pVCOEventList->first();          VCFCutoffCtrl.value == ccvalue;
760              if (Delay) { // skip events that happened before this voice was triggered          if (pDimRgn->VCFCutoffControllerInvert)  ccvalue = 127 - ccvalue;
761                  while (pVCOEvent && pVCOEvent->FragmentPos() <= Delay) pVCOEvent = pVCOEventList->next();          if (ccvalue < pDimRgn->VCFVelocityScale) ccvalue = pDimRgn->VCFVelocityScale;
762              }          float cutoff = CutoffBase * float(ccvalue);
763              // apply old pitchbend value until first pitch event occurs          if (cutoff > 127.0f) cutoff = 127.0f;
764              if (this->PitchBend != 1.0) {  
765                  uint end = (pVCOEvent) ? pVCOEvent->FragmentPos() : Samples;          VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of fFinalCutoff next time
766                  for (uint i = Delay; i < end; i++) {          fFinalCutoff = cutoff;
767                      pEngine->pSynthesisParameters[Event::destination_vco][i] *= this->PitchBend;      }
768    
769        void Voice::processResonanceEvent(RTList<Event>::Iterator& itEvent) {
770            // convert absolute controller value to differential
771            const int ctrldelta = itEvent->Param.CC.Value - VCFResonanceCtrl.value;
772            VCFResonanceCtrl.value = itEvent->Param.CC.Value;
773            const float resonancedelta = (float) ctrldelta;
774            fFinalResonance += resonancedelta;
775            // needed for initialization of parameter
776            VCFResonanceCtrl.fvalue = itEvent->Param.CC.Value;
777        }
778    
779        /**
780         *  Synthesizes the current audio fragment for this voice.
781         *
782         *  @param Samples - number of sample points to be rendered in this audio
783         *                   fragment cycle
784         *  @param pSrc    - pointer to input sample data
785         *  @param Skip    - number of sample points to skip in output buffer
786         */
787        void Voice::Synthesize(uint Samples, sample_t* pSrc, uint Skip) {
788            finalSynthesisParameters.pOutLeft  = &pEngineChannel->pChannelLeft->Buffer()[Skip];
789            finalSynthesisParameters.pOutRight = &pEngineChannel->pChannelRight->Buffer()[Skip];
790            finalSynthesisParameters.pSrc      = pSrc;
791    
792            RTList<Event>::Iterator itCCEvent = pEngineChannel->pEvents->first();
793            RTList<Event>::Iterator itNoteEvent = pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents->first();
794    
795            if (itTriggerEvent) { // skip events that happened before this voice was triggered
796                while (itCCEvent && itCCEvent->FragmentPos() <= Skip) ++itCCEvent;
797                // we can't simply compare the timestamp here, because note events
798                // might happen on the same time stamp, so we have to deal on the
799                // actual sequence the note events arrived instead (see bug #112)
800                for (; itNoteEvent; ++itNoteEvent) {
801                    if (itTriggerEvent == itNoteEvent) {
802                        ++itNoteEvent;
803                        break;
804                  }                  }
805              }              }
806              float pitch;          }
             while (pVCOEvent) {  
                 Event* pNextVCOEvent = pVCOEventList->next();  
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (pNextVCOEvent) ? pNextVCOEvent->FragmentPos() : Samples;  
   
                 pitch = RTMath::CentsToFreqRatio(((double) pVCOEvent->Pitch / 8192.0) * 200.0); // +-two semitones = +-200 cents  
   
                 // apply pitch value to the pitch parameter sequence  
                 for (uint i = pVCOEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vco][i] *= pitch;  
                 }  
807    
808                  pVCOEvent = pNextVCOEvent;          uint killPos;
809            if (itKillEvent) {
810                int maxFadeOutPos = Samples - pEngine->MinFadeOutSamples;
811                if (maxFadeOutPos < 0) {
812                    // There's not enough space in buffer to do a fade out
813                    // from max volume (this can only happen for audio
814                    // drivers that use Samples < MaxSamplesPerCycle).
815                    // End the EG1 here, at pos 0, with a shorter max fade
816                    // out time.
817                    EG1.enterFadeOutStage(Samples / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
818                    itKillEvent = Pool<Event>::Iterator();
819                } else {
820                    killPos = RTMath::Min(itKillEvent->FragmentPos(), maxFadeOutPos);
821              }              }
             if (pVCOEventList->last()) this->PitchBend = pitch;  
822          }          }
823    
824          // process volume / attenuation events (TODO: we only handle and _expect_ crossfade events here ATM !)          uint i = Skip;
825          {          while (i < Samples) {
826              RTEList<Event>* pVCAEventList = pEngine->pSynthesisEvents[Event::destination_vca];              int iSubFragmentEnd = RTMath::Min(i + CONFIG_DEFAULT_SUBFRAGMENT_SIZE, Samples);
             Event* pVCAEvent = pVCAEventList->first();  
             if (Delay) { // skip events that happened before this voice was triggered  
                 while (pVCAEvent && pVCAEvent->FragmentPos() <= Delay) pVCAEvent = pVCAEventList->next();  
             }  
             float crossfadevolume;  
             while (pVCAEvent) {  
                 Event* pNextVCAEvent = pVCAEventList->next();  
827    
828                  // calculate the influence length of this event (in sample points)              // initialize all final synthesis parameters
829                  uint end = (pNextVCAEvent) ? pNextVCAEvent->FragmentPos() : Samples;              fFinalCutoff    = VCFCutoffCtrl.fvalue;
830                fFinalResonance = VCFResonanceCtrl.fvalue;
831    
832                  crossfadevolume = CrossfadeAttenuation(pVCAEvent->Value);              // process MIDI control change and pitchbend events for this subfragment
833                processCCEvents(itCCEvent, iSubFragmentEnd);
834    
835                  float effective_volume = crossfadevolume * this->Volume * pEngine->GlobalVolume;              finalSynthesisParameters.fFinalPitch = PitchBase * PitchBend;
836                float fFinalVolume = VolumeSmoother.render() * CrossfadeSmoother.render();
837    #ifdef CONFIG_PROCESS_MUTED_CHANNELS
838                if (pEngineChannel->GetMute()) fFinalVolume = 0;
839    #endif
840    
841                  // apply volume value to the volume parameter sequence              // process transition events (note on, note off & sustain pedal)
842                  for (uint i = pVCAEvent->FragmentPos(); i < end; i++) {              processTransitionEvents(itNoteEvent, iSubFragmentEnd);
                     pEngine->pSynthesisParameters[Event::destination_vca][i] = effective_volume;  
                 }  
843    
844                  pVCAEvent = pNextVCAEvent;              // if the voice was killed in this subfragment, or if the
845                // filter EG is finished, switch EG1 to fade out stage
846                if ((itKillEvent && killPos <= iSubFragmentEnd) ||
847                    (SYNTHESIS_MODE_GET_FILTER(SynthesisMode) &&
848                     EG2.getSegmentType() == EGADSR::segment_end)) {
849                    EG1.enterFadeOutStage();
850                    itKillEvent = Pool<Event>::Iterator();
851              }              }
             if (pVCAEventList->last()) this->CrossfadeVolume = crossfadevolume;  
         }  
852    
853      #if ENABLE_FILTER              // process envelope generators
854          // process filter cutoff events              switch (EG1.getSegmentType()) {
855          {                  case EGADSR::segment_lin:
856              RTEList<Event>* pCutoffEventList = pEngine->pSynthesisEvents[Event::destination_vcfc];                      fFinalVolume *= EG1.processLin();
857              Event* pCutoffEvent = pCutoffEventList->first();                      break;
858              if (Delay) { // skip events that happened before this voice was triggered                  case EGADSR::segment_exp:
859                  while (pCutoffEvent && pCutoffEvent->FragmentPos() <= Delay) pCutoffEvent = pCutoffEventList->next();                      fFinalVolume *= EG1.processExp();
860              }                      break;
861              float cutoff;                  case EGADSR::segment_end:
862              while (pCutoffEvent) {                      fFinalVolume *= EG1.getLevel();
863                  Event* pNextCutoffEvent = pCutoffEventList->next();                      break; // noop
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (pNextCutoffEvent) ? pNextCutoffEvent->FragmentPos() : Samples;  
   
                 cutoff = exp((float) pCutoffEvent->Value * 0.00787402f * FILTER_CUTOFF_COEFF) * FILTER_CUTOFF_MAX - FILTER_CUTOFF_MIN;  
   
                 // apply cutoff frequency to the cutoff parameter sequence  
                 for (uint i = pCutoffEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vcfc][i] = cutoff;  
                 }  
   
                 pCutoffEvent = pNextCutoffEvent;  
864              }              }
865              if (pCutoffEventList->last()) VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of parameter matrix next time              switch (EG2.getSegmentType()) {
866          }                  case EGADSR::segment_lin:
867                        fFinalCutoff *= EG2.processLin();
868                        break;
869                    case EGADSR::segment_exp:
870                        fFinalCutoff *= EG2.processExp();
871                        break;
872                    case EGADSR::segment_end:
873                        fFinalCutoff *= EG2.getLevel();
874                        break; // noop
875                }
876                if (EG3.active()) finalSynthesisParameters.fFinalPitch *= EG3.render();
877    
878          // process filter resonance events              // process low frequency oscillators
879          {              if (bLFO1Enabled) fFinalVolume *= (1.0f - pLFO1->render());
880              RTEList<Event>* pResonanceEventList = pEngine->pSynthesisEvents[Event::destination_vcfr];              if (bLFO2Enabled) fFinalCutoff *= pLFO2->render();
881              Event* pResonanceEvent = pResonanceEventList->first();              if (bLFO3Enabled) finalSynthesisParameters.fFinalPitch *= RTMath::CentsToFreqRatio(pLFO3->render());
             if (Delay) { // skip events that happened before this voice was triggered  
                 while (pResonanceEvent && pResonanceEvent->FragmentPos() <= Delay) pResonanceEvent = pResonanceEventList->next();  
             }  
             while (pResonanceEvent) {  
                 Event* pNextResonanceEvent = pResonanceEventList->next();  
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (pNextResonanceEvent) ? pNextResonanceEvent->FragmentPos() : Samples;  
   
                 // convert absolute controller value to differential  
                 int ctrldelta = pResonanceEvent->Value - VCFResonanceCtrl.value;  
                 VCFResonanceCtrl.value = pResonanceEvent->Value;  
   
                 float resonancedelta = (float) ctrldelta * 0.00787f; // 0.0..1.0  
   
                 // apply cutoff frequency to the cutoff parameter sequence  
                 for (uint i = pResonanceEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vcfr][i] += resonancedelta;  
                 }  
882    
883                  pResonanceEvent = pNextResonanceEvent;              // limit the pitch so we don't read outside the buffer
884                finalSynthesisParameters.fFinalPitch = RTMath::Min(finalSynthesisParameters.fFinalPitch, float(1 << CONFIG_MAX_PITCH));
885    
886                // if filter enabled then update filter coefficients
887                if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode)) {
888                    finalSynthesisParameters.filterLeft.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
889                    finalSynthesisParameters.filterRight.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
890              }              }
             if (pResonanceEventList->last()) VCFResonanceCtrl.fvalue = pResonanceEventList->last()->Value * 0.00787f; // needed for initialization of parameter matrix next time  
         }  
     #endif // ENABLE_FILTER  
     }  
891    
892      #if ENABLE_FILTER              // do we need resampling?
893      /**              const float __PLUS_ONE_CENT  = 1.000577789506554859250142541782224725466f;
894       * Calculate all necessary, final biquad filter parameters.              const float __MINUS_ONE_CENT = 0.9994225441413807496009516495583113737666f;
895       *              const bool bResamplingRequired = !(finalSynthesisParameters.fFinalPitch <= __PLUS_ONE_CENT &&
896       * @param Samples - number of samples to be rendered in this audio fragment cycle                                                 finalSynthesisParameters.fFinalPitch >= __MINUS_ONE_CENT);
897       */              SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, bResamplingRequired);
     void Voice::CalculateBiquadParameters(uint Samples) {  
         if (!FilterLeft.Enabled) return;  
898    
899          biquad_param_t bqbase;              // prepare final synthesis parameters structure
900          biquad_param_t bqmain;              finalSynthesisParameters.uiToGo            = iSubFragmentEnd - i;
901          float prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][0];  #ifdef CONFIG_INTERPOLATE_VOLUME
902          float prev_res    = pEngine->pSynthesisParameters[Event::destination_vcfr][0];              finalSynthesisParameters.fFinalVolumeDeltaLeft  =
903          FilterLeft.SetParameters(&bqbase, &bqmain, prev_cutoff, prev_res, pEngine->SampleRate);                  (fFinalVolume * VolumeLeft  * PanLeftSmoother.render() -
904          pEngine->pBasicFilterParameters[0] = bqbase;                   finalSynthesisParameters.fFinalVolumeLeft) / finalSynthesisParameters.uiToGo;
905          pEngine->pMainFilterParameters[0]  = bqmain;              finalSynthesisParameters.fFinalVolumeDeltaRight =
906                    (fFinalVolume * VolumeRight * PanRightSmoother.render() -
907          float* bq;                   finalSynthesisParameters.fFinalVolumeRight) / finalSynthesisParameters.uiToGo;
908          for (int i = 1; i < Samples; i++) {  #else
909              // recalculate biquad parameters if cutoff or resonance differ from previous sample point              finalSynthesisParameters.fFinalVolumeLeft  =
910              if (!(i & FILTER_UPDATE_MASK)) if (pEngine->pSynthesisParameters[Event::destination_vcfr][i] != prev_res ||                  fFinalVolume * VolumeLeft  * PanLeftSmoother.render();
911                                                 pEngine->pSynthesisParameters[Event::destination_vcfc][i] != prev_cutoff) {              finalSynthesisParameters.fFinalVolumeRight =
912                  prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][i];                  fFinalVolume * VolumeRight * PanRightSmoother.render();
913                  prev_res    = pEngine->pSynthesisParameters[Event::destination_vcfr][i];  #endif
914                  FilterLeft.SetParameters(&bqbase, &bqmain, prev_cutoff, prev_res, pEngine->SampleRate);              // render audio for one subfragment
915              }              RunSynthesisFunction(SynthesisMode, &finalSynthesisParameters, &loop);
   
             //same as 'pEngine->pBasicFilterParameters[i] = bqbase;'  
             bq    = (float*) &pEngine->pBasicFilterParameters[i];  
             bq[0] = bqbase.a1;  
             bq[1] = bqbase.a2;  
             bq[2] = bqbase.b0;  
             bq[3] = bqbase.b1;  
             bq[4] = bqbase.b2;  
   
             // same as 'pEngine->pMainFilterParameters[i] = bqmain;'  
             bq    = (float*) &pEngine->pMainFilterParameters[i];  
             bq[0] = bqmain.a1;  
             bq[1] = bqmain.a2;  
             bq[2] = bqmain.b0;  
             bq[3] = bqmain.b1;  
             bq[4] = bqmain.b2;  
         }  
     }  
     #endif // ENABLE_FILTER  
916    
917      /**              // stop the rendering if volume EG is finished
918       *  Interpolates the input audio data (without looping).              if (EG1.getSegmentType() == EGADSR::segment_end) break;
      *  
      *  @param Samples - number of sample points to be rendered in this audio  
      *                   fragment cycle  
      *  @param pSrc    - pointer to input sample data  
      *  @param Skip    - number of sample points to skip in output buffer  
      */  
     void Voice::InterpolateNoLoop(uint Samples, sample_t* pSrc, uint Skip) {  
         int i = Skip;  
919    
920          // FIXME: assuming either mono or stereo              const double newPos = Pos + (iSubFragmentEnd - i) * finalSynthesisParameters.fFinalPitch;
         if (this->pSample->Channels == 2) { // Stereo Sample  
             while (i < Samples) InterpolateStereo(pSrc, i);  
         }  
         else { // Mono Sample  
             while (i < Samples) InterpolateMono(pSrc, i);  
         }  
     }  
921    
922      /**              // increment envelopes' positions
923       *  Interpolates the input audio data, this method honors looping.              if (EG1.active()) {
      *  
      *  @param Samples - number of sample points to be rendered in this audio  
      *                   fragment cycle  
      *  @param pSrc    - pointer to input sample data  
      *  @param Skip    - number of sample points to skip in output buffer  
      */  
     void Voice::InterpolateAndLoop(uint Samples, sample_t* pSrc, uint Skip) {  
         int i = Skip;  
924    
925          // FIXME: assuming either mono or stereo                  // if sample has a loop and loop start has been reached in this subfragment, send a special event to EG1 to let it finish the attack hold stage
926          if (pSample->Channels == 2) { // Stereo Sample                  if (pDimRgn->SampleLoops && Pos <= pDimRgn->pSampleLoops[0].LoopStart && pDimRgn->pSampleLoops[0].LoopStart < newPos) {
927              if (pSample->LoopPlayCount) {                      EG1.update(EGADSR::event_hold_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
                 // render loop (loop count limited)  
                 while (i < Samples && LoopCyclesLeft) {  
                     InterpolateStereo(pSrc, i);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                         LoopCyclesLeft--;  
                     }  
                 }  
                 // render on without loop  
                 while (i < Samples) InterpolateStereo(pSrc, i);  
             }  
             else { // render loop (endless loop)  
                 while (i < Samples) {  
                     InterpolateStereo(pSrc, i);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);  
                     }  
                 }  
             }  
         }  
         else { // Mono Sample  
             if (pSample->LoopPlayCount) {  
                 // render loop (loop count limited)  
                 while (i < Samples && LoopCyclesLeft) {  
                     InterpolateMono(pSrc, i);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                         LoopCyclesLeft--;  
                     }  
928                  }                  }
929                  // render on without loop  
930                  while (i < Samples) InterpolateMono(pSrc, i);                  EG1.increment(1);
931                    if (!EG1.toStageEndLeft()) EG1.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
932              }              }
933              else { // render loop (endless loop)              if (EG2.active()) {
934                  while (i < Samples) {                  EG2.increment(1);
935                      InterpolateMono(pSrc, i);                  if (!EG2.toStageEndLeft()) EG2.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                     }  
                 }  
936              }              }
937                EG3.increment(1);
938                if (!EG3.toEndLeft()) EG3.update(); // neutralize envelope coefficient if end reached
939    
940                Pos = newPos;
941                i = iSubFragmentEnd;
942          }          }
943      }      }
944    
945        /** @brief Update current portamento position.
946         *
947         * Will be called when portamento mode is enabled to get the final
948         * portamento position of this active voice from where the next voice(s)
949         * might continue to slide on.
950         *
951         * @param itNoteOffEvent - event which causes this voice to die soon
952         */
953        void Voice::UpdatePortamentoPos(Pool<Event>::Iterator& itNoteOffEvent) {
954            const float fFinalEG3Level = EG3.level(itNoteOffEvent->FragmentPos());
955            pEngineChannel->PortamentoPos = (float) MIDIKey + RTMath::FreqRatioToCents(fFinalEG3Level) * 0.01f;
956        }
957    
958      /**      /**
959       *  Immediately kill the voice. This method should not be used to kill       *  Immediately kill the voice. This method should not be used to kill
960       *  a normal, active voice, because it doesn't take care of things like       *  a normal, active voice, because it doesn't take care of things like
961       *  fading down the volume level to avoid clicks and regular processing       *  fading down the volume level to avoid clicks and regular processing
962       *  until the kill event actually occured!       *  until the kill event actually occured!
963       *       *
964       *  @see Kill()       * If it's necessary to know when the voice's disk stream was actually
965         * deleted, then one can set the optional @a bRequestNotification
966         * parameter and this method will then return the handle of the disk
967         * stream (unique identifier) and one can use this handle to poll the
968         * disk thread if this stream has been deleted. In any case this method
969         * will return immediately and will not block until the stream actually
970         * was deleted.
971         *
972         * @param bRequestNotification - (optional) whether the disk thread shall
973         *                                provide a notification once it deleted
974         *                               the respective disk stream
975         *                               (default=false)
976         * @returns handle to the voice's disk stream or @c Stream::INVALID_HANDLE
977         *          if the voice did not use a disk stream at all
978         * @see Kill()
979       */       */
980      void Voice::KillImmediately() {      Stream::Handle Voice::KillImmediately(bool bRequestNotification) {
981            Stream::Handle hStream = Stream::INVALID_HANDLE;
982          if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {          if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
983              pDiskThread->OrderDeletionOfStream(&DiskStreamRef);              pDiskThread->OrderDeletionOfStream(&DiskStreamRef, bRequestNotification);
984                hStream = DiskStreamRef.hStream;
985          }          }
986          Reset();          Reset();
987            return hStream;
988      }      }
989    
990      /**      /**
# Line 1047  namespace LinuxSampler { namespace gig { Line 994  namespace LinuxSampler { namespace gig {
994       *  of a voice, a kill process cannot be cancalled and is therefore       *  of a voice, a kill process cannot be cancalled and is therefore
995       *  usually used for voice stealing and key group conflicts.       *  usually used for voice stealing and key group conflicts.
996       *       *
997       *  @param pKillEvent - event which caused the voice to be killed       *  @param itKillEvent - event which caused the voice to be killed
998       */       */
999      void Voice::Kill(Event* pKillEvent) {      void Voice::Kill(Pool<Event>::Iterator& itKillEvent) {
1000          if (pTriggerEvent && pKillEvent->FragmentPos() <= pTriggerEvent->FragmentPos()) return;          #if CONFIG_DEVMODE
1001          this->pKillEvent = pKillEvent;          if (!itKillEvent) dmsg(1,("gig::Voice::Kill(): ERROR, !itKillEvent !!!\n"));
1002            if (itKillEvent && !itKillEvent.isValid()) dmsg(1,("gig::Voice::Kill(): ERROR, itKillEvent invalid !!!\n"));
1003            #endif // CONFIG_DEVMODE
1004    
1005            if (itTriggerEvent && itKillEvent->FragmentPos() <= itTriggerEvent->FragmentPos()) return;
1006            this->itKillEvent = itKillEvent;
1007      }      }
1008    
1009  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.245  
changed lines
  Added in v.2012

  ViewVC Help
Powered by ViewVC