/[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 614 by persson, Mon Jun 6 16:54:20 2005 UTC revision 2012 by iliev, Fri Oct 23 17:53:17 2009 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 Christian Schoenebeck                              *   *   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 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
 #include "EGADSR.h"  
 #include "Manipulator.h"  
24  #include "../../common/Features.h"  #include "../../common/Features.h"
25  #include "Synthesizer.h"  #include "Synthesizer.h"
26    #include "Profiler.h"
27    #include "Engine.h"
28    #include "EngineChannel.h"
29    
30  #include "Voice.h"  #include "Voice.h"
31    
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
     const float Voice::FILTER_CUTOFF_COEFF(CalculateFilterCutoffCoeff());  
   
     const int Voice::FILTER_UPDATE_MASK(CalculateFilterUpdateMask());  
   
     float Voice::CalculateFilterCutoffCoeff() {  
         return log(CONFIG_FILTER_CUTOFF_MIN / CONFIG_FILTER_CUTOFF_MAX);  
     }  
   
     int Voice::CalculateFilterUpdateMask() {  
         if (CONFIG_FILTER_UPDATE_STEPS <= 0) return 0;  
         int power_of_two;  
         for (power_of_two = 0; 1<<power_of_two < CONFIG_FILTER_UPDATE_STEPS; power_of_two++);  
         return (1 << power_of_two) - 1;  
     }  
   
34      Voice::Voice() {      Voice::Voice() {
35          pEngine     = NULL;          pEngine     = NULL;
36          pDiskThread = NULL;          pDiskThread = NULL;
37          PlaybackState = playback_state_end;          PlaybackState = playback_state_end;
38          pEG1   = NULL;          pLFO1 = new LFOUnsigned(1.0f);  // amplitude EG (0..1 range)
39          pEG2   = NULL;          pLFO2 = new LFOUnsigned(1.0f);  // filter EG (0..1 range)
40          pEG3   = NULL;          pLFO3 = new LFOSigned(1200.0f); // pitch EG (-1200..+1200 range)
         pVCAManipulator  = NULL;  
         pVCFCManipulator = NULL;  
         pVCOManipulator  = NULL;  
         pLFO1  = NULL;  
         pLFO2  = NULL;  
         pLFO3  = NULL;  
41          KeyGroup = 0;          KeyGroup = 0;
42          SynthesisMode = 0; // set all mode bits to 0 first          SynthesisMode = 0; // set all mode bits to 0 first
43          // select synthesis implementation (currently either pure C++ or MMX+SSE(1))          // select synthesis implementation (asm core is not supported ATM)
44          #if ARCH_X86          #if 0 // CONFIG_ASM && ARCH_X86
45          SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());          SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
46          #else          #else
47          SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);          SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);
48          #endif          #endif
49          SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, true);          SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, Profiler::isEnabled());
50    
51          FilterLeft.Reset();          finalSynthesisParameters.filterLeft.Reset();
52          FilterRight.Reset();          finalSynthesisParameters.filterRight.Reset();
53      }      }
54    
55      Voice::~Voice() {      Voice::~Voice() {
         if (pEG1)  delete pEG1;  
         if (pEG2)  delete pEG2;  
         if (pEG3)  delete pEG3;  
56          if (pLFO1) delete pLFO1;          if (pLFO1) delete pLFO1;
57          if (pLFO2) delete pLFO2;          if (pLFO2) delete pLFO2;
58          if (pLFO3) delete pLFO3;          if (pLFO3) delete pLFO3;
         if (pVCAManipulator)  delete pVCAManipulator;  
         if (pVCFCManipulator) delete pVCFCManipulator;  
         if (pVCOManipulator)  delete pVCOManipulator;  
59      }      }
60    
61      void Voice::SetEngine(Engine* pEngine) {      void Voice::SetEngine(LinuxSampler::Engine* pEngine) {
62          this->pEngine = pEngine;          Engine* engine = static_cast<Engine*>(pEngine);
63            this->pEngine     = engine;
64          // delete old objects          this->pDiskThread = engine->pDiskThread;
         if (pEG1) delete pEG1;  
         if (pEG2) delete pEG2;  
         if (pEG3) delete pEG3;  
         if (pVCAManipulator)  delete pVCAManipulator;  
         if (pVCFCManipulator) delete pVCFCManipulator;  
         if (pVCOManipulator)  delete pVCOManipulator;  
         if (pLFO1) delete pLFO1;  
         if (pLFO2) delete pLFO2;  
         if (pLFO3) delete pLFO3;  
   
         // create new ones  
         pEG1   = new EGADSR(pEngine, Event::destination_vca);  
         pEG2   = new EGADSR(pEngine, Event::destination_vcfc);  
         pEG3   = new EGDecay(pEngine, Event::destination_vco);  
         pVCAManipulator  = new VCAManipulator(pEngine);  
         pVCFCManipulator = new VCFCManipulator(pEngine);  
         pVCOManipulator  = new VCOManipulator(pEngine);  
         pLFO1  = new LFO<gig::VCAManipulator>(0.0f, 1.0f, LFO<VCAManipulator>::propagation_top_down, pVCAManipulator, pEngine->pEventPool);  
         pLFO2  = new LFO<gig::VCFCManipulator>(0.0f, 1.0f, LFO<VCFCManipulator>::propagation_top_down, pVCFCManipulator, pEngine->pEventPool);  
         pLFO3  = new LFO<gig::VCOManipulator>(-1200.0f, 1200.0f, LFO<VCOManipulator>::propagation_middle_balanced, pVCOManipulator, pEngine->pEventPool); // +-1 octave (+-1200 cents) max.  
   
         this->pDiskThread = pEngine->pDiskThread;  
65          dmsg(6,("Voice::SetEngine()\n"));          dmsg(6,("Voice::SetEngine()\n"));
66      }      }
67    
# Line 117  namespace LinuxSampler { namespace gig { Line 69  namespace LinuxSampler { namespace gig {
69       *  Initializes and triggers the voice, a disk stream will be launched if       *  Initializes and triggers the voice, a disk stream will be launched if
70       *  needed.       *  needed.
71       *       *
72       *  @param pEngineChannel       - engine channel on which this voice was ordered       *  @param pEngineChannel - engine channel on which this voice was ordered
73       *  @param itNoteOnEvent        - event that caused triggering of this voice       *  @param itNoteOnEvent  - event that caused triggering of this voice
74       *  @param PitchBend            - MIDI detune factor (-8192 ... +8191)       *  @param PitchBend      - MIDI detune factor (-8192 ... +8191)
75       *  @param pInstrument          - points to the loaded instrument which provides sample wave(s) and articulation data       *  @param pDimRgn        - points to the dimension region which provides sample wave(s) and articulation data
76       *  @param iLayer               - layer number this voice refers to (only if this is a layered sound of course)       *  @param VoiceType      - type of this voice
77       *  @param ReleaseTriggerVoice  - if this new voice is a release trigger voice (optional, default = false)       *  @param iKeyGroup      - a value > 0 defines a key group in which this voice is member of
      *  @param VoiceStealingAllowed - wether the voice is allowed to steal voices for further subvoices  
78       *  @returns 0 on success, a value < 0 if the voice wasn't triggered       *  @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       *           (either due to an error or e.g. because no region is
80       *           defined for the given key)       *           defined for the given key)
81       */       */
82      int Voice::Trigger(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int PitchBend, ::gig::Instrument* pInstrument, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealingAllowed) {      int Voice::Trigger(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int PitchBend, ::gig::DimensionRegion* pDimRgn, type_t VoiceType, int iKeyGroup) {
83          this->pEngineChannel = pEngineChannel;          this->pEngineChannel = pEngineChannel;
84          if (!pInstrument) {          this->pDimRgn        = pDimRgn;
85             dmsg(1,("voice::trigger: !pInstrument\n"));          Orphan = false;
86             exit(EXIT_FAILURE);  
         }  
87          #if CONFIG_DEVMODE          #if CONFIG_DEVMODE
88          if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging          if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging
89              dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));              dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
90          }          }
91          #endif // CONFIG_DEVMODE          #endif // CONFIG_DEVMODE
92    
93          Type            = type_normal;          Type            = VoiceType;
94          MIDIKey         = itNoteOnEvent->Param.Note.Key;          MIDIKey         = itNoteOnEvent->Param.Note.Key;
         pRegion         = pInstrument->GetRegion(MIDIKey);  
95          PlaybackState   = playback_state_init; // mark voice as triggered, but no audio rendered yet          PlaybackState   = playback_state_init; // mark voice as triggered, but no audio rendered yet
96          Delay           = itNoteOnEvent->FragmentPos();          Delay           = itNoteOnEvent->FragmentPos();
97          itTriggerEvent  = itNoteOnEvent;          itTriggerEvent  = itNoteOnEvent;
98          itKillEvent     = Pool<Event>::Iterator();          itKillEvent     = Pool<Event>::Iterator();
99            KeyGroup        = iKeyGroup;
100            pSample         = pDimRgn->pSample; // sample won't change until the voice is finished
101    
102          if (!pRegion) {          // calculate volume
103              dmsg(4, ("gig::Voice: No Region defined for MIDI key %d\n", MIDIKey));          const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
             return -1;  
         }  
   
         // only mark the first voice of a layered voice (group) to be in a  
         // key group, so the layered voices won't kill each other  
         KeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;  
104    
105          // get current dimension values to select the right dimension region          // For 16 bit samples, we downscale by 32768 to convert from
106          //FIXME: controller values for selecting the dimension region here are currently not sample accurate          // int16 value range to DSP value range (which is
107          uint DimValues[8] = { 0 };          // -1.0..1.0). For 24 bit, we downscale from int32.
108          for (int i = pRegion->Dimensions - 1; i >= 0; i--) {          float volume = velocityAttenuation / (pSample->BitDepth == 16 ? 32768.0f : 32768.0f * 65536.0f);
109              switch (pRegion->pDimensionDefinitions[i].dimension) {  
110                  case ::gig::dimension_samplechannel:          volume *= pDimRgn->SampleAttenuation * pEngineChannel->GlobalVolume * GLOBAL_VOLUME;
111                      DimValues[i] = 0; //TODO: we currently ignore this dimension  
112                      break;          // the volume of release triggered samples depends on note length
113                  case ::gig::dimension_layer:          if (Type == type_release_trigger) {
114                      DimValues[i] = iLayer;              float noteLength = float(pEngine->FrameTime + Delay -
115                      break;                                       pEngineChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime) / pEngine->SampleRate;
116                  case ::gig::dimension_velocity:              float attenuation = 1 - 0.01053 * (256 >> pDimRgn->ReleaseTriggerDecay) * noteLength;
117                      DimValues[i] = itNoteOnEvent->Param.Note.Velocity;              if (attenuation <= 0) return -1;
118                      break;              volume *= attenuation;
                 case ::gig::dimension_channelaftertouch:  
                     DimValues[i] = 0; //TODO: we currently ignore this dimension  
                     break;  
                 case ::gig::dimension_releasetrigger:  
                     Type = (ReleaseTriggerVoice) ? type_release_trigger : (!iLayer) ? type_release_trigger_required : type_normal;  
                     DimValues[i] = (uint) ReleaseTriggerVoice;  
                     break;  
                 case ::gig::dimension_keyboard:  
                     DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;  
                     break;  
                 case ::gig::dimension_roundrobin:  
                     DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on  
                     break;  
                 case ::gig::dimension_random:  
                     pEngine->RandomSeed = pEngine->RandomSeed * 1103515245 + 12345; // classic pseudo random number generator  
                     DimValues[i] = (uint) pEngine->RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random  
                     break;  
                 case ::gig::dimension_modwheel:  
                     DimValues[i] = pEngineChannel->ControllerTable[1];  
                     break;  
                 case ::gig::dimension_breath:  
                     DimValues[i] = pEngineChannel->ControllerTable[2];  
                     break;  
                 case ::gig::dimension_foot:  
                     DimValues[i] = pEngineChannel->ControllerTable[4];  
                     break;  
                 case ::gig::dimension_portamentotime:  
                     DimValues[i] = pEngineChannel->ControllerTable[5];  
                     break;  
                 case ::gig::dimension_effect1:  
                     DimValues[i] = pEngineChannel->ControllerTable[12];  
                     break;  
                 case ::gig::dimension_effect2:  
                     DimValues[i] = pEngineChannel->ControllerTable[13];  
                     break;  
                 case ::gig::dimension_genpurpose1:  
                     DimValues[i] = pEngineChannel->ControllerTable[16];  
                     break;  
                 case ::gig::dimension_genpurpose2:  
                     DimValues[i] = pEngineChannel->ControllerTable[17];  
                     break;  
                 case ::gig::dimension_genpurpose3:  
                     DimValues[i] = pEngineChannel->ControllerTable[18];  
                     break;  
                 case ::gig::dimension_genpurpose4:  
                     DimValues[i] = pEngineChannel->ControllerTable[19];  
                     break;  
                 case ::gig::dimension_sustainpedal:  
                     DimValues[i] = pEngineChannel->ControllerTable[64];  
                     break;  
                 case ::gig::dimension_portamento:  
                     DimValues[i] = pEngineChannel->ControllerTable[65];  
                     break;  
                 case ::gig::dimension_sostenutopedal:  
                     DimValues[i] = pEngineChannel->ControllerTable[66];  
                     break;  
                 case ::gig::dimension_softpedal:  
                     DimValues[i] = pEngineChannel->ControllerTable[67];  
                     break;  
                 case ::gig::dimension_genpurpose5:  
                     DimValues[i] = pEngineChannel->ControllerTable[80];  
                     break;  
                 case ::gig::dimension_genpurpose6:  
                     DimValues[i] = pEngineChannel->ControllerTable[81];  
                     break;  
                 case ::gig::dimension_genpurpose7:  
                     DimValues[i] = pEngineChannel->ControllerTable[82];  
                     break;  
                 case ::gig::dimension_genpurpose8:  
                     DimValues[i] = pEngineChannel->ControllerTable[83];  
                     break;  
                 case ::gig::dimension_effect1depth:  
                     DimValues[i] = pEngineChannel->ControllerTable[91];  
                     break;  
                 case ::gig::dimension_effect2depth:  
                     DimValues[i] = pEngineChannel->ControllerTable[92];  
                     break;  
                 case ::gig::dimension_effect3depth:  
                     DimValues[i] = pEngineChannel->ControllerTable[93];  
                     break;  
                 case ::gig::dimension_effect4depth:  
                     DimValues[i] = pEngineChannel->ControllerTable[94];  
                     break;  
                 case ::gig::dimension_effect5depth:  
                     DimValues[i] = pEngineChannel->ControllerTable[95];  
                     break;  
                 case ::gig::dimension_none:  
                     std::cerr << "gig::Voice::Trigger() Error: dimension=none\n" << std::flush;  
                     break;  
                 default:  
                     std::cerr << "gig::Voice::Trigger() Error: Unknown dimension\n" << std::flush;  
             }  
119          }          }
         pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);  
   
         pSample = pDimRgn->pSample; // sample won't change until the voice is finished  
         if (!pSample || !pSample->SamplesTotal) return -1; // no need to continue if sample is silent  
120    
121          // select channel mode (mono or stereo)          // select channel mode (mono or stereo)
122          SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, pSample->Channels == 2);          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          // get starting crossfade volume level
127            float crossfadeVolume;
128          switch (pDimRgn->AttenuationController.type) {          switch (pDimRgn->AttenuationController.type) {
129              case ::gig::attenuation_ctrl_t::type_channelaftertouch:              case ::gig::attenuation_ctrl_t::type_channelaftertouch:
130                  CrossfadeVolume = 1.0f; //TODO: aftertouch not supported yet                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[128])];
131                  break;                  break;
132              case ::gig::attenuation_ctrl_t::type_velocity:              case ::gig::attenuation_ctrl_t::type_velocity:
133                  CrossfadeVolume = CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity);                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity)];
134                  break;                  break;
135              case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate              case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate
136                  CrossfadeVolume = CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number]);                  crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number])];
137                  break;                  break;
138              case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined              case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined
139              default:              default:
140                  CrossfadeVolume = 1.0f;                  crossfadeVolume = 1.0f;
141          }          }
142    
143          PanLeft  = 1.0f - float(RTMath::Max(pDimRgn->Pan, 0)) /  63.0f;          VolumeLeft  = volume * Engine::PanCurve[64 - pDimRgn->Pan];
144          PanRight = 1.0f - float(RTMath::Min(pDimRgn->Pan, 0)) / -64.0f;          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          Pos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)          finalSynthesisParameters.dPos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)
153            Pos = pDimRgn->SampleStartOffset;
154    
155          // Check if the sample needs disk streaming or is too short for that          // Check if the sample needs disk streaming or is too short for that
156          long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;          long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;
157          DiskVoice          = cachedsamples < pSample->SamplesTotal;          DiskVoice          = cachedsamples < pSample->SamplesTotal;
158    
159            const DLS::sample_loop_t& loopinfo = pDimRgn->pSampleLoops[0];
160    
161          if (DiskVoice) { // voice to be streamed from disk          if (DiskVoice) { // voice to be streamed from disk
162              MaxRAMPos = cachedsamples - (pEngine->MaxSamplesPerCycle << 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)              if (cachedsamples > (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH)) {
163                    MaxRAMPos = cachedsamples - (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH) / pSample->Channels; //TODO: this calculation is too pessimistic and may better be moved to Render() method, so it calculates MaxRAMPos dependent to the current demand of sample points to be rendered (e.g. in case of JACK)
164                } else {
165                    // The cache is too small to fit a max sample buffer.
166                    // Setting MaxRAMPos to 0 will probably cause a click
167                    // in the audio, but it's better than not handling
168                    // this case at all, which would have caused the
169                    // unsigned MaxRAMPos to be set to a negative number.
170                    MaxRAMPos = 0;
171                }
172    
173              // check if there's a loop defined which completely fits into the cached (RAM) part of the sample              // check if there's a loop defined which completely fits into the cached (RAM) part of the sample
174              if (pSample->Loops && pSample->LoopEnd <= MaxRAMPos) {              RAMLoop = (pDimRgn->SampleLoops && (loopinfo.LoopStart + loopinfo.LoopLength) <= MaxRAMPos);
                 RAMLoop        = true;  
                 LoopCyclesLeft = pSample->LoopPlayCount;  
             }  
             else RAMLoop = false;  
175    
176              if (pDiskThread->OrderNewStream(&DiskStreamRef, pSample, MaxRAMPos, !RAMLoop) < 0) {              if (pDiskThread->OrderNewStream(&DiskStreamRef, pDimRgn, MaxRAMPos, !RAMLoop) < 0) {
177                  dmsg(1,("Disk stream order failed!\n"));                  dmsg(1,("Disk stream order failed!\n"));
178                  KillImmediately();                  KillImmediately();
179                  return -1;                  return -1;
# Line 316  namespace LinuxSampler { namespace gig { Line 182  namespace LinuxSampler { namespace gig {
182          }          }
183          else { // RAM only voice          else { // RAM only voice
184              MaxRAMPos = cachedsamples;              MaxRAMPos = cachedsamples;
185              if (pSample->Loops) {              RAMLoop = (pDimRgn->SampleLoops != 0);
                 RAMLoop        = true;  
                 LoopCyclesLeft = pSample->LoopPlayCount;  
             }  
             else RAMLoop = false;  
186              dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));              dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));
187          }          }
188            if (RAMLoop) {
189                loop.uiTotalCycles = pSample->LoopPlayCount;
190                loop.uiCyclesLeft  = pSample->LoopPlayCount;
191                loop.uiStart       = loopinfo.LoopStart;
192                loop.uiEnd         = loopinfo.LoopStart + loopinfo.LoopLength;
193                loop.uiSize        = loopinfo.LoopLength;
194            }
195    
196          // calculate initial pitch value          // calculate initial pitch value
197          {          {
198              double pitchbasecents = pDimRgn->FineTune + (int) pEngine->ScaleTuning[MIDIKey % 12];              double pitchbasecents = pEngineChannel->pInstrument->FineTune + pDimRgn->FineTune + pEngine->ScaleTuning[MIDIKey % 12];
             if (pDimRgn->PitchTrack) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;  
             this->PitchBase = RTMath::CentsToFreqRatio(pitchbasecents) * (double(pSample->SamplesPerSecond) / double(pEngine->pAudioOutputDevice->SampleRate()));  
             this->PitchBend = RTMath::CentsToFreqRatio(((double) PitchBend / 8192.0) * 200.0); // pitchbend wheel +-2 semitones = 200 cents  
         }  
199    
200          const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);              // GSt behaviour: maximum transpose up is 40 semitones. If
201                // MIDI key is more than 40 semitones above unity note,
202          Volume = velocityAttenuation / 32768.0f; // we downscale by 32768 to convert from int16 value range to DSP value range (which is -1.0..1.0)              // the transpose is not done.
203                if (pDimRgn->PitchTrack && (MIDIKey - (int) pDimRgn->UnityNote) < 40) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;
204          Volume *= pDimRgn->SampleAttenuation;  
205                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          // the length of the decay and release curves are dependent on the velocity
211          const double velrelease = 1 / pDimRgn->GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);          const double velrelease = 1 / pDimRgn->GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);
# Line 351  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 = itNoteOnEvent->Param.Note.Velocity;                      eg1controllervalue = itNoteOnEvent->Param.Note.Velocity;
# Line 362  namespace LinuxSampler { namespace gig { Line 230  namespace LinuxSampler { namespace gig {
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) * velrelease,                          pDimRgn->EG1Attack * eg1attack,
243                            (pDimRgn->EG1Decay2 + eg1decay) * velrelease,                          pDimRgn->EG1Hold,
244                            pDimRgn->EG1InfiniteSustain,                          pDimRgn->EG1Decay1 * eg1decay * velrelease,
245                            pDimRgn->EG1Sustain,                          pDimRgn->EG1Decay2 * eg1decay * velrelease,
246                            (pDimRgn->EG1Release + eg1release) * velrelease,                          pDimRgn->EG1InfiniteSustain,
247                            // the SSE synthesis implementation requires                          pDimRgn->EG1Sustain,
248                            // the vca start to be 16 byte aligned                          pDimRgn->EG1Release * eg1release * velrelease,
249                            SYNTHESIS_MODE_GET_IMPLEMENTATION(SynthesisMode) ?                          velocityAttenuation,
250                            Delay & 0xfffffffc : Delay,                          pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
251                            velocityAttenuation);          }
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    
271          // setup EG 2 (VCF Cutoff EG)          // setup EG 2 (VCF Cutoff EG)
272          {          {
# Line 393  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 = itNoteOnEvent->Param.Note.Velocity;                      eg2controllervalue = itNoteOnEvent->Param.Note.Velocity;
# Line 404  namespace LinuxSampler { namespace gig { Line 288  namespace LinuxSampler { namespace gig {
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) * velrelease,                          pDimRgn->EG2Decay2 * eg2decay * velrelease,
301                            (pDimRgn->EG2Decay2 + eg2decay) * velrelease,                          pDimRgn->EG2InfiniteSustain,
302                            pDimRgn->EG2InfiniteSustain,                          pDimRgn->EG2Sustain,
303                            pDimRgn->EG2Sustain,                          pDimRgn->EG2Release * eg2release * velrelease,
304                            (pDimRgn->EG2Release + eg2release) * velrelease,                          velocityAttenuation,
305                            Delay,                          pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
                           velocityAttenuation);  
306          }          }
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 437  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,  
                           pEngineChannel->ControllerTable[pLFO1->ExtController],  
                           pDimRgn->LFO1FlipPhase,  
                           pEngine->SampleRate,  
                           Delay);  
367          }          }
368    
369    
# Line 475  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,  
                           pEngineChannel->ControllerTable[pLFO2->ExtController],  
                           pDimRgn->LFO2FlipPhase,  
                           pEngine->SampleRate,  
                           Delay);  
413          }          }
414    
415    
# Line 513  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,  
                           pEngineChannel->ControllerTable[pLFO3->ExtController],  
                           false,  
                           pEngine->SampleRate,  
                           Delay);  
459          }          }
460    
461    
# Line 582  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;
# Line 613  namespace LinuxSampler { namespace gig { Line 530  namespace LinuxSampler { namespace gig {
530              #endif // CONFIG_OVERRIDE_RESONANCE_CTRL              #endif // CONFIG_OVERRIDE_RESONANCE_CTRL
531    
532              #ifndef CONFIG_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(CONFIG_OVERRIDE_FILTER_TYPE);              finalSynthesisParameters.filterLeft.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
537              FilterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);              finalSynthesisParameters.filterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
538              #endif // CONFIG_OVERRIDE_FILTER_TYPE              #endif // CONFIG_OVERRIDE_FILTER_TYPE
539    
540              VCFCutoffCtrl.value    = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];              VCFCutoffCtrl.value    = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
541              VCFResonanceCtrl.value = pEngineChannel->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 - itNoteOnEvent->Param.Note.Velocity) * (float) pDimRgn->VCFVelocityScale * 6.2E-5f * FILTER_CUTOFF_COEFF) * CONFIG_FILTER_CUTOFF_MAX  
                 : exp((float) VCFCutoffCtrl.value * 0.00787402f * FILTER_CUTOFF_COEFF) * CONFIG_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) (itNoteOnEvent->Param.Note.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 - CONFIG_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                // calculate resonance
564                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;
# Line 662  namespace LinuxSampler { namespace gig { Line 588  namespace LinuxSampler { namespace gig {
588      void Voice::Render(uint Samples) {      void Voice::Render(uint Samples) {
589    
590          // select default values for synthesis mode bits          // select default values for synthesis mode bits
         SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, (PitchBase * PitchBend) != 1.0f);  
         SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, true);  
591          SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);          SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);
592    
         // Reset the synthesis parameter matrix  
   
         pEngine->ResetSynthesisParameters(Event::destination_vca, this->Volume * this->CrossfadeVolume * pEngineChannel->GlobalVolume);  
         pEngine->ResetSynthesisParameters(Event::destination_vco, this->PitchBase);  
         pEngine->ResetSynthesisParameters(Event::destination_vcfc, VCFCutoffCtrl.fvalue);  
         pEngine->ResetSynthesisParameters(Event::destination_vcfr, VCFResonanceCtrl.fvalue);  
   
         // 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, pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents, itTriggerEvent, this->Pos, this->PitchBase * this->PitchBend, itKillEvent);  
         pEG2->Process(Samples, pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents, itTriggerEvent, this->Pos, this->PitchBase * this->PitchBend);  
         if (pEG3->Process(Samples)) { // if pitch EG is active  
             SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);  
             SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);  
         }  
         pLFO1->Process(Samples);  
         pLFO2->Process(Samples);  
         if (pLFO3->Process(Samples)) { // if pitch LFO modulation is active  
             SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);  
             SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);  
         }  
   
         if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode))  
             CalculateBiquadParameters(Samples); // calculate the final biquad filter parameters  
   
593          switch (this->PlaybackState) {          switch (this->PlaybackState) {
594    
595              case playback_state_init:              case playback_state_init:
# Line 707  namespace LinuxSampler { namespace gig { Line 604  namespace LinuxSampler { namespace gig {
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 727  namespace LinuxSampler { namespace gig { Line 623  namespace LinuxSampler { namespace gig {
623                              KillImmediately();                              KillImmediately();
624                              return;                              return;
625                          }                          }
626                          DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (int(Pos) - MaxRAMPos));                          DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (int(finalSynthesisParameters.dPos) - MaxRAMPos));
627                          Pos -= int(Pos);                          finalSynthesisParameters.dPos -= int(finalSynthesisParameters.dPos);
628                          RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet                          RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet
629                      }                      }
630    
# Line 744  namespace LinuxSampler { namespace gig { Line 640  namespace LinuxSampler { namespace gig {
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    
645                      // render current audio fragment                      // render current audio fragment
646                      Synthesize(Samples, ptr, Delay);                      Synthesize(Samples, ptr, Delay);
647    
648                      const int iPos = (int) Pos;                      const int iPos = (int) finalSynthesisParameters.dPos;
649                      const int readSampleWords = iPos * pSample->Channels; // amount of sample words actually been read                      const int readSampleWords = iPos * pSample->Channels; // amount of sample words actually been read
650                      DiskStreamRef.pStream->IncrementReadPos(readSampleWords);                      DiskStreamRef.pStream->IncrementReadPos(readSampleWords);
651                      Pos -= iPos; // just keep fractional part of Pos                      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                      // change state of voice to 'end' if we really reached the end of the sample data
654                      if (RealSampleWordsLeftToRead >= 0) {                      if (RealSampleWordsLeftToRead >= 0) {
# Line 767  namespace LinuxSampler { namespace gig { Line 663  namespace LinuxSampler { namespace gig {
663                  break;                  break;
664          }          }
665    
         // Reset synthesis event lists (except VCO, as VCO events apply channel wide currently)  
         pEngineChannel->pSynthesisEvents[Event::destination_vca]->clear();  
         pEngineChannel->pSynthesisEvents[Event::destination_vcfc]->clear();  
         pEngineChannel->pSynthesisEvents[Event::destination_vcfr]->clear();  
   
666          // Reset delay          // Reset delay
667          Delay = 0;          Delay = 0;
668    
669          itTriggerEvent = Pool<Event>::Iterator();          itTriggerEvent = Pool<Event>::Iterator();
670    
671          // If sample stream or release stage finished, kill the voice          // If sample stream or release stage finished, kill the voice
672          if (PlaybackState == playback_state_end || pEG1->GetStage() == EGADSR::stage_end) KillImmediately();          if (PlaybackState == playback_state_end || EG1.getSegmentType() == EGADSR::segment_end) KillImmediately();
673      }      }
674    
675      /**      /**
# Line 786  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();  
         FilterLeft.Reset();  
         FilterRight.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;
# Line 801  namespace LinuxSampler { namespace gig { Line 689  namespace LinuxSampler { namespace gig {
689      }      }
690    
691      /**      /**
692       *  Process the control change event lists of the engine for the current       * Process given list of MIDI note on, note off and sustain pedal events
693       *  audio fragment. Event values will be applied to the synthesis parameter       * for the given time.
      *  matrix.  
694       *       *
695       *  @param Samples - number of samples to be rendered in this audio fragment cycle       * @param itEvent - iterator pointing to the next event to be processed
696         * @param End     - youngest time stamp where processing should be stopped
697       */       */
698      void Voice::ProcessEvents(uint Samples) {      void Voice::processTransitionEvents(RTList<Event>::Iterator& itEvent, uint End) {
699            for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
700                if (itEvent->Type == Event::type_release) {
701                    EG1.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
702                    EG2.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
703                } else if (itEvent->Type == Event::type_cancel_release) {
704                    EG1.update(EGADSR::event_cancel_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
705                    EG2.update(EGADSR::event_cancel_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
706                }
707            }
708        }
709    
710          // dispatch control change events      /**
711          RTList<Event>::Iterator itCCEvent = pEngineChannel->pCCEvents->first();       * Process given list of MIDI control change and pitch bend events for
712          if (Delay) { // skip events that happened before this voice was triggered       * the given time.
713              while (itCCEvent && itCCEvent->FragmentPos() <= Delay) ++itCCEvent;       *
714          }       * @param itEvent - iterator pointing to the next event to be processed
715          while (itCCEvent) {       * @param End     - youngest time stamp where processing should be stopped
716              if (itCCEvent->Param.CC.Controller) { // if valid MIDI controller       */
717                  if (itCCEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {      void Voice::processCCEvents(RTList<Event>::Iterator& itEvent, uint End) {
718                      *pEngineChannel->pSynthesisEvents[Event::destination_vcfc]->allocAppend() = *itCCEvent;          for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
719                  }              if (itEvent->Type == Event::type_control_change &&
720                  if (itCCEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {                  itEvent->Param.CC.Controller) { // if (valid) MIDI control change event
721                      *pEngineChannel->pSynthesisEvents[Event::destination_vcfr]->allocAppend() = *itCCEvent;                  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 (itCCEvent->Param.CC.Controller == pLFO1->ExtController) {                  if (itEvent->Param.CC.Controller == pLFO1->ExtController) {
728                      pLFO1->SendEvent(itCCEvent);                      pLFO1->update(itEvent->Param.CC.Value);
729                  }                  }
730                  if (itCCEvent->Param.CC.Controller == pLFO2->ExtController) {                  if (itEvent->Param.CC.Controller == pLFO2->ExtController) {
731                      pLFO2->SendEvent(itCCEvent);                      pLFO2->update(itEvent->Param.CC.Value);
732                  }                  }
733                  if (itCCEvent->Param.CC.Controller == pLFO3->ExtController) {                  if (itEvent->Param.CC.Controller == pLFO3->ExtController) {
734                      pLFO3->SendEvent(itCCEvent);                      pLFO3->update(itEvent->Param.CC.Value);
735                  }                  }
736                  if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&                  if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&
737                      itCCEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) { // if crossfade event                      itEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) {
738                      *pEngineChannel->pSynthesisEvents[Event::destination_vca]->allocAppend() = *itCCEvent;                      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              }              }
   
             ++itCCEvent;  
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              RTList<Event>* pVCOEventList = pEngineChannel->pSynthesisEvents[Event::destination_vco];          if (VCFCutoffCtrl.value == ccvalue) return;
759              RTList<Event>::Iterator itVCOEvent = 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 (itVCOEvent && itVCOEvent->FragmentPos() <= Delay) ++itVCOEvent;          if (ccvalue < pDimRgn->VCFVelocityScale) ccvalue = pDimRgn->VCFVelocityScale;
762              }          float cutoff = CutoffBase * float(ccvalue);
763              // apply old pitchbend value until first pitch event occurs          if (cutoff > 127.0f) cutoff = 127.0f;
764              if (this->PitchBend != 1.0) {  
765                  uint end = (itVCOEvent) ? itVCOEvent->FragmentPos() : Samples;          VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of fFinalCutoff next time
766                  for (uint i = Delay; i < end; i++) {          fFinalCutoff = cutoff;
767                      pEngine->pSynthesisParameters[Event::destination_vco][i] *= this->PitchBend;      }
768    
769        void Voice::processResonanceEvent(RTList<Event>::Iterator& itEvent) {
770            // convert absolute controller value to differential
771            const int ctrldelta = itEvent->Param.CC.Value - VCFResonanceCtrl.value;
772            VCFResonanceCtrl.value = itEvent->Param.CC.Value;
773            const float resonancedelta = (float) ctrldelta;
774            fFinalResonance += resonancedelta;
775            // needed for initialization of parameter
776            VCFResonanceCtrl.fvalue = itEvent->Param.CC.Value;
777        }
778    
779        /**
780         *  Synthesizes the current audio fragment for this voice.
781         *
782         *  @param Samples - number of sample points to be rendered in this audio
783         *                   fragment cycle
784         *  @param pSrc    - pointer to input sample data
785         *  @param Skip    - number of sample points to skip in output buffer
786         */
787        void Voice::Synthesize(uint Samples, sample_t* pSrc, uint Skip) {
788            finalSynthesisParameters.pOutLeft  = &pEngineChannel->pChannelLeft->Buffer()[Skip];
789            finalSynthesisParameters.pOutRight = &pEngineChannel->pChannelRight->Buffer()[Skip];
790            finalSynthesisParameters.pSrc      = pSrc;
791    
792            RTList<Event>::Iterator itCCEvent = pEngineChannel->pEvents->first();
793            RTList<Event>::Iterator itNoteEvent = pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents->first();
794    
795            if (itTriggerEvent) { // skip events that happened before this voice was triggered
796                while (itCCEvent && itCCEvent->FragmentPos() <= Skip) ++itCCEvent;
797                // we can't simply compare the timestamp here, because note events
798                // might happen on the same time stamp, so we have to deal on the
799                // actual sequence the note events arrived instead (see bug #112)
800                for (; itNoteEvent; ++itNoteEvent) {
801                    if (itTriggerEvent == itNoteEvent) {
802                        ++itNoteEvent;
803                        break;
804                  }                  }
805              }              }
806              float pitch;          }
             while (itVCOEvent) {  
                 RTList<Event>::Iterator itNextVCOEvent = itVCOEvent;  
                 ++itNextVCOEvent;  
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (itNextVCOEvent) ? itNextVCOEvent->FragmentPos() : Samples;  
   
                 pitch = RTMath::CentsToFreqRatio(((double) itVCOEvent->Param.Pitch.Pitch / 8192.0) * 200.0); // +-two semitones = +-200 cents  
   
                 // apply pitch value to the pitch parameter sequence  
                 for (uint i = itVCOEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vco][i] *= pitch;  
                 }  
807    
808                  itVCOEvent = itNextVCOEvent;          uint killPos;
809              }          if (itKillEvent) {
810              if (!pVCOEventList->isEmpty()) {              int maxFadeOutPos = Samples - pEngine->MinFadeOutSamples;
811                  this->PitchBend = pitch;              if (maxFadeOutPos < 0) {
812                  SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);                  // There's not enough space in buffer to do a fade out
813                  SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);                  // 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              }              }
822          }          }
823    
824          // process volume / attenuation events (TODO: we only handle and _expect_ crossfade events here ATM !)          uint i = Skip;
825          {          while (i < Samples) {
826              RTList<Event>* pVCAEventList = pEngineChannel->pSynthesisEvents[Event::destination_vca];              int iSubFragmentEnd = RTMath::Min(i + CONFIG_DEFAULT_SUBFRAGMENT_SIZE, Samples);
             RTList<Event>::Iterator itVCAEvent = pVCAEventList->first();  
             if (Delay) { // skip events that happened before this voice was triggered  
                 while (itVCAEvent && itVCAEvent->FragmentPos() <= Delay) ++itVCAEvent;  
             }  
             float crossfadevolume;  
             while (itVCAEvent) {  
                 RTList<Event>::Iterator itNextVCAEvent = itVCAEvent;  
                 ++itNextVCAEvent;  
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (itNextVCAEvent) ? itNextVCAEvent->FragmentPos() : Samples;  
   
                 crossfadevolume = CrossfadeAttenuation(itVCAEvent->Param.CC.Value);  
   
                 float effective_volume = crossfadevolume * this->Volume * pEngineChannel->GlobalVolume;  
   
                 // apply volume value to the volume parameter sequence  
                 for (uint i = itVCAEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vca][i] = effective_volume;  
                 }  
827    
828                  itVCAEvent = itNextVCAEvent;              // initialize all final synthesis parameters
829              }              fFinalCutoff    = VCFCutoffCtrl.fvalue;
830              if (!pVCAEventList->isEmpty()) this->CrossfadeVolume = crossfadevolume;              fFinalResonance = VCFResonanceCtrl.fvalue;
         }  
831    
832          // process filter cutoff events              // process MIDI control change and pitchbend events for this subfragment
833          {              processCCEvents(itCCEvent, iSubFragmentEnd);
             RTList<Event>* pCutoffEventList = pEngineChannel->pSynthesisEvents[Event::destination_vcfc];  
             RTList<Event>::Iterator itCutoffEvent = pCutoffEventList->first();  
             if (Delay) { // skip events that happened before this voice was triggered  
                 while (itCutoffEvent && itCutoffEvent->FragmentPos() <= Delay) ++itCutoffEvent;  
             }  
             float cutoff;  
             while (itCutoffEvent) {  
                 RTList<Event>::Iterator itNextCutoffEvent = itCutoffEvent;  
                 ++itNextCutoffEvent;  
   
                 // calculate the influence length of this event (in sample points)  
                 uint end = (itNextCutoffEvent) ? itNextCutoffEvent->FragmentPos() : Samples;  
   
                 cutoff = exp((float) itCutoffEvent->Param.CC.Value * 0.00787402f * FILTER_CUTOFF_COEFF) * CONFIG_FILTER_CUTOFF_MAX - CONFIG_FILTER_CUTOFF_MIN;  
   
                 // apply cutoff frequency to the cutoff parameter sequence  
                 for (uint i = itCutoffEvent->FragmentPos(); i < end; i++) {  
                     pEngine->pSynthesisParameters[Event::destination_vcfc][i] = cutoff;  
                 }  
834    
835                  itCutoffEvent = itNextCutoffEvent;              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                // process transition events (note on, note off & sustain pedal)
842                processTransitionEvents(itNoteEvent, iSubFragmentEnd);
843    
844                // 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->isEmpty()) 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              RTList<Event>* pResonanceEventList = pEngineChannel->pSynthesisEvents[Event::destination_vcfr];                  case EGADSR::segment_lin:
856              RTList<Event>::Iterator itResonanceEvent = pResonanceEventList->first();                      fFinalVolume *= EG1.processLin();
857              if (Delay) { // skip events that happened before this voice was triggered                      break;
858                  while (itResonanceEvent && itResonanceEvent->FragmentPos() <= Delay) ++itResonanceEvent;                  case EGADSR::segment_exp:
859              }                      fFinalVolume *= EG1.processExp();
860              while (itResonanceEvent) {                      break;
861                  RTList<Event>::Iterator itNextResonanceEvent = itResonanceEvent;                  case EGADSR::segment_end:
862                  ++itNextResonanceEvent;                      fFinalVolume *= EG1.getLevel();
863                        break; // noop
864                  // calculate the influence length of this event (in sample points)              }
865                  uint end = (itNextResonanceEvent) ? itNextResonanceEvent->FragmentPos() : Samples;              switch (EG2.getSegmentType()) {
866                    case EGADSR::segment_lin:
867                  // convert absolute controller value to differential                      fFinalCutoff *= EG2.processLin();
868                  int ctrldelta = itResonanceEvent->Param.CC.Value - VCFResonanceCtrl.value;                      break;
869                  VCFResonanceCtrl.value = itResonanceEvent->Param.CC.Value;                  case EGADSR::segment_exp:
870                        fFinalCutoff *= EG2.processExp();
871                  float resonancedelta = (float) ctrldelta * 0.00787f; // 0.0..1.0                      break;
872                    case EGADSR::segment_end:
873                  // apply cutoff frequency to the cutoff parameter sequence                      fFinalCutoff *= EG2.getLevel();
874                  for (uint i = itResonanceEvent->FragmentPos(); i < end; i++) {                      break; // noop
875                      pEngine->pSynthesisParameters[Event::destination_vcfr][i] += resonancedelta;              }
876                  }              if (EG3.active()) finalSynthesisParameters.fFinalPitch *= EG3.render();
877    
878                // process low frequency oscillators
879                if (bLFO1Enabled) fFinalVolume *= (1.0f - pLFO1->render());
880                if (bLFO2Enabled) fFinalCutoff *= pLFO2->render();
881                if (bLFO3Enabled) finalSynthesisParameters.fFinalPitch *= RTMath::CentsToFreqRatio(pLFO3->render());
882    
883                // limit the pitch so we don't read outside the buffer
884                finalSynthesisParameters.fFinalPitch = RTMath::Min(finalSynthesisParameters.fFinalPitch, float(1 << CONFIG_MAX_PITCH));
885    
886                  itResonanceEvent = itNextResonanceEvent;              // if filter enabled then update filter coefficients
887                if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode)) {
888                    finalSynthesisParameters.filterLeft.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
889                    finalSynthesisParameters.filterRight.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
890              }              }
             if (!pResonanceEventList->isEmpty()) VCFResonanceCtrl.fvalue = pResonanceEventList->last()->Param.CC.Value * 0.00787f; // needed for initialization of parameter matrix next time  
         }  
     }  
891    
892      /**              // do we need resampling?
893       * Calculate all necessary, final biquad filter parameters.              const float __PLUS_ONE_CENT  = 1.000577789506554859250142541782224725466f;
894       *              const float __MINUS_ONE_CENT = 0.9994225441413807496009516495583113737666f;
895       * @param Samples - number of samples to be rendered in this audio fragment cycle              const bool bResamplingRequired = !(finalSynthesisParameters.fFinalPitch <= __PLUS_ONE_CENT &&
896       */                                                 finalSynthesisParameters.fFinalPitch >= __MINUS_ONE_CENT);
897      void Voice::CalculateBiquadParameters(uint Samples) {              SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, bResamplingRequired);
898          biquad_param_t bqbase;  
899          biquad_param_t bqmain;              // prepare final synthesis parameters structure
900          float prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][0];              finalSynthesisParameters.uiToGo            = iSubFragmentEnd - i;
901          float prev_res    = pEngine->pSynthesisParameters[Event::destination_vcfr][0];  #ifdef CONFIG_INTERPOLATE_VOLUME
902          FilterLeft.SetParameters( &bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);              finalSynthesisParameters.fFinalVolumeDeltaLeft  =
903          FilterRight.SetParameters(&bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);                  (fFinalVolume * VolumeLeft  * PanLeftSmoother.render() -
904          pEngine->pBasicFilterParameters[0] = bqbase;                   finalSynthesisParameters.fFinalVolumeLeft) / finalSynthesisParameters.uiToGo;
905          pEngine->pMainFilterParameters[0]  = bqmain;              finalSynthesisParameters.fFinalVolumeDeltaRight =
906                    (fFinalVolume * VolumeRight * PanRightSmoother.render() -
907          float* bq;                   finalSynthesisParameters.fFinalVolumeRight) / finalSynthesisParameters.uiToGo;
908          for (int i = 1; i < Samples; i++) {  #else
909              // recalculate biquad parameters if cutoff or resonance differ from previous sample point              finalSynthesisParameters.fFinalVolumeLeft  =
910              if (!(i & FILTER_UPDATE_MASK)) {                  fFinalVolume * VolumeLeft  * PanLeftSmoother.render();
911                  if (pEngine->pSynthesisParameters[Event::destination_vcfr][i] != prev_res ||              finalSynthesisParameters.fFinalVolumeRight =
912                      pEngine->pSynthesisParameters[Event::destination_vcfc][i] != prev_cutoff)                  fFinalVolume * VolumeRight * PanRightSmoother.render();
913                  {  #endif
914                      prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][i];              // render audio for one subfragment
915                      prev_res    = pEngine->pSynthesisParameters[Event::destination_vcfr][i];              RunSynthesisFunction(SynthesisMode, &finalSynthesisParameters, &loop);
916                      FilterLeft.SetParameters( &bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);  
917                      FilterRight.SetParameters(&bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);              // stop the rendering if volume EG is finished
918                if (EG1.getSegmentType() == EGADSR::segment_end) break;
919    
920                const double newPos = Pos + (iSubFragmentEnd - i) * finalSynthesisParameters.fFinalPitch;
921    
922                // 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                    EG1.increment(1);
931                    if (!EG1.toStageEndLeft()) EG1.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
932                }
933                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              //same as 'pEngine->pBasicFilterParameters[i] = bqbase;'              Pos = newPos;
941              bq    = (float*) &pEngine->pBasicFilterParameters[i];              i = iSubFragmentEnd;
             bq[0] = bqbase.b0;  
             bq[1] = bqbase.b1;  
             bq[2] = bqbase.b2;  
             bq[3] = bqbase.a1;  
             bq[4] = bqbase.a2;  
   
             // same as 'pEngine->pMainFilterParameters[i] = bqmain;'  
             bq    = (float*) &pEngine->pMainFilterParameters[i];  
             bq[0] = bqmain.b0;  
             bq[1] = bqmain.b1;  
             bq[2] = bqmain.b2;  
             bq[3] = bqmain.a1;  
             bq[4] = bqmain.a2;  
942          }          }
943      }      }
944    
945      /**      /** @brief Update current portamento position.
      *  Synthesizes the current audio fragment for this voice.  
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::Synthesize(uint Samples, sample_t* pSrc, uint Skip) {      void Voice::UpdatePortamentoPos(Pool<Event>::Iterator& itNoteOffEvent) {
954          RunSynthesisFunction(SynthesisMode, *this, Samples, pSrc, Skip);          const float fFinalEG3Level = EG3.level(itNoteOffEvent->FragmentPos());
955            pEngineChannel->PortamentoPos = (float) MIDIKey + RTMath::FreqRatioToCents(fFinalEG3Level) * 0.01f;
956      }      }
957    
958      /**      /**
# Line 1031  namespace LinuxSampler { namespace gig { Line 961  namespace LinuxSampler { namespace gig {
961       *  fading down the volume level to avoid clicks and regular processing       *  fading down the volume level to avoid clicks and regular processing
962       *  until the kill event actually occured!       *  until the kill event actually occured!
963       *       *
964       *  @see Kill()       * If it's necessary to know when the voice's disk stream was actually
965         * deleted, then one can set the optional @a bRequestNotification
966         * parameter and this method will then return the handle of the disk
967         * stream (unique identifier) and one can use this handle to poll the
968         * disk thread if this stream has been deleted. In any case this method
969         * will return immediately and will not block until the stream actually
970         * was deleted.
971         *
972         * @param bRequestNotification - (optional) whether the disk thread shall
973         *                                provide a notification once it deleted
974         *                               the respective disk stream
975         *                               (default=false)
976         * @returns handle to the voice's disk stream or @c Stream::INVALID_HANDLE
977         *          if the voice did not use a disk stream at all
978         * @see Kill()
979       */       */
980      void Voice::KillImmediately() {      Stream::Handle Voice::KillImmediately(bool bRequestNotification) {
981            Stream::Handle hStream = Stream::INVALID_HANDLE;
982          if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {          if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
983              pDiskThread->OrderDeletionOfStream(&DiskStreamRef);              pDiskThread->OrderDeletionOfStream(&DiskStreamRef, bRequestNotification);
984                hStream = DiskStreamRef.hStream;
985          }          }
986          Reset();          Reset();
987            return hStream;
988      }      }
989    
990      /**      /**

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

  ViewVC Help
Powered by ViewVC