/[svn]/linuxsampler/trunk/src/engines/common/AbstractVoice.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/engines/common/AbstractVoice.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2061 - (hide annotations) (download)
Tue Feb 23 18:32:31 2010 UTC (14 years, 1 month ago) by persson
File size: 29819 byte(s)
* sfz engine: added support for trigger=release and rt_decay

1 iliev 2015 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck *
6 persson 2045 * Copyright (C) 2005-2008 Christian Schoenebeck *
7     * Copyright (C) 2009-2010 Christian Schoenebeck and Grigor Iliev *
8 iliev 2015 * *
9     * This program is free software; you can redistribute it and/or modify *
10     * it under the terms of the GNU General Public License as published by *
11     * the Free Software Foundation; either version 2 of the License, or *
12     * (at your option) any later version. *
13     * *
14     * This program is distributed in the hope that it will be useful, *
15     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17     * GNU General Public License for more details. *
18     * *
19     * You should have received a copy of the GNU General Public License *
20     * along with this program; if not, write to the Free Software *
21     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
22     * MA 02111-1307 USA *
23     ***************************************************************************/
24    
25     #include "AbstractVoice.h"
26    
27     namespace LinuxSampler {
28    
29     AbstractVoice::AbstractVoice() {
30     pEngineChannel = NULL;
31     pLFO1 = new LFOUnsigned(1.0f); // amplitude EG (0..1 range)
32     pLFO2 = new LFOUnsigned(1.0f); // filter EG (0..1 range)
33     pLFO3 = new LFOSigned(1200.0f); // pitch EG (-1200..+1200 range)
34     PlaybackState = playback_state_end;
35     KeyGroup = 0;
36     SynthesisMode = 0; // set all mode bits to 0 first
37     // select synthesis implementation (asm core is not supported ATM)
38     #if 0 // CONFIG_ASM && ARCH_X86
39     SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
40     #else
41     SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);
42     #endif
43     SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, gig::Profiler::isEnabled());
44    
45     finalSynthesisParameters.filterLeft.Reset();
46     finalSynthesisParameters.filterRight.Reset();
47     }
48    
49     AbstractVoice::~AbstractVoice() {
50     if (pLFO1) delete pLFO1;
51     if (pLFO2) delete pLFO2;
52     if (pLFO3) delete pLFO3;
53     }
54 persson 2045
55 iliev 2015 /**
56     * Resets voice variables. Should only be called if rendering process is
57     * suspended / not running.
58     */
59     void AbstractVoice::Reset() {
60     finalSynthesisParameters.filterLeft.Reset();
61     finalSynthesisParameters.filterRight.Reset();
62     DiskStreamRef.pStream = NULL;
63     DiskStreamRef.hStream = 0;
64     DiskStreamRef.State = Stream::state_unused;
65     DiskStreamRef.OrderID = 0;
66     PlaybackState = playback_state_end;
67     itTriggerEvent = Pool<Event>::Iterator();
68     itKillEvent = Pool<Event>::Iterator();
69     }
70    
71     /**
72     * Initializes and triggers the voice, a disk stream will be launched if
73     * needed.
74     *
75     * @param pEngineChannel - engine channel on which this voice was ordered
76     * @param itNoteOnEvent - event that caused triggering of this voice
77     * @param PitchBend - MIDI detune factor (-8192 ... +8191)
78     * @param pRegion- points to the region which provides sample wave(s) and articulation data
79     * @param VoiceType - type of this voice
80     * @param iKeyGroup - a value > 0 defines a key group in which this voice is member of
81     * @returns 0 on success, a value < 0 if the voice wasn't triggered
82     * (either due to an error or e.g. because no region is
83     * defined for the given key)
84     */
85     int AbstractVoice::Trigger (
86     AbstractEngineChannel* pEngineChannel,
87     Pool<Event>::Iterator& itNoteOnEvent,
88     int PitchBend,
89     type_t VoiceType,
90     int iKeyGroup
91     ) {
92     this->pEngineChannel = pEngineChannel;
93     Orphan = false;
94    
95     #if CONFIG_DEVMODE
96     if (itNoteOnEvent->FragmentPos() > GetEngine()->MaxSamplesPerCycle) { // just a sanity check for debugging
97     dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
98     }
99     #endif // CONFIG_DEVMODE
100    
101     Type = VoiceType;
102     MIDIKey = itNoteOnEvent->Param.Note.Key;
103     PlaybackState = playback_state_init; // mark voice as triggered, but no audio rendered yet
104     Delay = itNoteOnEvent->FragmentPos();
105     itTriggerEvent = itNoteOnEvent;
106     itKillEvent = Pool<Event>::Iterator();
107     KeyGroup = iKeyGroup;
108    
109     SmplInfo = GetSampleInfo();
110     RgnInfo = GetRegionInfo();
111     InstrInfo = GetInstrumentInfo();
112    
113     // calculate volume
114     const double velocityAttenuation = GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
115     float volume = CalculateVolume(velocityAttenuation);
116 persson 2032 if (volume <= 0) return -1;
117 iliev 2015
118     // select channel mode (mono or stereo)
119     SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, SmplInfo.ChannelCount == 2);
120     // select bit depth (16 or 24)
121     SYNTHESIS_MODE_SET_BITDEPTH24(SynthesisMode, SmplInfo.BitDepth == 24);
122    
123     // get starting crossfade volume level
124     float crossfadeVolume = CalculateCrossfadeVolume(itNoteOnEvent->Param.Note.Velocity);
125    
126     VolumeLeft = volume * AbstractEngine::PanCurve[64 - RgnInfo.Pan];
127     VolumeRight = volume * AbstractEngine::PanCurve[64 + RgnInfo.Pan];
128    
129     float subfragmentRate = GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE;
130     CrossfadeSmoother.trigger(crossfadeVolume, subfragmentRate);
131     VolumeSmoother.trigger(pEngineChannel->MidiVolume, subfragmentRate);
132     PanLeftSmoother.trigger(pEngineChannel->GlobalPanLeft, subfragmentRate);
133     PanRightSmoother.trigger(pEngineChannel->GlobalPanRight, subfragmentRate);
134    
135     finalSynthesisParameters.dPos = RgnInfo.SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)
136     Pos = RgnInfo.SampleStartOffset;
137    
138     // Check if the sample needs disk streaming or is too short for that
139     long cachedsamples = GetSampleCacheSize() / SmplInfo.FrameSize;
140     DiskVoice = cachedsamples < SmplInfo.TotalFrameCount;
141    
142     if (DiskVoice) { // voice to be streamed from disk
143     if (cachedsamples > (GetEngine()->MaxSamplesPerCycle << CONFIG_MAX_PITCH)) {
144     MaxRAMPos = cachedsamples - (GetEngine()->MaxSamplesPerCycle << CONFIG_MAX_PITCH) / SmplInfo.ChannelCount; //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)
145     } else {
146     // The cache is too small to fit a max sample buffer.
147     // Setting MaxRAMPos to 0 will probably cause a click
148     // in the audio, but it's better than not handling
149     // this case at all, which would have caused the
150     // unsigned MaxRAMPos to be set to a negative number.
151     MaxRAMPos = 0;
152     }
153    
154     // check if there's a loop defined which completely fits into the cached (RAM) part of the sample
155     RAMLoop = (SmplInfo.HasLoops && (SmplInfo.LoopStart + SmplInfo.LoopLength) <= MaxRAMPos);
156    
157     if (OrderNewStream()) return -1;
158     dmsg(4,("Disk voice launched (cached samples: %d, total Samples: %d, MaxRAMPos: %d, RAMLooping: %s)\n", cachedsamples, SmplInfo.TotalFrameCount, MaxRAMPos, (RAMLoop) ? "yes" : "no"));
159     }
160     else { // RAM only voice
161     MaxRAMPos = cachedsamples;
162     RAMLoop = (SmplInfo.HasLoops);
163     dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));
164     }
165     if (RAMLoop) {
166     loop.uiTotalCycles = SmplInfo.LoopPlayCount;
167     loop.uiCyclesLeft = SmplInfo.LoopPlayCount;
168     loop.uiStart = SmplInfo.LoopStart;
169     loop.uiEnd = SmplInfo.LoopStart + SmplInfo.LoopLength;
170     loop.uiSize = SmplInfo.LoopLength;
171     }
172    
173     Pitch = CalculatePitchInfo(PitchBend);
174    
175     // the length of the decay and release curves are dependent on the velocity
176     const double velrelease = 1 / GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);
177    
178     // setup EG 1 (VCA EG)
179     {
180     // get current value of EG1 controller
181     double eg1controllervalue = GetEG1ControllerValue(itNoteOnEvent->Param.Note.Velocity);
182    
183     // calculate influence of EG1 controller on EG1's parameters
184     EGInfo egInfo = CalculateEG1ControllerInfluence(eg1controllervalue);
185    
186 persson 2055 TriggerEG1(egInfo, velrelease, velocityAttenuation, GetEngine()->SampleRate, itNoteOnEvent->Param.Note.Velocity);
187 iliev 2015 }
188    
189     #ifdef CONFIG_INTERPOLATE_VOLUME
190     // setup initial volume in synthesis parameters
191     #ifdef CONFIG_PROCESS_MUTED_CHANNELS
192     if (pEngineChannel->GetMute()) {
193     finalSynthesisParameters.fFinalVolumeLeft = 0;
194     finalSynthesisParameters.fFinalVolumeRight = 0;
195     }
196     else
197     #else
198     {
199 persson 2055 float finalVolume = pEngineChannel->MidiVolume * crossfadeVolume * pEG1->getLevel();
200 iliev 2015
201     finalSynthesisParameters.fFinalVolumeLeft = finalVolume * VolumeLeft * pEngineChannel->GlobalPanLeft;
202     finalSynthesisParameters.fFinalVolumeRight = finalVolume * VolumeRight * pEngineChannel->GlobalPanRight;
203     }
204     #endif
205     #endif
206    
207     // setup EG 2 (VCF Cutoff EG)
208     {
209     // get current value of EG2 controller
210     double eg2controllervalue = GetEG2ControllerValue(itNoteOnEvent->Param.Note.Velocity);
211    
212     // calculate influence of EG2 controller on EG2's parameters
213     EGInfo egInfo = CalculateEG2ControllerInfluence(eg2controllervalue);
214    
215     EG2.trigger (
216 persson 2045 uint(RgnInfo.EG2PreAttack),
217 iliev 2015 RgnInfo.EG2Attack * egInfo.Attack,
218     false,
219     RgnInfo.EG2Decay1 * egInfo.Decay * velrelease,
220     RgnInfo.EG2Decay2 * egInfo.Decay * velrelease,
221     RgnInfo.EG2InfiniteSustain,
222 persson 2045 uint(RgnInfo.EG2Sustain),
223 iliev 2015 RgnInfo.EG2Release * egInfo.Release * velrelease,
224     velocityAttenuation,
225     GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE
226     );
227     }
228    
229    
230     // setup EG 3 (VCO EG)
231     {
232     // if portamento mode is on, we dedicate EG3 purely for portamento, otherwise if portamento is off we do as told by the patch
233     bool bPortamento = pEngineChannel->PortamentoMode && pEngineChannel->PortamentoPos >= 0.0f;
234     float eg3depth = (bPortamento)
235     ? RTMath::CentsToFreqRatio((pEngineChannel->PortamentoPos - (float) MIDIKey) * 100)
236     : RTMath::CentsToFreqRatio(RgnInfo.EG3Depth);
237     float eg3time = (bPortamento)
238     ? pEngineChannel->PortamentoTime
239     : RgnInfo.EG3Attack;
240     EG3.trigger(eg3depth, eg3time, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
241     dmsg(5,("PortamentoPos=%f, depth=%f, time=%f\n", pEngineChannel->PortamentoPos, eg3depth, eg3time));
242     }
243    
244    
245     // setup LFO 1 (VCA LFO)
246     InitLFO1();
247     // setup LFO 2 (VCF Cutoff LFO)
248     InitLFO2();
249     // setup LFO 3 (VCO LFO)
250     InitLFO3();
251    
252    
253     #if CONFIG_FORCE_FILTER
254     const bool bUseFilter = true;
255     #else // use filter only if instrument file told so
256     const bool bUseFilter = RgnInfo.VCFEnabled;
257     #endif // CONFIG_FORCE_FILTER
258     SYNTHESIS_MODE_SET_FILTER(SynthesisMode, bUseFilter);
259     if (bUseFilter) {
260     #ifdef CONFIG_OVERRIDE_CUTOFF_CTRL
261     VCFCutoffCtrl.controller = CONFIG_OVERRIDE_CUTOFF_CTRL;
262     #else // use the one defined in the instrument file
263     VCFCutoffCtrl.controller = GetVCFCutoffCtrl();
264     #endif // CONFIG_OVERRIDE_CUTOFF_CTRL
265    
266     #ifdef CONFIG_OVERRIDE_RESONANCE_CTRL
267     VCFResonanceCtrl.controller = CONFIG_OVERRIDE_RESONANCE_CTRL;
268     #else // use the one defined in the instrument file
269     VCFResonanceCtrl.controller = GetVCFResonanceCtrl();
270     #endif // CONFIG_OVERRIDE_RESONANCE_CTRL
271    
272     #ifndef CONFIG_OVERRIDE_FILTER_TYPE
273     finalSynthesisParameters.filterLeft.SetType(RgnInfo.VCFType);
274     finalSynthesisParameters.filterRight.SetType(RgnInfo.VCFType);
275     #else // override filter type
276     finalSynthesisParameters.filterLeft.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
277     finalSynthesisParameters.filterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
278     #endif // CONFIG_OVERRIDE_FILTER_TYPE
279    
280     VCFCutoffCtrl.value = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
281     VCFResonanceCtrl.value = pEngineChannel->ControllerTable[VCFResonanceCtrl.controller];
282    
283     // calculate cutoff frequency
284     CutoffBase = CalculateCutoffBase(itNoteOnEvent->Param.Note.Velocity);
285    
286     VCFCutoffCtrl.fvalue = CalculateFinalCutoff(CutoffBase);
287    
288     // calculate resonance
289     float resonance = (float) (VCFResonanceCtrl.controller ? VCFResonanceCtrl.value : RgnInfo.VCFResonance);
290     VCFResonanceCtrl.fvalue = resonance;
291     } else {
292     VCFCutoffCtrl.controller = 0;
293     VCFResonanceCtrl.controller = 0;
294     }
295    
296     return 0; // success
297     }
298    
299     /**
300     * Synthesizes the current audio fragment for this voice.
301     *
302     * @param Samples - number of sample points to be rendered in this audio
303     * fragment cycle
304     * @param pSrc - pointer to input sample data
305     * @param Skip - number of sample points to skip in output buffer
306     */
307     void AbstractVoice::Synthesize(uint Samples, sample_t* pSrc, uint Skip) {
308     AbstractEngineChannel* pChannel = pEngineChannel;
309     finalSynthesisParameters.pOutLeft = &pChannel->pChannelLeft->Buffer()[Skip];
310     finalSynthesisParameters.pOutRight = &pChannel->pChannelRight->Buffer()[Skip];
311     finalSynthesisParameters.pSrc = pSrc;
312    
313     RTList<Event>::Iterator itCCEvent = pChannel->pEvents->first();
314     RTList<Event>::Iterator itNoteEvent;
315     GetFirstEventOnKey(MIDIKey, itNoteEvent);
316    
317     if (itTriggerEvent) { // skip events that happened before this voice was triggered
318     while (itCCEvent && itCCEvent->FragmentPos() <= Skip) ++itCCEvent;
319     // we can't simply compare the timestamp here, because note events
320     // might happen on the same time stamp, so we have to deal on the
321     // actual sequence the note events arrived instead (see bug #112)
322     for (; itNoteEvent; ++itNoteEvent) {
323     if (itTriggerEvent == itNoteEvent) {
324     ++itNoteEvent;
325     break;
326     }
327     }
328     }
329    
330     uint killPos;
331     if (itKillEvent) {
332     int maxFadeOutPos = Samples - GetEngine()->GetMinFadeOutSamples();
333     if (maxFadeOutPos < 0) {
334     // There's not enough space in buffer to do a fade out
335     // from max volume (this can only happen for audio
336     // drivers that use Samples < MaxSamplesPerCycle).
337     // End the EG1 here, at pos 0, with a shorter max fade
338     // out time.
339 persson 2055 pEG1->enterFadeOutStage(Samples / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
340 iliev 2015 itKillEvent = Pool<Event>::Iterator();
341     } else {
342     killPos = RTMath::Min(itKillEvent->FragmentPos(), maxFadeOutPos);
343     }
344     }
345    
346     uint i = Skip;
347     while (i < Samples) {
348     int iSubFragmentEnd = RTMath::Min(i + CONFIG_DEFAULT_SUBFRAGMENT_SIZE, Samples);
349    
350     // initialize all final synthesis parameters
351     fFinalCutoff = VCFCutoffCtrl.fvalue;
352     fFinalResonance = VCFResonanceCtrl.fvalue;
353    
354     // process MIDI control change and pitchbend events for this subfragment
355     processCCEvents(itCCEvent, iSubFragmentEnd);
356    
357     finalSynthesisParameters.fFinalPitch = Pitch.PitchBase * Pitch.PitchBend;
358     float fFinalVolume = VolumeSmoother.render() * CrossfadeSmoother.render();
359     #ifdef CONFIG_PROCESS_MUTED_CHANNELS
360     if (pChannel->GetMute()) fFinalVolume = 0;
361     #endif
362    
363     // process transition events (note on, note off & sustain pedal)
364     processTransitionEvents(itNoteEvent, iSubFragmentEnd);
365    
366     // if the voice was killed in this subfragment, or if the
367     // filter EG is finished, switch EG1 to fade out stage
368     if ((itKillEvent && killPos <= iSubFragmentEnd) ||
369     (SYNTHESIS_MODE_GET_FILTER(SynthesisMode) &&
370     EG2.getSegmentType() == gig::EGADSR::segment_end)) {
371 persson 2055 pEG1->enterFadeOutStage();
372 iliev 2015 itKillEvent = Pool<Event>::Iterator();
373     }
374    
375     // process envelope generators
376 persson 2055 switch (pEG1->getSegmentType()) {
377     case EG::segment_lin:
378     fFinalVolume *= pEG1->processLin();
379 iliev 2015 break;
380 persson 2055 case EG::segment_exp:
381     fFinalVolume *= pEG1->processExp();
382 iliev 2015 break;
383 persson 2055 case EG::segment_end:
384     fFinalVolume *= pEG1->getLevel();
385 iliev 2015 break; // noop
386 persson 2055 case EG::segment_pow:
387     fFinalVolume *= pEG1->processPow();
388     break;
389 iliev 2015 }
390     switch (EG2.getSegmentType()) {
391     case gig::EGADSR::segment_lin:
392     fFinalCutoff *= EG2.processLin();
393     break;
394     case gig::EGADSR::segment_exp:
395     fFinalCutoff *= EG2.processExp();
396     break;
397     case gig::EGADSR::segment_end:
398     fFinalCutoff *= EG2.getLevel();
399     break; // noop
400     }
401     if (EG3.active()) finalSynthesisParameters.fFinalPitch *= EG3.render();
402    
403     // process low frequency oscillators
404     if (bLFO1Enabled) fFinalVolume *= (1.0f - pLFO1->render());
405     if (bLFO2Enabled) fFinalCutoff *= pLFO2->render();
406     if (bLFO3Enabled) finalSynthesisParameters.fFinalPitch *= RTMath::CentsToFreqRatio(pLFO3->render());
407    
408     // limit the pitch so we don't read outside the buffer
409     finalSynthesisParameters.fFinalPitch = RTMath::Min(finalSynthesisParameters.fFinalPitch, float(1 << CONFIG_MAX_PITCH));
410    
411     // if filter enabled then update filter coefficients
412     if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode)) {
413     finalSynthesisParameters.filterLeft.SetParameters(fFinalCutoff, fFinalResonance, GetEngine()->SampleRate);
414     finalSynthesisParameters.filterRight.SetParameters(fFinalCutoff, fFinalResonance, GetEngine()->SampleRate);
415     }
416    
417     // do we need resampling?
418     const float __PLUS_ONE_CENT = 1.000577789506554859250142541782224725466f;
419     const float __MINUS_ONE_CENT = 0.9994225441413807496009516495583113737666f;
420     const bool bResamplingRequired = !(finalSynthesisParameters.fFinalPitch <= __PLUS_ONE_CENT &&
421     finalSynthesisParameters.fFinalPitch >= __MINUS_ONE_CENT);
422     SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, bResamplingRequired);
423    
424     // prepare final synthesis parameters structure
425     finalSynthesisParameters.uiToGo = iSubFragmentEnd - i;
426     #ifdef CONFIG_INTERPOLATE_VOLUME
427     finalSynthesisParameters.fFinalVolumeDeltaLeft =
428     (fFinalVolume * VolumeLeft * PanLeftSmoother.render() -
429     finalSynthesisParameters.fFinalVolumeLeft) / finalSynthesisParameters.uiToGo;
430     finalSynthesisParameters.fFinalVolumeDeltaRight =
431     (fFinalVolume * VolumeRight * PanRightSmoother.render() -
432     finalSynthesisParameters.fFinalVolumeRight) / finalSynthesisParameters.uiToGo;
433     #else
434     finalSynthesisParameters.fFinalVolumeLeft =
435     fFinalVolume * VolumeLeft * PanLeftSmoother.render();
436     finalSynthesisParameters.fFinalVolumeRight =
437     fFinalVolume * VolumeRight * PanRightSmoother.render();
438     #endif
439     // render audio for one subfragment
440     RunSynthesisFunction(SynthesisMode, &finalSynthesisParameters, &loop);
441    
442     // stop the rendering if volume EG is finished
443 persson 2055 if (pEG1->getSegmentType() == EG::segment_end) break;
444 iliev 2015
445     const double newPos = Pos + (iSubFragmentEnd - i) * finalSynthesisParameters.fFinalPitch;
446    
447     // increment envelopes' positions
448 persson 2055 if (pEG1->active()) {
449 iliev 2015
450     // 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
451     if (SmplInfo.HasLoops && Pos <= SmplInfo.LoopStart && SmplInfo.LoopStart < newPos) {
452 persson 2055 pEG1->update(EG::event_hold_end, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
453 iliev 2015 }
454    
455 persson 2055 pEG1->increment(1);
456     if (!pEG1->toStageEndLeft()) pEG1->update(EG::event_stage_end, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
457 iliev 2015 }
458     if (EG2.active()) {
459     EG2.increment(1);
460     if (!EG2.toStageEndLeft()) EG2.update(gig::EGADSR::event_stage_end, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
461     }
462     EG3.increment(1);
463     if (!EG3.toEndLeft()) EG3.update(); // neutralize envelope coefficient if end reached
464    
465     Pos = newPos;
466     i = iSubFragmentEnd;
467     }
468     }
469 persson 2045
470 iliev 2015 /**
471     * Process given list of MIDI control change and pitch bend events for
472     * the given time.
473     *
474     * @param itEvent - iterator pointing to the next event to be processed
475     * @param End - youngest time stamp where processing should be stopped
476     */
477     void AbstractVoice::processCCEvents(RTList<Event>::Iterator& itEvent, uint End) {
478     for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
479     if (itEvent->Type == Event::type_control_change && itEvent->Param.CC.Controller) { // if (valid) MIDI control change event
480     if (itEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {
481     ProcessCutoffEvent(itEvent);
482     }
483     if (itEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {
484     processResonanceEvent(itEvent);
485     }
486     if (itEvent->Param.CC.Controller == pLFO1->ExtController) {
487     pLFO1->update(itEvent->Param.CC.Value);
488     }
489     if (itEvent->Param.CC.Controller == pLFO2->ExtController) {
490     pLFO2->update(itEvent->Param.CC.Value);
491     }
492     if (itEvent->Param.CC.Controller == pLFO3->ExtController) {
493     pLFO3->update(itEvent->Param.CC.Value);
494     }
495     if (itEvent->Param.CC.Controller == 7) { // volume
496     VolumeSmoother.update(AbstractEngine::VolumeCurve[itEvent->Param.CC.Value]);
497     } else if (itEvent->Param.CC.Controller == 10) { // panpot
498     PanLeftSmoother.update(AbstractEngine::PanCurve[128 - itEvent->Param.CC.Value]);
499     PanRightSmoother.update(AbstractEngine::PanCurve[itEvent->Param.CC.Value]);
500     }
501     } else if (itEvent->Type == Event::type_pitchbend) { // if pitch bend event
502     processPitchEvent(itEvent);
503     }
504    
505     ProcessCCEvent(itEvent);
506     }
507     }
508    
509     void AbstractVoice::processPitchEvent(RTList<Event>::Iterator& itEvent) {
510     Pitch.PitchBend = RTMath::CentsToFreqRatio(itEvent->Param.Pitch.Pitch * Pitch.PitchBendRange);
511     }
512    
513     void AbstractVoice::processResonanceEvent(RTList<Event>::Iterator& itEvent) {
514     // convert absolute controller value to differential
515     const int ctrldelta = itEvent->Param.CC.Value - VCFResonanceCtrl.value;
516     VCFResonanceCtrl.value = itEvent->Param.CC.Value;
517     const float resonancedelta = (float) ctrldelta;
518     fFinalResonance += resonancedelta;
519     // needed for initialization of parameter
520     VCFResonanceCtrl.fvalue = itEvent->Param.CC.Value;
521     }
522    
523     /**
524     * Process given list of MIDI note on, note off and sustain pedal events
525     * for the given time.
526     *
527     * @param itEvent - iterator pointing to the next event to be processed
528     * @param End - youngest time stamp where processing should be stopped
529     */
530     void AbstractVoice::processTransitionEvents(RTList<Event>::Iterator& itEvent, uint End) {
531     for (; itEvent && itEvent->FragmentPos() <= End; ++itEvent) {
532     if (itEvent->Type == Event::type_release) {
533 persson 2055 pEG1->update(EG::event_release, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
534 iliev 2015 EG2.update(gig::EGADSR::event_release, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
535     } else if (itEvent->Type == Event::type_cancel_release) {
536 persson 2055 pEG1->update(EG::event_cancel_release, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
537 iliev 2015 EG2.update(gig::EGADSR::event_cancel_release, GetEngine()->SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE);
538     }
539     }
540     }
541    
542     /** @brief Update current portamento position.
543     *
544     * Will be called when portamento mode is enabled to get the final
545     * portamento position of this active voice from where the next voice(s)
546     * might continue to slide on.
547     *
548     * @param itNoteOffEvent - event which causes this voice to die soon
549     */
550     void AbstractVoice::UpdatePortamentoPos(Pool<Event>::Iterator& itNoteOffEvent) {
551     const float fFinalEG3Level = EG3.level(itNoteOffEvent->FragmentPos());
552     pEngineChannel->PortamentoPos = (float) MIDIKey + RTMath::FreqRatioToCents(fFinalEG3Level) * 0.01f;
553     }
554    
555     /**
556     * Kill the voice in regular sense. Let the voice render audio until
557     * the kill event actually occured and then fade down the volume level
558     * very quickly and let the voice die finally. Unlike a normal release
559     * of a voice, a kill process cannot be cancalled and is therefore
560     * usually used for voice stealing and key group conflicts.
561     *
562     * @param itKillEvent - event which caused the voice to be killed
563     */
564     void AbstractVoice::Kill(Pool<Event>::Iterator& itKillEvent) {
565     #if CONFIG_DEVMODE
566     if (!itKillEvent) dmsg(1,("AbstractVoice::Kill(): ERROR, !itKillEvent !!!\n"));
567     if (itKillEvent && !itKillEvent.isValid()) dmsg(1,("AbstractVoice::Kill(): ERROR, itKillEvent invalid !!!\n"));
568     #endif // CONFIG_DEVMODE
569    
570     if (itTriggerEvent && itKillEvent->FragmentPos() <= itTriggerEvent->FragmentPos()) return;
571     this->itKillEvent = itKillEvent;
572     }
573    
574     Voice::PitchInfo AbstractVoice::CalculatePitchInfo(int PitchBend) {
575     PitchInfo pitch;
576     double pitchbasecents = InstrInfo.FineTune + RgnInfo.FineTune + GetEngine()->ScaleTuning[MIDIKey % 12];
577    
578     // GSt behaviour: maximum transpose up is 40 semitones. If
579     // MIDI key is more than 40 semitones above unity note,
580     // the transpose is not done.
581     if (!SmplInfo.Unpitched && (MIDIKey - (int) RgnInfo.UnityNote) < 40) pitchbasecents += (MIDIKey - (int) RgnInfo.UnityNote) * 100;
582    
583     pitch.PitchBase = RTMath::CentsToFreqRatioUnlimited(pitchbasecents) * (double(SmplInfo.SampleRate) / double(GetEngine()->SampleRate));
584     pitch.PitchBendRange = 1.0 / 8192.0 * 100.0 * InstrInfo.PitchbendRange;
585     pitch.PitchBend = RTMath::CentsToFreqRatio(PitchBend * pitch.PitchBendRange);
586    
587     return pitch;
588     }
589    
590     double AbstractVoice::CalculateVolume(double velocityAttenuation) {
591     // For 16 bit samples, we downscale by 32768 to convert from
592     // int16 value range to DSP value range (which is
593     // -1.0..1.0). For 24 bit, we downscale from int32.
594     float volume = velocityAttenuation / (SmplInfo.BitDepth == 16 ? 32768.0f : 32768.0f * 65536.0f);
595    
596     volume *= GetSampleAttenuation() * pEngineChannel->GlobalVolume * GLOBAL_VOLUME;
597    
598     // the volume of release triggered samples depends on note length
599     if (Type == Voice::type_release_trigger) {
600     float noteLength = float(GetEngine()->FrameTime + Delay -
601     GetNoteOnTime(MIDIKey) ) / GetEngine()->SampleRate;
602    
603 persson 2061 volume *= GetReleaseTriggerAttenuation(noteLength);
604 iliev 2015 }
605    
606     return volume;
607     }
608 persson 2061
609     float AbstractVoice::GetReleaseTriggerAttenuation(float noteLength) {
610     return 1 - RgnInfo.ReleaseTriggerDecay * noteLength;
611     }
612 iliev 2015 } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC