/[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 53 by schoenebeck, Mon Apr 26 17:15:51 2004 UTC revision 2012 by iliev, Fri Oct 23 17:53:17 2009 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 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    
     // FIXME: no support for layers (nor crossfades) yet  
   
     const float Voice::FILTER_CUTOFF_COEFF(CalculateFilterCutoffCoeff());  
   
     float Voice::CalculateFilterCutoffCoeff() {  
         return log(FILTER_CUTOFF_MIN / FILTER_CUTOFF_MAX);  
     }  
   
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)
41          pVCAManipulator  = NULL;          KeyGroup = 0;
42          pVCFCManipulator = NULL;          SynthesisMode = 0; // set all mode bits to 0 first
43          pVCOManipulator  = NULL;          // select synthesis implementation (asm core is not supported ATM)
44          pLFO1  = NULL;          #if 0 // CONFIG_ASM && ARCH_X86
45          pLFO2  = NULL;          SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
46          pLFO3  = NULL;          #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;
59          if (pVCAManipulator)  delete pVCAManipulator;      }
         if (pVCFCManipulator) delete pVCFCManipulator;  
         if (pVCOManipulator)  delete pVCOManipulator;  
     }  
   
     void Voice::SetOutput(AudioOutputDevice* pAudioOutputDevice) {  
         this->pOutputLeft        = pAudioOutputDevice->Channel(0)->Buffer();  
         this->pOutputRight       = pAudioOutputDevice->Channel(1)->Buffer();  
         this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();  
         this->SampleRate         = pAudioOutputDevice->SampleRate();  
     }  
   
     void Voice::SetEngine(Engine* pEngine) {  
         this->pEngine = pEngine;  
   
         // delete old objects  
         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.  
60    
61          this->pDiskThread = pEngine->pDiskThread;      void Voice::SetEngine(LinuxSampler::Engine* pEngine) {
62          dmsg(1,("Voice::SetEngine()\n"));          Engine* engine = static_cast<Engine*>(pEngine);
63            this->pEngine     = engine;
64            this->pDiskThread = engine->pDiskThread;
65            dmsg(6,("Voice::SetEngine()\n"));
66      }      }
67    
68      /**      /**
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       *  @returns            0 on success, a value < 0 if something failed       *  @param pDimRgn        - points to the dimension region which provides sample wave(s) and articulation data
76         *  @param VoiceType      - type of this voice
77         *  @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 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          Active          = true;          if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging
89          MIDIKey         = pNoteOnEvent->Key;              dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
90          pRegion         = pInstrument->GetRegion(MIDIKey);          }
91          PlaybackState   = playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed          #endif // CONFIG_DEVMODE
92          Pos             = 0;  
93          Delay           = pNoteOnEvent->FragmentPos();          Type            = VoiceType;
94          pTriggerEvent   = pNoteOnEvent;          MIDIKey         = itNoteOnEvent->Param.Note.Key;
95            PlaybackState   = playback_state_init; // mark voice as triggered, but no audio rendered yet
96          if (!pRegion) {          Delay           = itNoteOnEvent->FragmentPos();
97              std::cerr << "Audio Thread: No Region defined for MIDI key " << MIDIKey << std::endl << std::flush;          itTriggerEvent  = itNoteOnEvent;
98              Kill();          itKillEvent     = Pool<Event>::Iterator();
99              return -1;          KeyGroup        = iKeyGroup;
100          }          pSample         = pDimRgn->pSample; // sample won't change until the voice is finished
101    
102          //TODO: current MIDI controller values are not taken into account yet          // calculate volume
103          ::gig::DimensionRegion* pDimRgn = NULL;          const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
104          for (int i = pRegion->Dimensions - 1; i >= 0; i--) { // Check if instrument has a velocity split  
105              if (pRegion->pDimensionDefinitions[i].dimension == ::gig::dimension_velocity) {          // For 16 bit samples, we downscale by 32768 to convert from
106                  uint DimValues[5] = {0,0,0,0,0};          // int16 value range to DSP value range (which is
107                      DimValues[i] = pNoteOnEvent->Velocity;          // -1.0..1.0). For 24 bit, we downscale from int32.
108                  pDimRgn = pRegion->GetDimensionRegionByValue(DimValues[4],DimValues[3],DimValues[2],DimValues[1],DimValues[0]);          float volume = velocityAttenuation / (pSample->BitDepth == 16 ? 32768.0f : 32768.0f * 65536.0f);
109    
110            volume *= pDimRgn->SampleAttenuation * pEngineChannel->GlobalVolume * GLOBAL_VOLUME;
111    
112            // the volume of release triggered samples depends on note length
113            if (Type == type_release_trigger) {
114                float noteLength = float(pEngine->FrameTime + Delay -
115                                         pEngineChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime) / pEngine->SampleRate;
116                float attenuation = 1 - 0.01053 * (256 >> pDimRgn->ReleaseTriggerDecay) * noteLength;
117                if (attenuation <= 0) return -1;
118                volume *= attenuation;
119            }
120    
121            // select channel mode (mono or stereo)
122            SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, pSample->Channels == 2);
123            // select bit depth (16 or 24)
124            SYNTHESIS_MODE_SET_BITDEPTH24(SynthesisMode, pSample->BitDepth == 24);
125    
126            // get starting crossfade volume level
127            float crossfadeVolume;
128            switch (pDimRgn->AttenuationController.type) {
129                case ::gig::attenuation_ctrl_t::type_channelaftertouch:
130                    crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[128])];
131                  break;                  break;
132              }              case ::gig::attenuation_ctrl_t::type_velocity:
133          }                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity)];
134          if (!pDimRgn) { // if there was no velocity split                  break;
135              pDimRgn = pRegion->GetDimensionRegionByValue(0,0,0,0,0);              case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate
136          }                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number])];
137                    break;
138                case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined
139                default:
140                    crossfadeVolume = 1.0f;
141            }
142    
143            VolumeLeft  = volume * Engine::PanCurve[64 - pDimRgn->Pan];
144            VolumeRight = volume * Engine::PanCurve[64 + pDimRgn->Pan];
145    
146            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          pSample = pDimRgn->pSample; // sample won't change until the voice is finished          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 - (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                  Kill();                  KillImmediately();
179                  return -1;                  return -1;
180              }              }
181              dmsg(4,("Disk voice launched (cached samples: %d, total Samples: %d, MaxRAMPos: %d, RAMLooping: %s)\n", cachedsamples, pSample->SamplesTotal, MaxRAMPos, (RAMLoop) ? "yes" : "no"));              dmsg(4,("Disk voice launched (cached samples: %d, total Samples: %d, MaxRAMPos: %d, RAMLooping: %s)\n", cachedsamples, pSample->SamplesTotal, MaxRAMPos, (RAMLoop) ? "yes" : "no"));
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;              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);  
             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 196  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 235  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 279  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,  
                           this->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 317  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,  
                           Delay);  
413          }          }
414      #endif // ENABLE_FILTER  
415    
416          // setup LFO 3 (VCO LFO)          // setup LFO 3 (VCO LFO)
417          {          {
# Line 354  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,  
                           this->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 422  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 450  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, SampleRate);              // calculate resonance
564              FilterRight.SetParameters(cutoff, resonance, 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  
   
         // ************************************************  
         // TODO: ARTICULATION DATA HANDLING IS MISSING HERE  
         // ************************************************  
573    
574          return 0; // success          return 0; // success
575      }      }
# Line 509  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);          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);  
     #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);  
   
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         Interpolate(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 559  namespace LinuxSampler { namespace gig { Line 620  namespace LinuxSampler { namespace gig {
620                          DiskStreamRef.pStream = pDiskThread->AskForCreatedStream(DiskStreamRef.OrderID);                          DiskStreamRef.pStream = pDiskThread->AskForCreatedStream(DiskStreamRef.OrderID);
621                          if (!DiskStreamRef.pStream) {                          if (!DiskStreamRef.pStream) {
622                              std::cout << stderr << "Disk stream not available in time!" << std::endl << std::flush;                              std::cout << stderr << "Disk stream not available in time!" << std::endl << std::flush;
623                              Kill();                              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() < (MaxSamplesPerCycle << MAX_PITCH) / pSample->Channels) {                      if (DiskStreamRef.State == Stream::state_end) {
635                          DiskStreamRef.pStream->WriteSilence((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                      Interpolate(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                  Kill(); // free voice                  std::cerr << "gig::Voice::Render(): entered with playback_state_end, this is a bug!\n" << std::flush;
663                  break;                  break;
664          }          }
665    
   
     #if ENABLE_FILTER  
         // Reset synthesis event lists (except VCO, as VCO events apply channel wide currently)  
         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 605  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          // dispatch control change events              if (itEvent->Type == Event::type_release) {
701          Event* pCCEvent = pEngine->pCCEvents->first();                  EG1.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
702          if (Delay) { // skip events that happened before this voice was triggered                  EG2.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
703              while (pCCEvent && pCCEvent->FragmentPos() <= Delay) pCCEvent = pEngine->pCCEvents->next();              } 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          while (pCCEvent) {      }
709              if (pCCEvent->Controller) { // if valid MIDI controller  
710                  #if ENABLE_FILTER      /**
711                  if (pCCEvent->Controller == VCFCutoffCtrl.controller) {       * Process given list of MIDI control change and pitch bend events for
712                      pEngine->pSynthesisEvents[Event::destination_vcfc]->alloc_assign(*pCCEvent);       * the given time.
713         *
714         * @param itEvent - iterator pointing to the next event to be processed
715         * @param End     - youngest time stamp where processing should be stopped
716         */
717        void Voice::processCCEvents(RTList<Event>::Iterator& itEvent, uint End) {
718            for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
719                if (itEvent->Type == Event::type_control_change &&
720                    itEvent->Param.CC.Controller) { // if (valid) MIDI control change event
721                    if (itEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {
722                        processCutoffEvent(itEvent);
723                    }
724                    if (itEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {
725                        processResonanceEvent(itEvent);
726                  }                  }
727                  if (pCCEvent->Controller == VCFResonanceCtrl.controller) {                  if (itEvent->Param.CC.Controller == pLFO1->ExtController) {
728                      pEngine->pSynthesisEvents[Event::destination_vcfr]->alloc_assign(*pCCEvent);                      pLFO1->update(itEvent->Param.CC.Value);
729                  }                  }
730                  #endif // ENABLE_FILTER                  if (itEvent->Param.CC.Controller == pLFO2->ExtController) {
731                  if (pCCEvent->Controller == pLFO1->ExtController) {                      pLFO2->update(itEvent->Param.CC.Value);
                     pLFO1->SendEvent(pCCEvent);  
732                  }                  }
733                  #if ENABLE_FILTER                  if (itEvent->Param.CC.Controller == pLFO3->ExtController) {
734                  if (pCCEvent->Controller == pLFO2->ExtController) {                      pLFO3->update(itEvent->Param.CC.Value);
                     pLFO2->SendEvent(pCCEvent);  
735                  }                  }
736                  #endif // ENABLE_FILTER                  if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&
737                  if (pCCEvent->Controller == pLFO3->ExtController) {                      itEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) {
738                      pLFO3->SendEvent(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;
             if (this->PitchBend != 1.0) {  
                 uint end = (pVCOEvent) ? pVCOEvent->FragmentPos() : Samples;  
                 for (uint i = Delay; i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vco][i] *= this->PitchBend;  
                 }  
             }  
             float pitch;  
             while (pVCOEvent) {  
                 Event* pNextVCOEvent = pVCOEventList->next();  
764    
765                  // calculate the influence length of this event (in sample points)          VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of fFinalCutoff next time
766                  uint end = (pNextVCOEvent) ? pNextVCOEvent->FragmentPos() : Samples;          fFinalCutoff = cutoff;
767        }
768    
769                  pitch = RTMath::CentsToFreqRatio(((double) pVCOEvent->Pitch / 8192.0) * 200.0); // +-two semitones = +-200 cents      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                  // apply pitch value to the pitch parameter sequence      /**
780                  for (uint i = pVCOEvent->FragmentPos(); i < end; i++) {       *  Synthesizes the current audio fragment for this voice.
781                      pEngine->pSynthesisParameters[Event::destination_vco][i] *= pitch;       *
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            }
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            uint i = Skip;
825            while (i < Samples) {
826                int iSubFragmentEnd = RTMath::Min(i + CONFIG_DEFAULT_SUBFRAGMENT_SIZE, Samples);
827    
828      #if ENABLE_FILTER              // initialize all final synthesis parameters
829          // process filter cutoff events              fFinalCutoff    = VCFCutoffCtrl.fvalue;
830          {              fFinalResonance = VCFResonanceCtrl.fvalue;
             RTEList<Event>* pCutoffEventList = pEngine->pSynthesisEvents[Event::destination_vcfc];  
             Event* pCutoffEvent = pCutoffEventList->first();  
             if (Delay) { // skip events that happened before this voice was triggered  
                 while (pCutoffEvent && pCutoffEvent->FragmentPos() <= Delay) pCutoffEvent = pCutoffEventList->next();  
             }  
             float cutoff;  
             while (pCutoffEvent) {  
                 Event* pNextCutoffEvent = pCutoffEventList->next();  
831    
832                  // calculate the influence length of this event (in sample points)              // process MIDI control change and pitchbend events for this subfragment
833                  uint end = (pNextCutoffEvent) ? pNextCutoffEvent->FragmentPos() : Samples;              processCCEvents(itCCEvent, iSubFragmentEnd);
834    
835                  cutoff = exp((float) pCutoffEvent->Value * 0.00787402f * FILTER_CUTOFF_COEFF) * FILTER_CUTOFF_MAX - FILTER_CUTOFF_MIN;              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 cutoff frequency to the cutoff parameter sequence              // process transition events (note on, note off & sustain pedal)
842                  for (uint i = pCutoffEvent->FragmentPos(); i < end; i++) {              processTransitionEvents(itNoteEvent, iSubFragmentEnd);
                     pEngine->pSynthesisParameters[Event::destination_vcfc][i] = cutoff;  
                 }  
843    
844                  pCutoffEvent = pNextCutoffEvent;              // 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 (pCutoffEventList->last()) VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of parameter matrix next time  
         }  
852    
853          // process filter resonance events              // process envelope generators
854          {              switch (EG1.getSegmentType()) {
855              RTEList<Event>* pResonanceEventList = pEngine->pSynthesisEvents[Event::destination_vcfr];                  case EGADSR::segment_lin:
856              Event* pResonanceEvent = pResonanceEventList->first();                      fFinalVolume *= EG1.processLin();
857              if (Delay) { // skip events that happened before this voice was triggered                      break;
858                  while (pResonanceEvent && pResonanceEvent->FragmentPos() <= Delay) pResonanceEvent = pResonanceEventList->next();                  case EGADSR::segment_exp:
859                        fFinalVolume *= EG1.processExp();
860                        break;
861                    case EGADSR::segment_end:
862                        fFinalVolume *= EG1.getLevel();
863                        break; // noop
864                }
865                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              while (pResonanceEvent) {              if (EG3.active()) finalSynthesisParameters.fFinalPitch *= EG3.render();
                 Event* pNextResonanceEvent = pResonanceEventList->next();  
877    
878                  // calculate the influence length of this event (in sample points)              // process low frequency oscillators
879                  uint end = (pNextResonanceEvent) ? pNextResonanceEvent->FragmentPos() : Samples;              if (bLFO1Enabled) fFinalVolume *= (1.0f - pLFO1->render());
880                if (bLFO2Enabled) fFinalCutoff *= pLFO2->render();
881                if (bLFO3Enabled) finalSynthesisParameters.fFinalPitch *= RTMath::CentsToFreqRatio(pLFO3->render());
882    
883                  // convert absolute controller value to differential              // limit the pitch so we don't read outside the buffer
884                  int ctrldelta = pResonanceEvent->Value - VCFResonanceCtrl.value;              finalSynthesisParameters.fFinalPitch = RTMath::Min(finalSynthesisParameters.fFinalPitch, float(1 << CONFIG_MAX_PITCH));
                 VCFResonanceCtrl.value = pResonanceEvent->Value;  
885    
886                  float resonancedelta = (float) ctrldelta * 0.00787f; // 0.0..1.0              // 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                }
891    
892                // do we need resampling?
893                const float __PLUS_ONE_CENT  = 1.000577789506554859250142541782224725466f;
894                const float __MINUS_ONE_CENT = 0.9994225441413807496009516495583113737666f;
895                const bool bResamplingRequired = !(finalSynthesisParameters.fFinalPitch <= __PLUS_ONE_CENT &&
896                                                   finalSynthesisParameters.fFinalPitch >= __MINUS_ONE_CENT);
897                SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, bResamplingRequired);
898    
899                // prepare final synthesis parameters structure
900                finalSynthesisParameters.uiToGo            = iSubFragmentEnd - i;
901    #ifdef CONFIG_INTERPOLATE_VOLUME
902                finalSynthesisParameters.fFinalVolumeDeltaLeft  =
903                    (fFinalVolume * VolumeLeft  * PanLeftSmoother.render() -
904                     finalSynthesisParameters.fFinalVolumeLeft) / finalSynthesisParameters.uiToGo;
905                finalSynthesisParameters.fFinalVolumeDeltaRight =
906                    (fFinalVolume * VolumeRight * PanRightSmoother.render() -
907                     finalSynthesisParameters.fFinalVolumeRight) / finalSynthesisParameters.uiToGo;
908    #else
909                finalSynthesisParameters.fFinalVolumeLeft  =
910                    fFinalVolume * VolumeLeft  * PanLeftSmoother.render();
911                finalSynthesisParameters.fFinalVolumeRight =
912                    fFinalVolume * VolumeRight * PanRightSmoother.render();
913    #endif
914                // render audio for one subfragment
915                RunSynthesisFunction(SynthesisMode, &finalSynthesisParameters, &loop);
916    
917                // stop the rendering if volume EG is finished
918                if (EG1.getSegmentType() == EGADSR::segment_end) break;
919    
920                  // apply cutoff frequency to the cutoff parameter sequence              const double newPos = Pos + (iSubFragmentEnd - i) * finalSynthesisParameters.fFinalPitch;
921                  for (uint i = pResonanceEvent->FragmentPos(); i < end; i++) {  
922                      pEngine->pSynthesisParameters[Event::destination_vcfr][i] += resonancedelta;              // increment envelopes' positions
923                if (EG1.active()) {
924    
925                    // 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 (pDimRgn->SampleLoops && Pos <= pDimRgn->pSampleLoops[0].LoopStart && pDimRgn->pSampleLoops[0].LoopStart < newPos) {
927                        EG1.update(EGADSR::event_hold_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
928                  }                  }
929    
930                  pResonanceEvent = pNextResonanceEvent;                  EG1.increment(1);
931                    if (!EG1.toStageEndLeft()) EG1.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
932              }              }
933              if (pResonanceEventList->last()) VCFResonanceCtrl.fvalue = pResonanceEventList->last()->Value * 0.00787f; // needed for initialization of parameter matrix next time              if (EG2.active()) {
934                    EG2.increment(1);
935                    if (!EG2.toStageEndLeft()) EG2.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
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          }          }
     #endif // ENABLE_FILTER  
943      }      }
944    
945      /**      /** @brief Update current portamento position.
      *  Interpolates the input audio data (no loop).  
946       *       *
947       *  @param Samples - number of sample points to be rendered in this audio       * Will be called when portamento mode is enabled to get the final
948       *                   fragment cycle       * portamento position of this active voice from where the next voice(s)
949       *  @param pSrc    - pointer to input sample data       * might continue to slide on.
950       *  @param Skip    - number of sample points to skip in output buffer       *
951         * @param itNoteOffEvent - event which causes this voice to die soon
952       */       */
953      void Voice::Interpolate(uint Samples, sample_t* pSrc, uint Skip) {      void Voice::UpdatePortamentoPos(Pool<Event>::Iterator& itNoteOffEvent) {
954          int i = Skip;          const float fFinalEG3Level = EG3.level(itNoteOffEvent->FragmentPos());
955            pEngineChannel->PortamentoPos = (float) MIDIKey + RTMath::FreqRatioToCents(fFinalEG3Level) * 0.01f;
         // FIXME: assuming either mono or stereo  
         if (this->pSample->Channels == 2) { // Stereo Sample  
             while (i < Samples) {  
                 InterpolateOneStep_Stereo(pSrc, i,  
                                           pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                           pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                           pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                           pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
             }  
         }  
         else { // Mono Sample  
             while (i < Samples) {  
                 InterpolateOneStep_Mono(pSrc, i,  
                                         pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                         pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                         pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                         pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
             }  
         }  
956      }      }
957    
958      /**      /**
959       *  Interpolates the input audio data, this method honors looping.       *  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
961         *  fading down the volume level to avoid clicks and regular processing
962         *  until the kill event actually occured!
963       *       *
964       *  @param Samples - number of sample points to be rendered in this audio       * If it's necessary to know when the voice's disk stream was actually
965       *                   fragment cycle       * deleted, then one can set the optional @a bRequestNotification
966       *  @param pSrc    - pointer to input sample data       * parameter and this method will then return the handle of the disk
967       *  @param Skip    - number of sample points to skip in output buffer       * 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::InterpolateAndLoop(uint Samples, sample_t* pSrc, uint Skip) {      Stream::Handle Voice::KillImmediately(bool bRequestNotification) {
981          int i = Skip;          Stream::Handle hStream = Stream::INVALID_HANDLE;
982            if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
983          // FIXME: assuming either mono or stereo              pDiskThread->OrderDeletionOfStream(&DiskStreamRef, bRequestNotification);
984          if (pSample->Channels == 2) { // Stereo Sample              hStream = DiskStreamRef.hStream;
             if (pSample->LoopPlayCount) {  
                 // render loop (loop count limited)  
                 while (i < Samples && LoopCyclesLeft) {  
                     InterpolateOneStep_Stereo(pSrc, i,  
                                               pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                         LoopCyclesLeft--;  
                     }  
                 }  
                 // render on without loop  
                 while (i < Samples) {  
                     InterpolateOneStep_Stereo(pSrc, i,  
                                               pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
                 }  
             }  
             else { // render loop (endless loop)  
                 while (i < Samples) {  
                     InterpolateOneStep_Stereo(pSrc, i,  
                                               pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                               pEngine->pSynthesisParameters[Event::destination_vcfr][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) {  
                     InterpolateOneStep_Mono(pSrc, i,  
                                             pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                         LoopCyclesLeft--;  
                     }  
                 }  
                 // render on without loop  
                 while (i < Samples) {  
                     InterpolateOneStep_Mono(pSrc, i,  
                                             pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
                 }  
             }  
             else { // render loop (endless loop)  
                 while (i < Samples) {  
                     InterpolateOneStep_Mono(pSrc, i,  
                                             pEngine->pSynthesisParameters[Event::destination_vca][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vco][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfc][i],  
                                             pEngine->pSynthesisParameters[Event::destination_vcfr][i]);  
                     if (Pos > pSample->LoopEnd) {  
                         Pos = pSample->LoopStart + fmod(Pos - pSample->LoopEnd, pSample->LoopSize);;  
                     }  
                 }  
             }  
985          }          }
986            Reset();
987            return hStream;
988      }      }
989    
990      /**      /**
991       *  Immediately kill the voice.       *  Kill the voice in regular sense. Let the voice render audio until
992         *  the kill event actually occured and then fade down the volume level
993         *  very quickly and let the voice die finally. Unlike a normal release
994         *  of a voice, a kill process cannot be cancalled and is therefore
995         *  usually used for voice stealing and key group conflicts.
996         *
997         *  @param itKillEvent - event which caused the voice to be killed
998       */       */
999      void Voice::Kill() {      void Voice::Kill(Pool<Event>::Iterator& itKillEvent) {
1000          if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {          #if CONFIG_DEVMODE
1001              pDiskThread->OrderDeletionOfStream(&DiskStreamRef);          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          Reset();          #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.53  
changed lines
  Added in v.2012

  ViewVC Help
Powered by ViewVC