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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2012 - (hide annotations) (download)
Fri Oct 23 17:53:17 2009 UTC (14 years, 6 months ago) by iliev
File size: 51253 byte(s)
* Refactoring: moved the independent code from
  the Gigasampler format engine to base classes
* SFZ format engine: experimental code (not usable yet)
* SoundFont format engine: experimental code (not usable yet)
* Fixed crash which may occur when MIDI key + transpose is out of range

1 schoenebeck 53 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5 schoenebeck 56 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 schoenebeck 1857 * Copyright (C) 2005 - 2009 Christian Schoenebeck *
7 schoenebeck 53 * *
8     * 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 *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This program is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this program; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24 schoenebeck 319 #include "../../common/Features.h"
25     #include "Synthesizer.h"
26 schoenebeck 770 #include "Profiler.h"
27 iliev 2012 #include "Engine.h"
28     #include "EngineChannel.h"
29 schoenebeck 53
30     #include "Voice.h"
31    
32     namespace LinuxSampler { namespace gig {
33    
34     Voice::Voice() {
35     pEngine = NULL;
36     pDiskThread = NULL;
37 schoenebeck 285 PlaybackState = playback_state_end;
38 schoenebeck 738 pLFO1 = new LFOUnsigned(1.0f); // amplitude EG (0..1 range)
39     pLFO2 = new LFOUnsigned(1.0f); // filter EG (0..1 range)
40     pLFO3 = new LFOSigned(1200.0f); // pitch EG (-1200..+1200 range)
41 schoenebeck 239 KeyGroup = 0;
42 schoenebeck 361 SynthesisMode = 0; // set all mode bits to 0 first
43 schoenebeck 1259 // select synthesis implementation (asm core is not supported ATM)
44     #if 0 // CONFIG_ASM && ARCH_X86
45 schoenebeck 319 SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
46 schoenebeck 361 #else
47     SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);
48     #endif
49 schoenebeck 770 SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, Profiler::isEnabled());
50 schoenebeck 368
51 schoenebeck 770 finalSynthesisParameters.filterLeft.Reset();
52     finalSynthesisParameters.filterRight.Reset();
53 schoenebeck 53 }
54    
55     Voice::~Voice() {
56     if (pLFO1) delete pLFO1;
57     if (pLFO2) delete pLFO2;
58     if (pLFO3) delete pLFO3;
59     }
60    
61 iliev 2012 void Voice::SetEngine(LinuxSampler::Engine* pEngine) {
62     Engine* engine = static_cast<Engine*>(pEngine);
63     this->pEngine = engine;
64     this->pDiskThread = engine->pDiskThread;
65 schoenebeck 64 dmsg(6,("Voice::SetEngine()\n"));
66 schoenebeck 53 }
67    
68     /**
69     * Initializes and triggers the voice, a disk stream will be launched if
70     * needed.
71     *
72 schoenebeck 669 * @param pEngineChannel - engine channel on which this voice was ordered
73     * @param itNoteOnEvent - event that caused triggering of this voice
74     * @param PitchBend - MIDI detune factor (-8192 ... +8191)
75     * @param pDimRgn - points to the dimension region which provides sample wave(s) and articulation data
76     * @param VoiceType - type of this voice
77     * @param iKeyGroup - a value > 0 defines a key group in which this voice is member of
78 schoenebeck 354 * @returns 0 on success, a value < 0 if the voice wasn't triggered
79     * (either due to an error or e.g. because no region is
80     * defined for the given key)
81 schoenebeck 53 */
82 schoenebeck 669 int Voice::Trigger(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int PitchBend, ::gig::DimensionRegion* pDimRgn, type_t VoiceType, int iKeyGroup) {
83 schoenebeck 411 this->pEngineChannel = pEngineChannel;
84 schoenebeck 669 this->pDimRgn = pDimRgn;
85 persson 1038 Orphan = false;
86 schoenebeck 669
87 schoenebeck 563 #if CONFIG_DEVMODE
88     if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging
89 schoenebeck 319 dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
90     }
91 schoenebeck 563 #endif // CONFIG_DEVMODE
92 schoenebeck 53
93 schoenebeck 669 Type = VoiceType;
94 schoenebeck 271 MIDIKey = itNoteOnEvent->Param.Note.Key;
95 schoenebeck 563 PlaybackState = playback_state_init; // mark voice as triggered, but no audio rendered yet
96 schoenebeck 271 Delay = itNoteOnEvent->FragmentPos();
97     itTriggerEvent = itNoteOnEvent;
98     itKillEvent = Pool<Event>::Iterator();
99 schoenebeck 669 KeyGroup = iKeyGroup;
100     pSample = pDimRgn->pSample; // sample won't change until the voice is finished
101 schoenebeck 53
102 persson 630 // calculate volume
103     const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
104    
105 persson 903 // For 16 bit samples, we downscale by 32768 to convert from
106     // int16 value range to DSP value range (which is
107     // -1.0..1.0). For 24 bit, we downscale from int32.
108     float volume = velocityAttenuation / (pSample->BitDepth == 16 ? 32768.0f : 32768.0f * 65536.0f);
109 persson 630
110 persson 1010 volume *= pDimRgn->SampleAttenuation * pEngineChannel->GlobalVolume * GLOBAL_VOLUME;
111 persson 630
112     // the volume of release triggered samples depends on note length
113 schoenebeck 669 if (Type == type_release_trigger) {
114 persson 630 float noteLength = float(pEngine->FrameTime + Delay -
115     pEngineChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime) / pEngine->SampleRate;
116     float attenuation = 1 - 0.01053 * (256 >> pDimRgn->ReleaseTriggerDecay) * noteLength;
117     if (attenuation <= 0) return -1;
118 persson 832 volume *= attenuation;
119 persson 630 }
120    
121 schoenebeck 319 // select channel mode (mono or stereo)
122     SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, pSample->Channels == 2);
123 persson 903 // select bit depth (16 or 24)
124     SYNTHESIS_MODE_SET_BITDEPTH24(SynthesisMode, pSample->BitDepth == 24);
125 schoenebeck 319
126 schoenebeck 236 // get starting crossfade volume level
127 persson 832 float crossfadeVolume;
128 schoenebeck 236 switch (pDimRgn->AttenuationController.type) {
129     case ::gig::attenuation_ctrl_t::type_channelaftertouch:
130 persson 903 crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[128])];
131 schoenebeck 236 break;
132     case ::gig::attenuation_ctrl_t::type_velocity:
133 persson 832 crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity)];
134 schoenebeck 236 break;
135     case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate
136 persson 832 crossfadeVolume = Engine::CrossfadeCurve[CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number])];
137 schoenebeck 236 break;
138     case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined
139     default:
140 persson 832 crossfadeVolume = 1.0f;
141 schoenebeck 236 }
142    
143 persson 832 VolumeLeft = volume * Engine::PanCurve[64 - pDimRgn->Pan];
144     VolumeRight = volume * Engine::PanCurve[64 + pDimRgn->Pan];
145 schoenebeck 245
146 persson 832 float subfragmentRate = pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE;
147     CrossfadeSmoother.trigger(crossfadeVolume, subfragmentRate);
148 persson 1010 VolumeSmoother.trigger(pEngineChannel->MidiVolume, subfragmentRate);
149 persson 832 PanLeftSmoother.trigger(pEngineChannel->GlobalPanLeft, subfragmentRate);
150     PanRightSmoother.trigger(pEngineChannel->GlobalPanRight, subfragmentRate);
151    
152 schoenebeck 770 finalSynthesisParameters.dPos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)
153 persson 783 Pos = pDimRgn->SampleStartOffset;
154 schoenebeck 236
155 schoenebeck 53 // Check if the sample needs disk streaming or is too short for that
156     long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;
157     DiskVoice = cachedsamples < pSample->SamplesTotal;
158    
159 persson 865 const DLS::sample_loop_t& loopinfo = pDimRgn->pSampleLoops[0];
160    
161 schoenebeck 53 if (DiskVoice) { // voice to be streamed from disk
162 persson 1895 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 schoenebeck 53
173     // check if there's a loop defined which completely fits into the cached (RAM) part of the sample
174 persson 865 RAMLoop = (pDimRgn->SampleLoops && (loopinfo.LoopStart + loopinfo.LoopLength) <= MaxRAMPos);
175 schoenebeck 53
176 persson 865 if (pDiskThread->OrderNewStream(&DiskStreamRef, pDimRgn, MaxRAMPos, !RAMLoop) < 0) {
177 schoenebeck 53 dmsg(1,("Disk stream order failed!\n"));
178 schoenebeck 239 KillImmediately();
179 schoenebeck 53 return -1;
180     }
181     dmsg(4,("Disk voice launched (cached samples: %d, total Samples: %d, MaxRAMPos: %d, RAMLooping: %s)\n", cachedsamples, pSample->SamplesTotal, MaxRAMPos, (RAMLoop) ? "yes" : "no"));
182     }
183     else { // RAM only voice
184     MaxRAMPos = cachedsamples;
185 persson 865 RAMLoop = (pDimRgn->SampleLoops != 0);
186 schoenebeck 53 dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));
187     }
188 persson 799 if (RAMLoop) {
189     loop.uiTotalCycles = pSample->LoopPlayCount;
190     loop.uiCyclesLeft = pSample->LoopPlayCount;
191 persson 865 loop.uiStart = loopinfo.LoopStart;
192     loop.uiEnd = loopinfo.LoopStart + loopinfo.LoopLength;
193     loop.uiSize = loopinfo.LoopLength;
194 persson 799 }
195 schoenebeck 53
196     // calculate initial pitch value
197     {
198 persson 1858 double pitchbasecents = pEngineChannel->pInstrument->FineTune + pDimRgn->FineTune + pEngine->ScaleTuning[MIDIKey % 12];
199 persson 1700
200     // GSt behaviour: maximum transpose up is 40 semitones. If
201     // MIDI key is more than 40 semitones above unity note,
202     // the transpose is not done.
203     if (pDimRgn->PitchTrack && (MIDIKey - (int) pDimRgn->UnityNote) < 40) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;
204    
205 persson 1862 this->PitchBase = RTMath::CentsToFreqRatioUnlimited(pitchbasecents) * (double(pSample->SamplesPerSecond) / double(pEngine->SampleRate));
206 persson 1923 this->PitchBendRange = 1.0 / 8192.0 * 100.0 * pEngineChannel->pInstrument->PitchbendRange;
207     this->PitchBend = RTMath::CentsToFreqRatio(PitchBend * PitchBendRange);
208 schoenebeck 53 }
209    
210 persson 614 // the length of the decay and release curves are dependent on the velocity
211     const double velrelease = 1 / pDimRgn->GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);
212    
213 schoenebeck 53 // setup EG 1 (VCA EG)
214     {
215     // get current value of EG1 controller
216     double eg1controllervalue;
217     switch (pDimRgn->EG1Controller.type) {
218     case ::gig::eg1_ctrl_t::type_none: // no controller defined
219     eg1controllervalue = 0;
220     break;
221     case ::gig::eg1_ctrl_t::type_channelaftertouch:
222 persson 903 eg1controllervalue = pEngineChannel->ControllerTable[128];
223 schoenebeck 53 break;
224     case ::gig::eg1_ctrl_t::type_velocity:
225 schoenebeck 271 eg1controllervalue = itNoteOnEvent->Param.Note.Velocity;
226 schoenebeck 53 break;
227     case ::gig::eg1_ctrl_t::type_controlchange: // MIDI control change controller
228 schoenebeck 411 eg1controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG1Controller.controller_number];
229 schoenebeck 53 break;
230     }
231     if (pDimRgn->EG1ControllerInvert) eg1controllervalue = 127 - eg1controllervalue;
232    
233 persson 696 // calculate influence of EG1 controller on EG1's parameters
234     // (eg1attack is different from the others)
235     double eg1attack = (pDimRgn->EG1ControllerAttackInfluence) ?
236     1 + 0.031 * (double) (pDimRgn->EG1ControllerAttackInfluence == 1 ?
237     1 : 1 << pDimRgn->EG1ControllerAttackInfluence) * eg1controllervalue : 1.0;
238     double eg1decay = (pDimRgn->EG1ControllerDecayInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG1ControllerDecayInfluence) * eg1controllervalue : 1.0;
239     double eg1release = (pDimRgn->EG1ControllerReleaseInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG1ControllerReleaseInfluence) * eg1controllervalue : 1.0;
240 schoenebeck 53
241 schoenebeck 738 EG1.trigger(pDimRgn->EG1PreAttack,
242     pDimRgn->EG1Attack * eg1attack,
243     pDimRgn->EG1Hold,
244     pDimRgn->EG1Decay1 * eg1decay * velrelease,
245     pDimRgn->EG1Decay2 * eg1decay * velrelease,
246     pDimRgn->EG1InfiniteSustain,
247     pDimRgn->EG1Sustain,
248     pDimRgn->EG1Release * eg1release * velrelease,
249     velocityAttenuation,
250     pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
251 schoenebeck 53 }
252    
253 persson 832 #ifdef CONFIG_INTERPOLATE_VOLUME
254 persson 830 // setup initial volume in synthesis parameters
255 persson 832 #ifdef CONFIG_PROCESS_MUTED_CHANNELS
256     if (pEngineChannel->GetMute()) {
257     finalSynthesisParameters.fFinalVolumeLeft = 0;
258     finalSynthesisParameters.fFinalVolumeRight = 0;
259     }
260     else
261     #else
262     {
263 persson 1010 float finalVolume = pEngineChannel->MidiVolume * crossfadeVolume * EG1.getLevel();
264 schoenebeck 53
265 persson 832 finalSynthesisParameters.fFinalVolumeLeft = finalVolume * VolumeLeft * pEngineChannel->GlobalPanLeft;
266     finalSynthesisParameters.fFinalVolumeRight = finalVolume * VolumeRight * pEngineChannel->GlobalPanRight;
267     }
268     #endif
269     #endif
270 persson 830
271 schoenebeck 53 // setup EG 2 (VCF Cutoff EG)
272     {
273     // get current value of EG2 controller
274     double eg2controllervalue;
275     switch (pDimRgn->EG2Controller.type) {
276     case ::gig::eg2_ctrl_t::type_none: // no controller defined
277     eg2controllervalue = 0;
278     break;
279     case ::gig::eg2_ctrl_t::type_channelaftertouch:
280 persson 903 eg2controllervalue = pEngineChannel->ControllerTable[128];
281 schoenebeck 53 break;
282     case ::gig::eg2_ctrl_t::type_velocity:
283 schoenebeck 271 eg2controllervalue = itNoteOnEvent->Param.Note.Velocity;
284 schoenebeck 53 break;
285     case ::gig::eg2_ctrl_t::type_controlchange: // MIDI control change controller
286 schoenebeck 411 eg2controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG2Controller.controller_number];
287 schoenebeck 53 break;
288     }
289     if (pDimRgn->EG2ControllerInvert) eg2controllervalue = 127 - eg2controllervalue;
290    
291 persson 696 // calculate influence of EG2 controller on EG2's parameters
292     double eg2attack = (pDimRgn->EG2ControllerAttackInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerAttackInfluence) * eg2controllervalue : 1.0;
293     double eg2decay = (pDimRgn->EG2ControllerDecayInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerDecayInfluence) * eg2controllervalue : 1.0;
294     double eg2release = (pDimRgn->EG2ControllerReleaseInfluence) ? 1 + 0.00775 * (double) (1 << pDimRgn->EG2ControllerReleaseInfluence) * eg2controllervalue : 1.0;
295 schoenebeck 53
296 schoenebeck 738 EG2.trigger(pDimRgn->EG2PreAttack,
297     pDimRgn->EG2Attack * eg2attack,
298     false,
299     pDimRgn->EG2Decay1 * eg2decay * velrelease,
300     pDimRgn->EG2Decay2 * eg2decay * velrelease,
301     pDimRgn->EG2InfiniteSustain,
302     pDimRgn->EG2Sustain,
303     pDimRgn->EG2Release * eg2release * velrelease,
304     velocityAttenuation,
305     pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
306 schoenebeck 53 }
307    
308    
309     // setup EG 3 (VCO EG)
310     {
311 schoenebeck 829 // if portamento mode is on, we dedicate EG3 purely for portamento, otherwise if portamento is off we do as told by the patch
312     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 schoenebeck 53 }
322    
323    
324     // setup LFO 1 (VCA LFO)
325     {
326     uint16_t lfo1_internal_depth;
327     switch (pDimRgn->LFO1Controller) {
328     case ::gig::lfo1_ctrl_internal:
329     lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
330     pLFO1->ExtController = 0; // no external controller
331 schoenebeck 687 bLFO1Enabled = (lfo1_internal_depth > 0);
332 schoenebeck 53 break;
333     case ::gig::lfo1_ctrl_modwheel:
334     lfo1_internal_depth = 0;
335     pLFO1->ExtController = 1; // MIDI controller 1
336 schoenebeck 687 bLFO1Enabled = (pDimRgn->LFO1ControlDepth > 0);
337 schoenebeck 53 break;
338     case ::gig::lfo1_ctrl_breath:
339     lfo1_internal_depth = 0;
340     pLFO1->ExtController = 2; // MIDI controller 2
341 schoenebeck 687 bLFO1Enabled = (pDimRgn->LFO1ControlDepth > 0);
342 schoenebeck 53 break;
343     case ::gig::lfo1_ctrl_internal_modwheel:
344     lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
345     pLFO1->ExtController = 1; // MIDI controller 1
346 schoenebeck 687 bLFO1Enabled = (lfo1_internal_depth > 0 || pDimRgn->LFO1ControlDepth > 0);
347 schoenebeck 53 break;
348     case ::gig::lfo1_ctrl_internal_breath:
349     lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
350     pLFO1->ExtController = 2; // MIDI controller 2
351 schoenebeck 687 bLFO1Enabled = (lfo1_internal_depth > 0 || pDimRgn->LFO1ControlDepth > 0);
352 schoenebeck 53 break;
353     default:
354     lfo1_internal_depth = 0;
355     pLFO1->ExtController = 0; // no external controller
356 schoenebeck 687 bLFO1Enabled = false;
357 schoenebeck 53 }
358 persson 841 if (bLFO1Enabled) {
359     pLFO1->trigger(pDimRgn->LFO1Frequency,
360 persson 922 start_level_min,
361 persson 841 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     }
367 schoenebeck 53 }
368    
369 schoenebeck 319
370 schoenebeck 53 // setup LFO 2 (VCF Cutoff LFO)
371     {
372     uint16_t lfo2_internal_depth;
373     switch (pDimRgn->LFO2Controller) {
374     case ::gig::lfo2_ctrl_internal:
375     lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
376     pLFO2->ExtController = 0; // no external controller
377 schoenebeck 687 bLFO2Enabled = (lfo2_internal_depth > 0);
378 schoenebeck 53 break;
379     case ::gig::lfo2_ctrl_modwheel:
380     lfo2_internal_depth = 0;
381     pLFO2->ExtController = 1; // MIDI controller 1
382 schoenebeck 687 bLFO2Enabled = (pDimRgn->LFO2ControlDepth > 0);
383 schoenebeck 53 break;
384     case ::gig::lfo2_ctrl_foot:
385     lfo2_internal_depth = 0;
386     pLFO2->ExtController = 4; // MIDI controller 4
387 schoenebeck 687 bLFO2Enabled = (pDimRgn->LFO2ControlDepth > 0);
388 schoenebeck 53 break;
389     case ::gig::lfo2_ctrl_internal_modwheel:
390     lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
391     pLFO2->ExtController = 1; // MIDI controller 1
392 schoenebeck 687 bLFO2Enabled = (lfo2_internal_depth > 0 || pDimRgn->LFO2ControlDepth > 0);
393 schoenebeck 53 break;
394     case ::gig::lfo2_ctrl_internal_foot:
395     lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
396     pLFO2->ExtController = 4; // MIDI controller 4
397 schoenebeck 687 bLFO2Enabled = (lfo2_internal_depth > 0 || pDimRgn->LFO2ControlDepth > 0);
398 schoenebeck 53 break;
399     default:
400     lfo2_internal_depth = 0;
401     pLFO2->ExtController = 0; // no external controller
402 schoenebeck 687 bLFO2Enabled = false;
403 schoenebeck 53 }
404 persson 841 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     }
413 schoenebeck 53 }
414    
415 schoenebeck 319
416 schoenebeck 53 // setup LFO 3 (VCO LFO)
417     {
418     uint16_t lfo3_internal_depth;
419     switch (pDimRgn->LFO3Controller) {
420     case ::gig::lfo3_ctrl_internal:
421     lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
422     pLFO3->ExtController = 0; // no external controller
423 schoenebeck 687 bLFO3Enabled = (lfo3_internal_depth > 0);
424 schoenebeck 53 break;
425     case ::gig::lfo3_ctrl_modwheel:
426     lfo3_internal_depth = 0;
427     pLFO3->ExtController = 1; // MIDI controller 1
428 schoenebeck 687 bLFO3Enabled = (pDimRgn->LFO3ControlDepth > 0);
429 schoenebeck 53 break;
430     case ::gig::lfo3_ctrl_aftertouch:
431     lfo3_internal_depth = 0;
432 persson 903 pLFO3->ExtController = 128;
433     bLFO3Enabled = true;
434 schoenebeck 53 break;
435     case ::gig::lfo3_ctrl_internal_modwheel:
436     lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
437     pLFO3->ExtController = 1; // MIDI controller 1
438 schoenebeck 687 bLFO3Enabled = (lfo3_internal_depth > 0 || pDimRgn->LFO3ControlDepth > 0);
439 schoenebeck 53 break;
440     case ::gig::lfo3_ctrl_internal_aftertouch:
441     lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
442 persson 903 pLFO1->ExtController = 128;
443     bLFO3Enabled = (lfo3_internal_depth > 0 || pDimRgn->LFO3ControlDepth > 0);
444 schoenebeck 53 break;
445     default:
446     lfo3_internal_depth = 0;
447     pLFO3->ExtController = 0; // no external controller
448 schoenebeck 687 bLFO3Enabled = false;
449 schoenebeck 53 }
450 persson 841 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     }
459 schoenebeck 53 }
460    
461 schoenebeck 319
462 schoenebeck 554 #if CONFIG_FORCE_FILTER
463 schoenebeck 368 const bool bUseFilter = true;
464 schoenebeck 53 #else // use filter only if instrument file told so
465 schoenebeck 368 const bool bUseFilter = pDimRgn->VCFEnabled;
466 schoenebeck 554 #endif // CONFIG_FORCE_FILTER
467 schoenebeck 368 SYNTHESIS_MODE_SET_FILTER(SynthesisMode, bUseFilter);
468     if (bUseFilter) {
469 schoenebeck 554 #ifdef CONFIG_OVERRIDE_CUTOFF_CTRL
470     VCFCutoffCtrl.controller = CONFIG_OVERRIDE_CUTOFF_CTRL;
471 schoenebeck 53 #else // use the one defined in the instrument file
472     switch (pDimRgn->VCFCutoffController) {
473     case ::gig::vcf_cutoff_ctrl_modwheel:
474     VCFCutoffCtrl.controller = 1;
475     break;
476     case ::gig::vcf_cutoff_ctrl_effect1:
477     VCFCutoffCtrl.controller = 12;
478     break;
479     case ::gig::vcf_cutoff_ctrl_effect2:
480     VCFCutoffCtrl.controller = 13;
481     break;
482     case ::gig::vcf_cutoff_ctrl_breath:
483     VCFCutoffCtrl.controller = 2;
484     break;
485     case ::gig::vcf_cutoff_ctrl_foot:
486     VCFCutoffCtrl.controller = 4;
487     break;
488     case ::gig::vcf_cutoff_ctrl_sustainpedal:
489     VCFCutoffCtrl.controller = 64;
490     break;
491     case ::gig::vcf_cutoff_ctrl_softpedal:
492     VCFCutoffCtrl.controller = 67;
493     break;
494     case ::gig::vcf_cutoff_ctrl_genpurpose7:
495     VCFCutoffCtrl.controller = 82;
496     break;
497     case ::gig::vcf_cutoff_ctrl_genpurpose8:
498     VCFCutoffCtrl.controller = 83;
499     break;
500 persson 903 case ::gig::vcf_cutoff_ctrl_aftertouch:
501     VCFCutoffCtrl.controller = 128;
502     break;
503 schoenebeck 53 case ::gig::vcf_cutoff_ctrl_none:
504     default:
505     VCFCutoffCtrl.controller = 0;
506     break;
507     }
508 schoenebeck 554 #endif // CONFIG_OVERRIDE_CUTOFF_CTRL
509 schoenebeck 53
510 schoenebeck 554 #ifdef CONFIG_OVERRIDE_RESONANCE_CTRL
511     VCFResonanceCtrl.controller = CONFIG_OVERRIDE_RESONANCE_CTRL;
512 schoenebeck 53 #else // use the one defined in the instrument file
513     switch (pDimRgn->VCFResonanceController) {
514     case ::gig::vcf_res_ctrl_genpurpose3:
515     VCFResonanceCtrl.controller = 18;
516     break;
517     case ::gig::vcf_res_ctrl_genpurpose4:
518     VCFResonanceCtrl.controller = 19;
519     break;
520     case ::gig::vcf_res_ctrl_genpurpose5:
521     VCFResonanceCtrl.controller = 80;
522     break;
523     case ::gig::vcf_res_ctrl_genpurpose6:
524     VCFResonanceCtrl.controller = 81;
525     break;
526     case ::gig::vcf_res_ctrl_none:
527     default:
528     VCFResonanceCtrl.controller = 0;
529     }
530 schoenebeck 554 #endif // CONFIG_OVERRIDE_RESONANCE_CTRL
531 schoenebeck 53
532 schoenebeck 554 #ifndef CONFIG_OVERRIDE_FILTER_TYPE
533 schoenebeck 770 finalSynthesisParameters.filterLeft.SetType(pDimRgn->VCFType);
534     finalSynthesisParameters.filterRight.SetType(pDimRgn->VCFType);
535 schoenebeck 53 #else // override filter type
536 schoenebeck 1181 finalSynthesisParameters.filterLeft.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
537     finalSynthesisParameters.filterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
538 schoenebeck 554 #endif // CONFIG_OVERRIDE_FILTER_TYPE
539 schoenebeck 53
540 schoenebeck 411 VCFCutoffCtrl.value = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
541     VCFResonanceCtrl.value = pEngineChannel->ControllerTable[VCFResonanceCtrl.controller];
542 schoenebeck 53
543     // calculate cutoff frequency
544 persson 729 float cutoff = pDimRgn->GetVelocityCutoff(itNoteOnEvent->Param.Note.Velocity);
545     if (pDimRgn->VCFKeyboardTracking) {
546     cutoff *= exp((itNoteOnEvent->Param.Note.Key - pDimRgn->VCFKeyboardTrackingBreakpoint) * 0.057762265f); // (ln(2) / 12)
547     }
548     CutoffBase = cutoff;
549 schoenebeck 53
550 persson 729 int cvalue;
551     if (VCFCutoffCtrl.controller) {
552     cvalue = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
553     if (pDimRgn->VCFCutoffControllerInvert) cvalue = 127 - cvalue;
554 persson 791 // VCFVelocityScale in this case means Minimum cutoff
555 persson 729 if (cvalue < pDimRgn->VCFVelocityScale) cvalue = pDimRgn->VCFVelocityScale;
556     }
557     else {
558     cvalue = pDimRgn->VCFCutoff;
559     }
560 persson 877 cutoff *= float(cvalue);
561     if (cutoff > 127.0f) cutoff = 127.0f;
562 persson 729
563 schoenebeck 53 // calculate resonance
564 persson 877 float resonance = (float) (VCFResonanceCtrl.controller ? VCFResonanceCtrl.value : pDimRgn->VCFResonance);
565 schoenebeck 53
566 persson 877 VCFCutoffCtrl.fvalue = cutoff;
567 schoenebeck 53 VCFResonanceCtrl.fvalue = resonance;
568     }
569     else {
570     VCFCutoffCtrl.controller = 0;
571     VCFResonanceCtrl.controller = 0;
572     }
573    
574     return 0; // success
575     }
576    
577     /**
578     * Renders the audio data for this voice for the current audio fragment.
579     * The sample input data can either come from RAM (cached sample or sample
580     * part) or directly from disk. The output signal will be rendered by
581     * resampling / interpolation. If this voice is a disk streaming voice and
582     * the voice completely played back the cached RAM part of the sample, it
583     * will automatically switch to disk playback for the next RenderAudio()
584     * call.
585     *
586     * @param Samples - number of samples to be rendered in this audio fragment cycle
587     */
588     void Voice::Render(uint Samples) {
589    
590 schoenebeck 319 // select default values for synthesis mode bits
591     SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);
592    
593     switch (this->PlaybackState) {
594 schoenebeck 80
595 schoenebeck 563 case playback_state_init:
596     this->PlaybackState = playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed
597     // no break - continue with playback_state_ram
598    
599 schoenebeck 319 case playback_state_ram: {
600     if (RAMLoop) SYNTHESIS_MODE_SET_LOOP(SynthesisMode, true); // enable looping
601 schoenebeck 80
602 schoenebeck 319 // render current fragment
603     Synthesize(Samples, (sample_t*) pSample->GetCache().pStart, Delay);
604 schoenebeck 53
605     if (DiskVoice) {
606     // check if we reached the allowed limit of the sample RAM cache
607 schoenebeck 770 if (finalSynthesisParameters.dPos > MaxRAMPos) {
608     dmsg(5,("Voice: switching to disk playback (Pos=%f)\n", finalSynthesisParameters.dPos));
609 schoenebeck 53 this->PlaybackState = playback_state_disk;
610     }
611 schoenebeck 770 } else if (finalSynthesisParameters.dPos >= pSample->GetCache().Size / pSample->FrameSize) {
612 schoenebeck 53 this->PlaybackState = playback_state_end;
613     }
614     }
615     break;
616    
617     case playback_state_disk: {
618     if (!DiskStreamRef.pStream) {
619     // check if the disk thread created our ordered disk stream in the meantime
620     DiskStreamRef.pStream = pDiskThread->AskForCreatedStream(DiskStreamRef.OrderID);
621     if (!DiskStreamRef.pStream) {
622     std::cout << stderr << "Disk stream not available in time!" << std::endl << std::flush;
623 schoenebeck 239 KillImmediately();
624 schoenebeck 53 return;
625     }
626 schoenebeck 770 DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (int(finalSynthesisParameters.dPos) - MaxRAMPos));
627     finalSynthesisParameters.dPos -= int(finalSynthesisParameters.dPos);
628 schoenebeck 330 RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet
629 schoenebeck 53 }
630    
631 schoenebeck 323 const int sampleWordsLeftToRead = DiskStreamRef.pStream->GetReadSpace();
632    
633 schoenebeck 53 // add silence sample at the end if we reached the end of the stream (for the interpolator)
634 schoenebeck 323 if (DiskStreamRef.State == Stream::state_end) {
635 schoenebeck 554 const int maxSampleWordsPerCycle = (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH) * pSample->Channels + 6; // +6 for the interpolator algorithm
636 schoenebeck 323 if (sampleWordsLeftToRead <= maxSampleWordsPerCycle) {
637 schoenebeck 330 // remember how many sample words there are before any silence has been added
638     if (RealSampleWordsLeftToRead < 0) RealSampleWordsLeftToRead = sampleWordsLeftToRead;
639 schoenebeck 323 DiskStreamRef.pStream->WriteSilence(maxSampleWordsPerCycle - sampleWordsLeftToRead);
640     }
641 schoenebeck 53 }
642    
643 persson 903 sample_t* ptr = (sample_t*)DiskStreamRef.pStream->GetReadPtr(); // get the current read_ptr within the ringbuffer where we read the samples from
644 schoenebeck 319
645     // render current audio fragment
646     Synthesize(Samples, ptr, Delay);
647    
648 schoenebeck 770 const int iPos = (int) finalSynthesisParameters.dPos;
649 schoenebeck 323 const int readSampleWords = iPos * pSample->Channels; // amount of sample words actually been read
650     DiskStreamRef.pStream->IncrementReadPos(readSampleWords);
651 schoenebeck 770 finalSynthesisParameters.dPos -= iPos; // just keep fractional part of playback position
652 schoenebeck 323
653     // change state of voice to 'end' if we really reached the end of the sample data
654 schoenebeck 330 if (RealSampleWordsLeftToRead >= 0) {
655     RealSampleWordsLeftToRead -= readSampleWords;
656     if (RealSampleWordsLeftToRead <= 0) this->PlaybackState = playback_state_end;
657     }
658 schoenebeck 53 }
659     break;
660    
661     case playback_state_end:
662 schoenebeck 285 std::cerr << "gig::Voice::Render(): entered with playback_state_end, this is a bug!\n" << std::flush;
663 schoenebeck 53 break;
664     }
665    
666     // Reset delay
667     Delay = 0;
668    
669 schoenebeck 271 itTriggerEvent = Pool<Event>::Iterator();
670 schoenebeck 53
671 schoenebeck 285 // If sample stream or release stage finished, kill the voice
672 schoenebeck 738 if (PlaybackState == playback_state_end || EG1.getSegmentType() == EGADSR::segment_end) KillImmediately();
673 schoenebeck 53 }
674    
675     /**
676     * Resets voice variables. Should only be called if rendering process is
677     * suspended / not running.
678     */
679     void Voice::Reset() {
680 schoenebeck 770 finalSynthesisParameters.filterLeft.Reset();
681     finalSynthesisParameters.filterRight.Reset();
682 schoenebeck 53 DiskStreamRef.pStream = NULL;
683     DiskStreamRef.hStream = 0;
684     DiskStreamRef.State = Stream::state_unused;
685     DiskStreamRef.OrderID = 0;
686 schoenebeck 285 PlaybackState = playback_state_end;
687     itTriggerEvent = Pool<Event>::Iterator();
688     itKillEvent = Pool<Event>::Iterator();
689 schoenebeck 53 }
690    
691     /**
692 schoenebeck 738 * Process given list of MIDI note on, note off and sustain pedal events
693     * for the given time.
694 schoenebeck 53 *
695 schoenebeck 738 * @param itEvent - iterator pointing to the next event to be processed
696 persson 832 * @param End - youngest time stamp where processing should be stopped
697 schoenebeck 53 */
698 schoenebeck 738 void Voice::processTransitionEvents(RTList<Event>::Iterator& itEvent, uint End) {
699     for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
700     if (itEvent->Type == Event::type_release) {
701 persson 783 EG1.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
702     EG2.update(EGADSR::event_release, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
703 schoenebeck 738 } else if (itEvent->Type == Event::type_cancel_release) {
704 persson 783 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 schoenebeck 738 }
707     }
708     }
709 schoenebeck 53
710 schoenebeck 738 /**
711     * Process given list of MIDI control change and pitch bend events for
712     * the given time.
713     *
714     * @param itEvent - iterator pointing to the next event to be processed
715 persson 832 * @param End - youngest time stamp where processing should be stopped
716 schoenebeck 738 */
717     void Voice::processCCEvents(RTList<Event>::Iterator& itEvent, uint End) {
718     for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
719     if (itEvent->Type == Event::type_control_change &&
720     itEvent->Param.CC.Controller) { // if (valid) MIDI control change event
721     if (itEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {
722     processCutoffEvent(itEvent);
723 schoenebeck 53 }
724 schoenebeck 738 if (itEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {
725     processResonanceEvent(itEvent);
726 schoenebeck 53 }
727 schoenebeck 738 if (itEvent->Param.CC.Controller == pLFO1->ExtController) {
728     pLFO1->update(itEvent->Param.CC.Value);
729 schoenebeck 53 }
730 schoenebeck 738 if (itEvent->Param.CC.Controller == pLFO2->ExtController) {
731     pLFO2->update(itEvent->Param.CC.Value);
732 schoenebeck 53 }
733 schoenebeck 738 if (itEvent->Param.CC.Controller == pLFO3->ExtController) {
734     pLFO3->update(itEvent->Param.CC.Value);
735 schoenebeck 53 }
736 schoenebeck 236 if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&
737 schoenebeck 738 itEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) {
738 persson 832 CrossfadeSmoother.update(Engine::CrossfadeCurve[CrossfadeAttenuation(itEvent->Param.CC.Value)]);
739 schoenebeck 236 }
740 persson 832 if (itEvent->Param.CC.Controller == 7) { // volume
741 schoenebeck 947 VolumeSmoother.update(Engine::VolumeCurve[itEvent->Param.CC.Value]);
742 persson 832 } 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 schoenebeck 738 } else if (itEvent->Type == Event::type_pitchbend) { // if pitch bend event
747     processPitchEvent(itEvent);
748 schoenebeck 53 }
749     }
750 schoenebeck 738 }
751 schoenebeck 53
752 schoenebeck 738 void Voice::processPitchEvent(RTList<Event>::Iterator& itEvent) {
753 persson 1923 PitchBend = RTMath::CentsToFreqRatio(itEvent->Param.Pitch.Pitch * PitchBendRange);
754 schoenebeck 738 }
755 schoenebeck 53
756 schoenebeck 738 void Voice::processCutoffEvent(RTList<Event>::Iterator& itEvent) {
757     int ccvalue = itEvent->Param.CC.Value;
758     if (VCFCutoffCtrl.value == ccvalue) return;
759     VCFCutoffCtrl.value == ccvalue;
760     if (pDimRgn->VCFCutoffControllerInvert) ccvalue = 127 - ccvalue;
761     if (ccvalue < pDimRgn->VCFVelocityScale) ccvalue = pDimRgn->VCFVelocityScale;
762 persson 877 float cutoff = CutoffBase * float(ccvalue);
763     if (cutoff > 127.0f) cutoff = 127.0f;
764 persson 791
765 persson 877 VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of fFinalCutoff next time
766 schoenebeck 738 fFinalCutoff = cutoff;
767     }
768 schoenebeck 53
769 schoenebeck 738 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 persson 877 const float resonancedelta = (float) ctrldelta;
774 schoenebeck 738 fFinalResonance += resonancedelta;
775     // needed for initialization of parameter
776 persson 877 VCFResonanceCtrl.fvalue = itEvent->Param.CC.Value;
777 schoenebeck 738 }
778 schoenebeck 53
779 schoenebeck 738 /**
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 schoenebeck 1001 finalSynthesisParameters.pOutLeft = &pEngineChannel->pChannelLeft->Buffer()[Skip];
789     finalSynthesisParameters.pOutRight = &pEngineChannel->pChannelRight->Buffer()[Skip];
790 schoenebeck 770 finalSynthesisParameters.pSrc = pSrc;
791    
792 schoenebeck 738 RTList<Event>::Iterator itCCEvent = pEngineChannel->pEvents->first();
793     RTList<Event>::Iterator itNoteEvent = pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents->first();
794 persson 768
795 persson 1748 if (itTriggerEvent) { // skip events that happened before this voice was triggered
796 schoenebeck 738 while (itCCEvent && itCCEvent->FragmentPos() <= Skip) ++itCCEvent;
797 schoenebeck 1857 // 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 schoenebeck 53 }
807 persson 768
808 persson 796 uint killPos;
809 persson 1748 if (itKillEvent) {
810     int maxFadeOutPos = Samples - pEngine->MinFadeOutSamples;
811     if (maxFadeOutPos < 0) {
812     // There's not enough space in buffer to do a fade out
813     // from max volume (this can only happen for audio
814     // drivers that use Samples < MaxSamplesPerCycle).
815     // End the EG1 here, at pos 0, with a shorter max fade
816     // out time.
817     EG1.enterFadeOutStage(Samples / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
818     itKillEvent = Pool<Event>::Iterator();
819     } else {
820     killPos = RTMath::Min(itKillEvent->FragmentPos(), maxFadeOutPos);
821     }
822     }
823 persson 796
824 schoenebeck 738 uint i = Skip;
825     while (i < Samples) {
826     int iSubFragmentEnd = RTMath::Min(i + CONFIG_DEFAULT_SUBFRAGMENT_SIZE, Samples);
827 persson 768
828 schoenebeck 738 // initialize all final synthesis parameters
829     fFinalCutoff = VCFCutoffCtrl.fvalue;
830     fFinalResonance = VCFResonanceCtrl.fvalue;
831 persson 768
832 schoenebeck 738 // process MIDI control change and pitchbend events for this subfragment
833     processCCEvents(itCCEvent, iSubFragmentEnd);
834 schoenebeck 53
835 persson 1858 finalSynthesisParameters.fFinalPitch = PitchBase * PitchBend;
836 persson 832 float fFinalVolume = VolumeSmoother.render() * CrossfadeSmoother.render();
837     #ifdef CONFIG_PROCESS_MUTED_CHANNELS
838     if (pEngineChannel->GetMute()) fFinalVolume = 0;
839     #endif
840    
841 schoenebeck 738 // process transition events (note on, note off & sustain pedal)
842     processTransitionEvents(itNoteEvent, iSubFragmentEnd);
843 persson 768
844 persson 950 // 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 persson 796 EG1.enterFadeOutStage();
850     itKillEvent = Pool<Event>::Iterator();
851     }
852    
853 schoenebeck 738 // process envelope generators
854     switch (EG1.getSegmentType()) {
855     case EGADSR::segment_lin:
856     fFinalVolume *= EG1.processLin();
857     break;
858     case EGADSR::segment_exp:
859     fFinalVolume *= EG1.processExp();
860     break;
861     case EGADSR::segment_end:
862     fFinalVolume *= EG1.getLevel();
863     break; // noop
864 schoenebeck 236 }
865 schoenebeck 738 switch (EG2.getSegmentType()) {
866     case EGADSR::segment_lin:
867     fFinalCutoff *= EG2.processLin();
868     break;
869     case EGADSR::segment_exp:
870     fFinalCutoff *= EG2.processExp();
871     break;
872     case EGADSR::segment_end:
873     fFinalCutoff *= EG2.getLevel();
874     break; // noop
875 schoenebeck 236 }
876 schoenebeck 829 if (EG3.active()) finalSynthesisParameters.fFinalPitch *= EG3.render();
877 persson 768
878 schoenebeck 738 // process low frequency oscillators
879 persson 922 if (bLFO1Enabled) fFinalVolume *= (1.0f - pLFO1->render());
880 schoenebeck 738 if (bLFO2Enabled) fFinalCutoff *= pLFO2->render();
881 schoenebeck 770 if (bLFO3Enabled) finalSynthesisParameters.fFinalPitch *= RTMath::CentsToFreqRatio(pLFO3->render());
882 schoenebeck 236
883 persson 1862 // 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 schoenebeck 738 // if filter enabled then update filter coefficients
887     if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode)) {
888 persson 877 finalSynthesisParameters.filterLeft.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
889     finalSynthesisParameters.filterRight.SetParameters(fFinalCutoff, fFinalResonance, pEngine->SampleRate);
890 schoenebeck 53 }
891    
892 schoenebeck 770 // do we need resampling?
893     const float __PLUS_ONE_CENT = 1.000577789506554859250142541782224725466f;
894     const float __MINUS_ONE_CENT = 0.9994225441413807496009516495583113737666f;
895     const bool bResamplingRequired = !(finalSynthesisParameters.fFinalPitch <= __PLUS_ONE_CENT &&
896     finalSynthesisParameters.fFinalPitch >= __MINUS_ONE_CENT);
897     SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, bResamplingRequired);
898 persson 768
899 schoenebeck 770 // prepare final synthesis parameters structure
900 persson 830 finalSynthesisParameters.uiToGo = iSubFragmentEnd - i;
901     #ifdef CONFIG_INTERPOLATE_VOLUME
902     finalSynthesisParameters.fFinalVolumeDeltaLeft =
903 persson 832 (fFinalVolume * VolumeLeft * PanLeftSmoother.render() -
904     finalSynthesisParameters.fFinalVolumeLeft) / finalSynthesisParameters.uiToGo;
905 persson 830 finalSynthesisParameters.fFinalVolumeDeltaRight =
906 persson 832 (fFinalVolume * VolumeRight * PanRightSmoother.render() -
907     finalSynthesisParameters.fFinalVolumeRight) / finalSynthesisParameters.uiToGo;
908 persson 830 #else
909 persson 832 finalSynthesisParameters.fFinalVolumeLeft =
910     fFinalVolume * VolumeLeft * PanLeftSmoother.render();
911     finalSynthesisParameters.fFinalVolumeRight =
912     fFinalVolume * VolumeRight * PanRightSmoother.render();
913 persson 830 #endif
914 schoenebeck 738 // render audio for one subfragment
915 schoenebeck 770 RunSynthesisFunction(SynthesisMode, &finalSynthesisParameters, &loop);
916 schoenebeck 53
917 persson 830 // stop the rendering if volume EG is finished
918     if (EG1.getSegmentType() == EGADSR::segment_end) break;
919    
920 persson 783 const double newPos = Pos + (iSubFragmentEnd - i) * finalSynthesisParameters.fFinalPitch;
921    
922 persson 768 // increment envelopes' positions
923 schoenebeck 738 if (EG1.active()) {
924 persson 783
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 persson 865 if (pDimRgn->SampleLoops && Pos <= pDimRgn->pSampleLoops[0].LoopStart && pDimRgn->pSampleLoops[0].LoopStart < newPos) {
927 persson 783 EG1.update(EGADSR::event_hold_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
928     }
929    
930 persson 768 EG1.increment(1);
931 persson 783 if (!EG1.toStageEndLeft()) EG1.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
932 schoenebeck 53 }
933 schoenebeck 738 if (EG2.active()) {
934 persson 768 EG2.increment(1);
935 persson 783 if (!EG2.toStageEndLeft()) EG2.update(EGADSR::event_stage_end, pEngine->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
936 schoenebeck 53 }
937 persson 768 EG3.increment(1);
938 schoenebeck 738 if (!EG3.toEndLeft()) EG3.update(); // neutralize envelope coefficient if end reached
939 persson 768
940 persson 783 Pos = newPos;
941 persson 768 i = iSubFragmentEnd;
942 schoenebeck 53 }
943     }
944    
945 schoenebeck 829 /** @brief Update current portamento position.
946     *
947     * Will be called when portamento mode is enabled to get the final
948     * portamento position of this active voice from where the next voice(s)
949     * might continue to slide on.
950     *
951     * @param itNoteOffEvent - event which causes this voice to die soon
952     */
953     void Voice::UpdatePortamentoPos(Pool<Event>::Iterator& itNoteOffEvent) {
954     const float fFinalEG3Level = EG3.level(itNoteOffEvent->FragmentPos());
955     pEngineChannel->PortamentoPos = (float) MIDIKey + RTMath::FreqRatioToCents(fFinalEG3Level) * 0.01f;
956     }
957    
958 schoenebeck 53 /**
959 schoenebeck 239 * Immediately kill the voice. This method should not be used to kill
960     * a normal, active voice, because it doesn't take care of things like
961     * fading down the volume level to avoid clicks and regular processing
962     * until the kill event actually occured!
963     *
964 schoenebeck 1321 * 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 schoenebeck 53 */
980 schoenebeck 1321 Stream::Handle Voice::KillImmediately(bool bRequestNotification) {
981     Stream::Handle hStream = Stream::INVALID_HANDLE;
982 schoenebeck 53 if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
983 schoenebeck 1321 pDiskThread->OrderDeletionOfStream(&DiskStreamRef, bRequestNotification);
984     hStream = DiskStreamRef.hStream;
985 schoenebeck 53 }
986     Reset();
987 schoenebeck 1321 return hStream;
988 schoenebeck 53 }
989    
990 schoenebeck 239 /**
991     * Kill the voice in regular sense. Let the voice render audio until
992     * the kill event actually occured and then fade down the volume level
993     * very quickly and let the voice die finally. Unlike a normal release
994     * of a voice, a kill process cannot be cancalled and is therefore
995     * usually used for voice stealing and key group conflicts.
996     *
997 schoenebeck 271 * @param itKillEvent - event which caused the voice to be killed
998 schoenebeck 239 */
999 schoenebeck 271 void Voice::Kill(Pool<Event>::Iterator& itKillEvent) {
1000 schoenebeck 554 #if CONFIG_DEVMODE
1001 schoenebeck 287 if (!itKillEvent) dmsg(1,("gig::Voice::Kill(): ERROR, !itKillEvent !!!\n"));
1002     if (itKillEvent && !itKillEvent.isValid()) dmsg(1,("gig::Voice::Kill(): ERROR, itKillEvent invalid !!!\n"));
1003 schoenebeck 554 #endif // CONFIG_DEVMODE
1004 schoenebeck 287
1005 schoenebeck 271 if (itTriggerEvent && itKillEvent->FragmentPos() <= itTriggerEvent->FragmentPos()) return;
1006     this->itKillEvent = itKillEvent;
1007 schoenebeck 239 }
1008    
1009 schoenebeck 53 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC