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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 669 - (show annotations) (download)
Tue Jun 21 13:33:19 2005 UTC (18 years, 10 months ago) by schoenebeck
File size: 46441 byte(s)
* fixed minor issue with null/silence samples
  (those stole voices even though they don't need a voice at all which
  resulted in "voice stealing didn't work out" messages)

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005 Christian Schoenebeck *
7 * *
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 #include "EGADSR.h"
25 #include "Manipulator.h"
26 #include "../../common/Features.h"
27 #include "Synthesizer.h"
28
29 #include "Voice.h"
30
31 namespace LinuxSampler { namespace gig {
32
33 const float Voice::FILTER_CUTOFF_COEFF(CalculateFilterCutoffCoeff());
34
35 const int Voice::FILTER_UPDATE_MASK(CalculateFilterUpdateMask());
36
37 float Voice::CalculateFilterCutoffCoeff() {
38 return log(CONFIG_FILTER_CUTOFF_MIN / CONFIG_FILTER_CUTOFF_MAX);
39 }
40
41 int Voice::CalculateFilterUpdateMask() {
42 if (CONFIG_FILTER_UPDATE_STEPS <= 0) return 0;
43 int power_of_two;
44 for (power_of_two = 0; 1<<power_of_two < CONFIG_FILTER_UPDATE_STEPS; power_of_two++);
45 return (1 << power_of_two) - 1;
46 }
47
48 Voice::Voice() {
49 pEngine = NULL;
50 pDiskThread = NULL;
51 PlaybackState = playback_state_end;
52 pEG1 = NULL;
53 pEG2 = NULL;
54 pEG3 = NULL;
55 pVCAManipulator = NULL;
56 pVCFCManipulator = NULL;
57 pVCOManipulator = NULL;
58 pLFO1 = NULL;
59 pLFO2 = NULL;
60 pLFO3 = NULL;
61 KeyGroup = 0;
62 SynthesisMode = 0; // set all mode bits to 0 first
63 // select synthesis implementation (currently either pure C++ or MMX+SSE(1))
64 #if CONFIG_ASM && ARCH_X86
65 SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, Features::supportsMMX() && Features::supportsSSE());
66 #else
67 SYNTHESIS_MODE_SET_IMPLEMENTATION(SynthesisMode, false);
68 #endif
69 SYNTHESIS_MODE_SET_PROFILING(SynthesisMode, true);
70
71 FilterLeft.Reset();
72 FilterRight.Reset();
73 }
74
75 Voice::~Voice() {
76 if (pEG1) delete pEG1;
77 if (pEG2) delete pEG2;
78 if (pEG3) delete pEG3;
79 if (pLFO1) delete pLFO1;
80 if (pLFO2) delete pLFO2;
81 if (pLFO3) delete pLFO3;
82 if (pVCAManipulator) delete pVCAManipulator;
83 if (pVCFCManipulator) delete pVCFCManipulator;
84 if (pVCOManipulator) delete pVCOManipulator;
85 }
86
87 void Voice::SetEngine(Engine* pEngine) {
88 this->pEngine = pEngine;
89
90 // delete old objects
91 if (pEG1) delete pEG1;
92 if (pEG2) delete pEG2;
93 if (pEG3) delete pEG3;
94 if (pVCAManipulator) delete pVCAManipulator;
95 if (pVCFCManipulator) delete pVCFCManipulator;
96 if (pVCOManipulator) delete pVCOManipulator;
97 if (pLFO1) delete pLFO1;
98 if (pLFO2) delete pLFO2;
99 if (pLFO3) delete pLFO3;
100
101 // create new ones
102 pEG1 = new EGADSR(pEngine, Event::destination_vca);
103 pEG2 = new EGADSR(pEngine, Event::destination_vcfc);
104 pEG3 = new EGDecay(pEngine, Event::destination_vco);
105 pVCAManipulator = new VCAManipulator(pEngine);
106 pVCFCManipulator = new VCFCManipulator(pEngine);
107 pVCOManipulator = new VCOManipulator(pEngine);
108 pLFO1 = new LFO<gig::VCAManipulator>(0.0f, 1.0f, LFO<VCAManipulator>::propagation_top_down, pVCAManipulator, pEngine->pEventPool);
109 pLFO2 = new LFO<gig::VCFCManipulator>(0.0f, 1.0f, LFO<VCFCManipulator>::propagation_top_down, pVCFCManipulator, pEngine->pEventPool);
110 pLFO3 = new LFO<gig::VCOManipulator>(-1200.0f, 1200.0f, LFO<VCOManipulator>::propagation_middle_balanced, pVCOManipulator, pEngine->pEventPool); // +-1 octave (+-1200 cents) max.
111
112 this->pDiskThread = pEngine->pDiskThread;
113 dmsg(6,("Voice::SetEngine()\n"));
114 }
115
116 /**
117 * Initializes and triggers the voice, a disk stream will be launched if
118 * needed.
119 *
120 * @param pEngineChannel - engine channel on which this voice was ordered
121 * @param itNoteOnEvent - event that caused triggering of this voice
122 * @param PitchBend - MIDI detune factor (-8192 ... +8191)
123 * @param pDimRgn - points to the dimension region which provides sample wave(s) and articulation data
124 * @param VoiceType - type of this voice
125 * @param iKeyGroup - a value > 0 defines a key group in which this voice is member of
126 * @returns 0 on success, a value < 0 if the voice wasn't triggered
127 * (either due to an error or e.g. because no region is
128 * defined for the given key)
129 */
130 int Voice::Trigger(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int PitchBend, ::gig::DimensionRegion* pDimRgn, type_t VoiceType, int iKeyGroup) {
131 this->pEngineChannel = pEngineChannel;
132 this->pDimRgn = pDimRgn;
133
134 #if CONFIG_DEVMODE
135 if (itNoteOnEvent->FragmentPos() > pEngine->MaxSamplesPerCycle) { // just a sanity check for debugging
136 dmsg(1,("Voice::Trigger(): ERROR, TriggerDelay > Totalsamples\n"));
137 }
138 #endif // CONFIG_DEVMODE
139
140 Type = VoiceType;
141 MIDIKey = itNoteOnEvent->Param.Note.Key;
142 PlaybackState = playback_state_init; // mark voice as triggered, but no audio rendered yet
143 Delay = itNoteOnEvent->FragmentPos();
144 itTriggerEvent = itNoteOnEvent;
145 itKillEvent = Pool<Event>::Iterator();
146 KeyGroup = iKeyGroup;
147 pSample = pDimRgn->pSample; // sample won't change until the voice is finished
148
149 // calculate volume
150 const double velocityAttenuation = pDimRgn->GetVelocityAttenuation(itNoteOnEvent->Param.Note.Velocity);
151
152 Volume = velocityAttenuation / 32768.0f; // we downscale by 32768 to convert from int16 value range to DSP value range (which is -1.0..1.0)
153
154 Volume *= pDimRgn->SampleAttenuation;
155
156 // the volume of release triggered samples depends on note length
157 if (Type == type_release_trigger) {
158 float noteLength = float(pEngine->FrameTime + Delay -
159 pEngineChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime) / pEngine->SampleRate;
160 float attenuation = 1 - 0.01053 * (256 >> pDimRgn->ReleaseTriggerDecay) * noteLength;
161 if (attenuation <= 0) return -1;
162 Volume *= attenuation;
163 }
164
165 // select channel mode (mono or stereo)
166 SYNTHESIS_MODE_SET_CHANNELS(SynthesisMode, pSample->Channels == 2);
167
168 // get starting crossfade volume level
169 switch (pDimRgn->AttenuationController.type) {
170 case ::gig::attenuation_ctrl_t::type_channelaftertouch:
171 CrossfadeVolume = 1.0f; //TODO: aftertouch not supported yet
172 break;
173 case ::gig::attenuation_ctrl_t::type_velocity:
174 CrossfadeVolume = CrossfadeAttenuation(itNoteOnEvent->Param.Note.Velocity);
175 break;
176 case ::gig::attenuation_ctrl_t::type_controlchange: //FIXME: currently not sample accurate
177 CrossfadeVolume = CrossfadeAttenuation(pEngineChannel->ControllerTable[pDimRgn->AttenuationController.controller_number]);
178 break;
179 case ::gig::attenuation_ctrl_t::type_none: // no crossfade defined
180 default:
181 CrossfadeVolume = 1.0f;
182 }
183
184 PanLeft = 1.0f - float(RTMath::Max(pDimRgn->Pan, 0)) / 63.0f;
185 PanRight = 1.0f - float(RTMath::Min(pDimRgn->Pan, 0)) / -64.0f;
186
187 Pos = pDimRgn->SampleStartOffset; // offset where we should start playback of sample (0 - 2000 sample points)
188
189 // Check if the sample needs disk streaming or is too short for that
190 long cachedsamples = pSample->GetCache().Size / pSample->FrameSize;
191 DiskVoice = cachedsamples < pSample->SamplesTotal;
192
193 if (DiskVoice) { // voice to be streamed from disk
194 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)
195
196 // check if there's a loop defined which completely fits into the cached (RAM) part of the sample
197 if (pSample->Loops && pSample->LoopEnd <= MaxRAMPos) {
198 RAMLoop = true;
199 LoopCyclesLeft = pSample->LoopPlayCount;
200 }
201 else RAMLoop = false;
202
203 if (pDiskThread->OrderNewStream(&DiskStreamRef, pSample, MaxRAMPos, !RAMLoop) < 0) {
204 dmsg(1,("Disk stream order failed!\n"));
205 KillImmediately();
206 return -1;
207 }
208 dmsg(4,("Disk voice launched (cached samples: %d, total Samples: %d, MaxRAMPos: %d, RAMLooping: %s)\n", cachedsamples, pSample->SamplesTotal, MaxRAMPos, (RAMLoop) ? "yes" : "no"));
209 }
210 else { // RAM only voice
211 MaxRAMPos = cachedsamples;
212 if (pSample->Loops) {
213 RAMLoop = true;
214 LoopCyclesLeft = pSample->LoopPlayCount;
215 }
216 else RAMLoop = false;
217 dmsg(4,("RAM only voice launched (Looping: %s)\n", (RAMLoop) ? "yes" : "no"));
218 }
219
220
221 // calculate initial pitch value
222 {
223 double pitchbasecents = pDimRgn->FineTune + (int) pEngine->ScaleTuning[MIDIKey % 12];
224 if (pDimRgn->PitchTrack) pitchbasecents += (MIDIKey - (int) pDimRgn->UnityNote) * 100;
225 this->PitchBase = RTMath::CentsToFreqRatio(pitchbasecents) * (double(pSample->SamplesPerSecond) / double(pEngine->pAudioOutputDevice->SampleRate()));
226 this->PitchBend = RTMath::CentsToFreqRatio(((double) PitchBend / 8192.0) * 200.0); // pitchbend wheel +-2 semitones = 200 cents
227 }
228
229 // the length of the decay and release curves are dependent on the velocity
230 const double velrelease = 1 / pDimRgn->GetVelocityRelease(itNoteOnEvent->Param.Note.Velocity);
231
232 // setup EG 1 (VCA EG)
233 {
234 // get current value of EG1 controller
235 double eg1controllervalue;
236 switch (pDimRgn->EG1Controller.type) {
237 case ::gig::eg1_ctrl_t::type_none: // no controller defined
238 eg1controllervalue = 0;
239 break;
240 case ::gig::eg1_ctrl_t::type_channelaftertouch:
241 eg1controllervalue = 0; // TODO: aftertouch not yet supported
242 break;
243 case ::gig::eg1_ctrl_t::type_velocity:
244 eg1controllervalue = itNoteOnEvent->Param.Note.Velocity;
245 break;
246 case ::gig::eg1_ctrl_t::type_controlchange: // MIDI control change controller
247 eg1controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG1Controller.controller_number];
248 break;
249 }
250 if (pDimRgn->EG1ControllerInvert) eg1controllervalue = 127 - eg1controllervalue;
251
252 // calculate influence of EG1 controller on EG1's parameters (TODO: needs to be fine tuned)
253 double eg1attack = (pDimRgn->EG1ControllerAttackInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerAttackInfluence) * eg1controllervalue : 0.0;
254 double eg1decay = (pDimRgn->EG1ControllerDecayInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerDecayInfluence) * eg1controllervalue : 0.0;
255 double eg1release = (pDimRgn->EG1ControllerReleaseInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG1ControllerReleaseInfluence) * eg1controllervalue : 0.0;
256
257 pEG1->Trigger(pDimRgn->EG1PreAttack,
258 pDimRgn->EG1Attack + eg1attack,
259 pDimRgn->EG1Hold,
260 pSample->LoopStart,
261 (pDimRgn->EG1Decay1 + eg1decay) * velrelease,
262 (pDimRgn->EG1Decay2 + eg1decay) * velrelease,
263 pDimRgn->EG1InfiniteSustain,
264 pDimRgn->EG1Sustain,
265 (pDimRgn->EG1Release + eg1release) * velrelease,
266 // the SSE synthesis implementation requires
267 // the vca start to be 16 byte aligned
268 SYNTHESIS_MODE_GET_IMPLEMENTATION(SynthesisMode) ?
269 Delay & 0xfffffffc : Delay,
270 velocityAttenuation);
271 }
272
273
274 // setup EG 2 (VCF Cutoff EG)
275 {
276 // get current value of EG2 controller
277 double eg2controllervalue;
278 switch (pDimRgn->EG2Controller.type) {
279 case ::gig::eg2_ctrl_t::type_none: // no controller defined
280 eg2controllervalue = 0;
281 break;
282 case ::gig::eg2_ctrl_t::type_channelaftertouch:
283 eg2controllervalue = 0; // TODO: aftertouch not yet supported
284 break;
285 case ::gig::eg2_ctrl_t::type_velocity:
286 eg2controllervalue = itNoteOnEvent->Param.Note.Velocity;
287 break;
288 case ::gig::eg2_ctrl_t::type_controlchange: // MIDI control change controller
289 eg2controllervalue = pEngineChannel->ControllerTable[pDimRgn->EG2Controller.controller_number];
290 break;
291 }
292 if (pDimRgn->EG2ControllerInvert) eg2controllervalue = 127 - eg2controllervalue;
293
294 // calculate influence of EG2 controller on EG2's parameters (TODO: needs to be fine tuned)
295 double eg2attack = (pDimRgn->EG2ControllerAttackInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerAttackInfluence) * eg2controllervalue : 0.0;
296 double eg2decay = (pDimRgn->EG2ControllerDecayInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerDecayInfluence) * eg2controllervalue : 0.0;
297 double eg2release = (pDimRgn->EG2ControllerReleaseInfluence) ? 0.0001 * (double) (1 << pDimRgn->EG2ControllerReleaseInfluence) * eg2controllervalue : 0.0;
298
299 pEG2->Trigger(pDimRgn->EG2PreAttack,
300 pDimRgn->EG2Attack + eg2attack,
301 false,
302 pSample->LoopStart,
303 (pDimRgn->EG2Decay1 + eg2decay) * velrelease,
304 (pDimRgn->EG2Decay2 + eg2decay) * velrelease,
305 pDimRgn->EG2InfiniteSustain,
306 pDimRgn->EG2Sustain,
307 (pDimRgn->EG2Release + eg2release) * velrelease,
308 Delay,
309 velocityAttenuation);
310 }
311
312
313 // setup EG 3 (VCO EG)
314 {
315 double eg3depth = RTMath::CentsToFreqRatio(pDimRgn->EG3Depth);
316 pEG3->Trigger(eg3depth, pDimRgn->EG3Attack, Delay);
317 }
318
319
320 // setup LFO 1 (VCA LFO)
321 {
322 uint16_t lfo1_internal_depth;
323 switch (pDimRgn->LFO1Controller) {
324 case ::gig::lfo1_ctrl_internal:
325 lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
326 pLFO1->ExtController = 0; // no external controller
327 break;
328 case ::gig::lfo1_ctrl_modwheel:
329 lfo1_internal_depth = 0;
330 pLFO1->ExtController = 1; // MIDI controller 1
331 break;
332 case ::gig::lfo1_ctrl_breath:
333 lfo1_internal_depth = 0;
334 pLFO1->ExtController = 2; // MIDI controller 2
335 break;
336 case ::gig::lfo1_ctrl_internal_modwheel:
337 lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
338 pLFO1->ExtController = 1; // MIDI controller 1
339 break;
340 case ::gig::lfo1_ctrl_internal_breath:
341 lfo1_internal_depth = pDimRgn->LFO1InternalDepth;
342 pLFO1->ExtController = 2; // MIDI controller 2
343 break;
344 default:
345 lfo1_internal_depth = 0;
346 pLFO1->ExtController = 0; // no external controller
347 }
348 pLFO1->Trigger(pDimRgn->LFO1Frequency,
349 lfo1_internal_depth,
350 pDimRgn->LFO1ControlDepth,
351 pEngineChannel->ControllerTable[pLFO1->ExtController],
352 pDimRgn->LFO1FlipPhase,
353 pEngine->SampleRate,
354 Delay);
355 }
356
357
358 // setup LFO 2 (VCF Cutoff LFO)
359 {
360 uint16_t lfo2_internal_depth;
361 switch (pDimRgn->LFO2Controller) {
362 case ::gig::lfo2_ctrl_internal:
363 lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
364 pLFO2->ExtController = 0; // no external controller
365 break;
366 case ::gig::lfo2_ctrl_modwheel:
367 lfo2_internal_depth = 0;
368 pLFO2->ExtController = 1; // MIDI controller 1
369 break;
370 case ::gig::lfo2_ctrl_foot:
371 lfo2_internal_depth = 0;
372 pLFO2->ExtController = 4; // MIDI controller 4
373 break;
374 case ::gig::lfo2_ctrl_internal_modwheel:
375 lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
376 pLFO2->ExtController = 1; // MIDI controller 1
377 break;
378 case ::gig::lfo2_ctrl_internal_foot:
379 lfo2_internal_depth = pDimRgn->LFO2InternalDepth;
380 pLFO2->ExtController = 4; // MIDI controller 4
381 break;
382 default:
383 lfo2_internal_depth = 0;
384 pLFO2->ExtController = 0; // no external controller
385 }
386 pLFO2->Trigger(pDimRgn->LFO2Frequency,
387 lfo2_internal_depth,
388 pDimRgn->LFO2ControlDepth,
389 pEngineChannel->ControllerTable[pLFO2->ExtController],
390 pDimRgn->LFO2FlipPhase,
391 pEngine->SampleRate,
392 Delay);
393 }
394
395
396 // setup LFO 3 (VCO LFO)
397 {
398 uint16_t lfo3_internal_depth;
399 switch (pDimRgn->LFO3Controller) {
400 case ::gig::lfo3_ctrl_internal:
401 lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
402 pLFO3->ExtController = 0; // no external controller
403 break;
404 case ::gig::lfo3_ctrl_modwheel:
405 lfo3_internal_depth = 0;
406 pLFO3->ExtController = 1; // MIDI controller 1
407 break;
408 case ::gig::lfo3_ctrl_aftertouch:
409 lfo3_internal_depth = 0;
410 pLFO3->ExtController = 0; // TODO: aftertouch not implemented yet
411 break;
412 case ::gig::lfo3_ctrl_internal_modwheel:
413 lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
414 pLFO3->ExtController = 1; // MIDI controller 1
415 break;
416 case ::gig::lfo3_ctrl_internal_aftertouch:
417 lfo3_internal_depth = pDimRgn->LFO3InternalDepth;
418 pLFO1->ExtController = 0; // TODO: aftertouch not implemented yet
419 break;
420 default:
421 lfo3_internal_depth = 0;
422 pLFO3->ExtController = 0; // no external controller
423 }
424 pLFO3->Trigger(pDimRgn->LFO3Frequency,
425 lfo3_internal_depth,
426 pDimRgn->LFO3ControlDepth,
427 pEngineChannel->ControllerTable[pLFO3->ExtController],
428 false,
429 pEngine->SampleRate,
430 Delay);
431 }
432
433
434 #if CONFIG_FORCE_FILTER
435 const bool bUseFilter = true;
436 #else // use filter only if instrument file told so
437 const bool bUseFilter = pDimRgn->VCFEnabled;
438 #endif // CONFIG_FORCE_FILTER
439 SYNTHESIS_MODE_SET_FILTER(SynthesisMode, bUseFilter);
440 if (bUseFilter) {
441 #ifdef CONFIG_OVERRIDE_CUTOFF_CTRL
442 VCFCutoffCtrl.controller = CONFIG_OVERRIDE_CUTOFF_CTRL;
443 #else // use the one defined in the instrument file
444 switch (pDimRgn->VCFCutoffController) {
445 case ::gig::vcf_cutoff_ctrl_modwheel:
446 VCFCutoffCtrl.controller = 1;
447 break;
448 case ::gig::vcf_cutoff_ctrl_effect1:
449 VCFCutoffCtrl.controller = 12;
450 break;
451 case ::gig::vcf_cutoff_ctrl_effect2:
452 VCFCutoffCtrl.controller = 13;
453 break;
454 case ::gig::vcf_cutoff_ctrl_breath:
455 VCFCutoffCtrl.controller = 2;
456 break;
457 case ::gig::vcf_cutoff_ctrl_foot:
458 VCFCutoffCtrl.controller = 4;
459 break;
460 case ::gig::vcf_cutoff_ctrl_sustainpedal:
461 VCFCutoffCtrl.controller = 64;
462 break;
463 case ::gig::vcf_cutoff_ctrl_softpedal:
464 VCFCutoffCtrl.controller = 67;
465 break;
466 case ::gig::vcf_cutoff_ctrl_genpurpose7:
467 VCFCutoffCtrl.controller = 82;
468 break;
469 case ::gig::vcf_cutoff_ctrl_genpurpose8:
470 VCFCutoffCtrl.controller = 83;
471 break;
472 case ::gig::vcf_cutoff_ctrl_aftertouch: //TODO: not implemented yet
473 case ::gig::vcf_cutoff_ctrl_none:
474 default:
475 VCFCutoffCtrl.controller = 0;
476 break;
477 }
478 #endif // CONFIG_OVERRIDE_CUTOFF_CTRL
479
480 #ifdef CONFIG_OVERRIDE_RESONANCE_CTRL
481 VCFResonanceCtrl.controller = CONFIG_OVERRIDE_RESONANCE_CTRL;
482 #else // use the one defined in the instrument file
483 switch (pDimRgn->VCFResonanceController) {
484 case ::gig::vcf_res_ctrl_genpurpose3:
485 VCFResonanceCtrl.controller = 18;
486 break;
487 case ::gig::vcf_res_ctrl_genpurpose4:
488 VCFResonanceCtrl.controller = 19;
489 break;
490 case ::gig::vcf_res_ctrl_genpurpose5:
491 VCFResonanceCtrl.controller = 80;
492 break;
493 case ::gig::vcf_res_ctrl_genpurpose6:
494 VCFResonanceCtrl.controller = 81;
495 break;
496 case ::gig::vcf_res_ctrl_none:
497 default:
498 VCFResonanceCtrl.controller = 0;
499 }
500 #endif // CONFIG_OVERRIDE_RESONANCE_CTRL
501
502 #ifndef CONFIG_OVERRIDE_FILTER_TYPE
503 FilterLeft.SetType(pDimRgn->VCFType);
504 FilterRight.SetType(pDimRgn->VCFType);
505 #else // override filter type
506 FilterLeft.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
507 FilterRight.SetType(CONFIG_OVERRIDE_FILTER_TYPE);
508 #endif // CONFIG_OVERRIDE_FILTER_TYPE
509
510 VCFCutoffCtrl.value = pEngineChannel->ControllerTable[VCFCutoffCtrl.controller];
511 VCFResonanceCtrl.value = pEngineChannel->ControllerTable[VCFResonanceCtrl.controller];
512
513 // calculate cutoff frequency
514 float cutoff = (!VCFCutoffCtrl.controller)
515 ? exp((float) (127 - itNoteOnEvent->Param.Note.Velocity) * (float) pDimRgn->VCFVelocityScale * 6.2E-5f * FILTER_CUTOFF_COEFF) * CONFIG_FILTER_CUTOFF_MAX
516 : exp((float) VCFCutoffCtrl.value * 0.00787402f * FILTER_CUTOFF_COEFF) * CONFIG_FILTER_CUTOFF_MAX;
517
518 // calculate resonance
519 float resonance = (float) VCFResonanceCtrl.value * 0.00787f; // 0.0..1.0
520 if (pDimRgn->VCFKeyboardTracking) {
521 resonance += (float) (itNoteOnEvent->Param.Note.Key - pDimRgn->VCFKeyboardTrackingBreakpoint) * 0.00787f;
522 }
523 Constrain(resonance, 0.0, 1.0); // correct resonance if outside allowed value range (0.0..1.0)
524
525 VCFCutoffCtrl.fvalue = cutoff - CONFIG_FILTER_CUTOFF_MIN;
526 VCFResonanceCtrl.fvalue = resonance;
527
528 FilterUpdateCounter = -1;
529 }
530 else {
531 VCFCutoffCtrl.controller = 0;
532 VCFResonanceCtrl.controller = 0;
533 }
534
535 return 0; // success
536 }
537
538 /**
539 * Renders the audio data for this voice for the current audio fragment.
540 * The sample input data can either come from RAM (cached sample or sample
541 * part) or directly from disk. The output signal will be rendered by
542 * resampling / interpolation. If this voice is a disk streaming voice and
543 * the voice completely played back the cached RAM part of the sample, it
544 * will automatically switch to disk playback for the next RenderAudio()
545 * call.
546 *
547 * @param Samples - number of samples to be rendered in this audio fragment cycle
548 */
549 void Voice::Render(uint Samples) {
550
551 // select default values for synthesis mode bits
552 SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, (PitchBase * PitchBend) != 1.0f);
553 SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, true);
554 SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);
555
556 // Reset the synthesis parameter matrix
557
558 pEngine->ResetSynthesisParameters(Event::destination_vca, this->Volume * this->CrossfadeVolume * pEngineChannel->GlobalVolume);
559 pEngine->ResetSynthesisParameters(Event::destination_vco, this->PitchBase);
560 pEngine->ResetSynthesisParameters(Event::destination_vcfc, VCFCutoffCtrl.fvalue);
561 pEngine->ResetSynthesisParameters(Event::destination_vcfr, VCFResonanceCtrl.fvalue);
562
563 // Apply events to the synthesis parameter matrix
564 ProcessEvents(Samples);
565
566 // Let all modulators write their parameter changes to the synthesis parameter matrix for the current audio fragment
567 pEG1->Process(Samples, pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents, itTriggerEvent, this->Pos, this->PitchBase * this->PitchBend, itKillEvent);
568 pEG2->Process(Samples, pEngineChannel->pMIDIKeyInfo[MIDIKey].pEvents, itTriggerEvent, this->Pos, this->PitchBase * this->PitchBend);
569 if (pEG3->Process(Samples)) { // if pitch EG is active
570 SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);
571 SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);
572 }
573 pLFO1->Process(Samples);
574 pLFO2->Process(Samples);
575 if (pLFO3->Process(Samples)) { // if pitch LFO modulation is active
576 SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);
577 SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);
578 }
579
580 if (SYNTHESIS_MODE_GET_FILTER(SynthesisMode))
581 CalculateBiquadParameters(Samples); // calculate the final biquad filter parameters
582
583 switch (this->PlaybackState) {
584
585 case playback_state_init:
586 this->PlaybackState = playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed
587 // no break - continue with playback_state_ram
588
589 case playback_state_ram: {
590 if (RAMLoop) SYNTHESIS_MODE_SET_LOOP(SynthesisMode, true); // enable looping
591
592 // render current fragment
593 Synthesize(Samples, (sample_t*) pSample->GetCache().pStart, Delay);
594
595 if (DiskVoice) {
596 // check if we reached the allowed limit of the sample RAM cache
597 if (Pos > MaxRAMPos) {
598 dmsg(5,("Voice: switching to disk playback (Pos=%f)\n", Pos));
599 this->PlaybackState = playback_state_disk;
600 }
601 }
602 else if (Pos >= pSample->GetCache().Size / pSample->FrameSize) {
603 this->PlaybackState = playback_state_end;
604 }
605 }
606 break;
607
608 case playback_state_disk: {
609 if (!DiskStreamRef.pStream) {
610 // check if the disk thread created our ordered disk stream in the meantime
611 DiskStreamRef.pStream = pDiskThread->AskForCreatedStream(DiskStreamRef.OrderID);
612 if (!DiskStreamRef.pStream) {
613 std::cout << stderr << "Disk stream not available in time!" << std::endl << std::flush;
614 KillImmediately();
615 return;
616 }
617 DiskStreamRef.pStream->IncrementReadPos(pSample->Channels * (int(Pos) - MaxRAMPos));
618 Pos -= int(Pos);
619 RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet
620 }
621
622 const int sampleWordsLeftToRead = DiskStreamRef.pStream->GetReadSpace();
623
624 // add silence sample at the end if we reached the end of the stream (for the interpolator)
625 if (DiskStreamRef.State == Stream::state_end) {
626 const int maxSampleWordsPerCycle = (pEngine->MaxSamplesPerCycle << CONFIG_MAX_PITCH) * pSample->Channels + 6; // +6 for the interpolator algorithm
627 if (sampleWordsLeftToRead <= maxSampleWordsPerCycle) {
628 // remember how many sample words there are before any silence has been added
629 if (RealSampleWordsLeftToRead < 0) RealSampleWordsLeftToRead = sampleWordsLeftToRead;
630 DiskStreamRef.pStream->WriteSilence(maxSampleWordsPerCycle - sampleWordsLeftToRead);
631 }
632 }
633
634 sample_t* ptr = DiskStreamRef.pStream->GetReadPtr(); // get the current read_ptr within the ringbuffer where we read the samples from
635
636 // render current audio fragment
637 Synthesize(Samples, ptr, Delay);
638
639 const int iPos = (int) Pos;
640 const int readSampleWords = iPos * pSample->Channels; // amount of sample words actually been read
641 DiskStreamRef.pStream->IncrementReadPos(readSampleWords);
642 Pos -= iPos; // just keep fractional part of Pos
643
644 // change state of voice to 'end' if we really reached the end of the sample data
645 if (RealSampleWordsLeftToRead >= 0) {
646 RealSampleWordsLeftToRead -= readSampleWords;
647 if (RealSampleWordsLeftToRead <= 0) this->PlaybackState = playback_state_end;
648 }
649 }
650 break;
651
652 case playback_state_end:
653 std::cerr << "gig::Voice::Render(): entered with playback_state_end, this is a bug!\n" << std::flush;
654 break;
655 }
656
657 // Reset synthesis event lists (except VCO, as VCO events apply channel wide currently)
658 pEngineChannel->pSynthesisEvents[Event::destination_vca]->clear();
659 pEngineChannel->pSynthesisEvents[Event::destination_vcfc]->clear();
660 pEngineChannel->pSynthesisEvents[Event::destination_vcfr]->clear();
661
662 // Reset delay
663 Delay = 0;
664
665 itTriggerEvent = Pool<Event>::Iterator();
666
667 // If sample stream or release stage finished, kill the voice
668 if (PlaybackState == playback_state_end || pEG1->GetStage() == EGADSR::stage_end) KillImmediately();
669 }
670
671 /**
672 * Resets voice variables. Should only be called if rendering process is
673 * suspended / not running.
674 */
675 void Voice::Reset() {
676 pLFO1->Reset();
677 pLFO2->Reset();
678 pLFO3->Reset();
679 FilterLeft.Reset();
680 FilterRight.Reset();
681 DiskStreamRef.pStream = NULL;
682 DiskStreamRef.hStream = 0;
683 DiskStreamRef.State = Stream::state_unused;
684 DiskStreamRef.OrderID = 0;
685 PlaybackState = playback_state_end;
686 itTriggerEvent = Pool<Event>::Iterator();
687 itKillEvent = Pool<Event>::Iterator();
688 }
689
690 /**
691 * Process the control change event lists of the engine for the current
692 * audio fragment. Event values will be applied to the synthesis parameter
693 * matrix.
694 *
695 * @param Samples - number of samples to be rendered in this audio fragment cycle
696 */
697 void Voice::ProcessEvents(uint Samples) {
698
699 // dispatch control change events
700 RTList<Event>::Iterator itCCEvent = pEngineChannel->pCCEvents->first();
701 if (Delay) { // skip events that happened before this voice was triggered
702 while (itCCEvent && itCCEvent->FragmentPos() <= Delay) ++itCCEvent;
703 }
704 while (itCCEvent) {
705 if (itCCEvent->Param.CC.Controller) { // if valid MIDI controller
706 if (itCCEvent->Param.CC.Controller == VCFCutoffCtrl.controller) {
707 *pEngineChannel->pSynthesisEvents[Event::destination_vcfc]->allocAppend() = *itCCEvent;
708 }
709 if (itCCEvent->Param.CC.Controller == VCFResonanceCtrl.controller) {
710 *pEngineChannel->pSynthesisEvents[Event::destination_vcfr]->allocAppend() = *itCCEvent;
711 }
712 if (itCCEvent->Param.CC.Controller == pLFO1->ExtController) {
713 pLFO1->SendEvent(itCCEvent);
714 }
715 if (itCCEvent->Param.CC.Controller == pLFO2->ExtController) {
716 pLFO2->SendEvent(itCCEvent);
717 }
718 if (itCCEvent->Param.CC.Controller == pLFO3->ExtController) {
719 pLFO3->SendEvent(itCCEvent);
720 }
721 if (pDimRgn->AttenuationController.type == ::gig::attenuation_ctrl_t::type_controlchange &&
722 itCCEvent->Param.CC.Controller == pDimRgn->AttenuationController.controller_number) { // if crossfade event
723 *pEngineChannel->pSynthesisEvents[Event::destination_vca]->allocAppend() = *itCCEvent;
724 }
725 }
726
727 ++itCCEvent;
728 }
729
730
731 // process pitch events
732 {
733 RTList<Event>* pVCOEventList = pEngineChannel->pSynthesisEvents[Event::destination_vco];
734 RTList<Event>::Iterator itVCOEvent = pVCOEventList->first();
735 if (Delay) { // skip events that happened before this voice was triggered
736 while (itVCOEvent && itVCOEvent->FragmentPos() <= Delay) ++itVCOEvent;
737 }
738 // apply old pitchbend value until first pitch event occurs
739 if (this->PitchBend != 1.0) {
740 uint end = (itVCOEvent) ? itVCOEvent->FragmentPos() : Samples;
741 for (uint i = Delay; i < end; i++) {
742 pEngine->pSynthesisParameters[Event::destination_vco][i] *= this->PitchBend;
743 }
744 }
745 float pitch;
746 while (itVCOEvent) {
747 RTList<Event>::Iterator itNextVCOEvent = itVCOEvent;
748 ++itNextVCOEvent;
749
750 // calculate the influence length of this event (in sample points)
751 uint end = (itNextVCOEvent) ? itNextVCOEvent->FragmentPos() : Samples;
752
753 pitch = RTMath::CentsToFreqRatio(((double) itVCOEvent->Param.Pitch.Pitch / 8192.0) * 200.0); // +-two semitones = +-200 cents
754
755 // apply pitch value to the pitch parameter sequence
756 for (uint i = itVCOEvent->FragmentPos(); i < end; i++) {
757 pEngine->pSynthesisParameters[Event::destination_vco][i] *= pitch;
758 }
759
760 itVCOEvent = itNextVCOEvent;
761 }
762 if (!pVCOEventList->isEmpty()) {
763 this->PitchBend = pitch;
764 SYNTHESIS_MODE_SET_INTERPOLATE(SynthesisMode, true);
765 SYNTHESIS_MODE_SET_CONSTPITCH(SynthesisMode, false);
766 }
767 }
768
769 // process volume / attenuation events (TODO: we only handle and _expect_ crossfade events here ATM !)
770 {
771 RTList<Event>* pVCAEventList = pEngineChannel->pSynthesisEvents[Event::destination_vca];
772 RTList<Event>::Iterator itVCAEvent = pVCAEventList->first();
773 if (Delay) { // skip events that happened before this voice was triggered
774 while (itVCAEvent && itVCAEvent->FragmentPos() <= Delay) ++itVCAEvent;
775 }
776 float crossfadevolume;
777 while (itVCAEvent) {
778 RTList<Event>::Iterator itNextVCAEvent = itVCAEvent;
779 ++itNextVCAEvent;
780
781 // calculate the influence length of this event (in sample points)
782 uint end = (itNextVCAEvent) ? itNextVCAEvent->FragmentPos() : Samples;
783
784 crossfadevolume = CrossfadeAttenuation(itVCAEvent->Param.CC.Value);
785
786 float effective_volume = crossfadevolume * this->Volume * pEngineChannel->GlobalVolume;
787
788 // apply volume value to the volume parameter sequence
789 for (uint i = itVCAEvent->FragmentPos(); i < end; i++) {
790 pEngine->pSynthesisParameters[Event::destination_vca][i] = effective_volume;
791 }
792
793 itVCAEvent = itNextVCAEvent;
794 }
795 if (!pVCAEventList->isEmpty()) this->CrossfadeVolume = crossfadevolume;
796 }
797
798 // process filter cutoff events
799 {
800 RTList<Event>* pCutoffEventList = pEngineChannel->pSynthesisEvents[Event::destination_vcfc];
801 RTList<Event>::Iterator itCutoffEvent = pCutoffEventList->first();
802 if (Delay) { // skip events that happened before this voice was triggered
803 while (itCutoffEvent && itCutoffEvent->FragmentPos() <= Delay) ++itCutoffEvent;
804 }
805 float cutoff;
806 while (itCutoffEvent) {
807 RTList<Event>::Iterator itNextCutoffEvent = itCutoffEvent;
808 ++itNextCutoffEvent;
809
810 // calculate the influence length of this event (in sample points)
811 uint end = (itNextCutoffEvent) ? itNextCutoffEvent->FragmentPos() : Samples;
812
813 cutoff = exp((float) itCutoffEvent->Param.CC.Value * 0.00787402f * FILTER_CUTOFF_COEFF) * CONFIG_FILTER_CUTOFF_MAX - CONFIG_FILTER_CUTOFF_MIN;
814
815 // apply cutoff frequency to the cutoff parameter sequence
816 for (uint i = itCutoffEvent->FragmentPos(); i < end; i++) {
817 pEngine->pSynthesisParameters[Event::destination_vcfc][i] = cutoff;
818 }
819
820 itCutoffEvent = itNextCutoffEvent;
821 }
822 if (!pCutoffEventList->isEmpty()) VCFCutoffCtrl.fvalue = cutoff; // needed for initialization of parameter matrix next time
823 }
824
825 // process filter resonance events
826 {
827 RTList<Event>* pResonanceEventList = pEngineChannel->pSynthesisEvents[Event::destination_vcfr];
828 RTList<Event>::Iterator itResonanceEvent = pResonanceEventList->first();
829 if (Delay) { // skip events that happened before this voice was triggered
830 while (itResonanceEvent && itResonanceEvent->FragmentPos() <= Delay) ++itResonanceEvent;
831 }
832 while (itResonanceEvent) {
833 RTList<Event>::Iterator itNextResonanceEvent = itResonanceEvent;
834 ++itNextResonanceEvent;
835
836 // calculate the influence length of this event (in sample points)
837 uint end = (itNextResonanceEvent) ? itNextResonanceEvent->FragmentPos() : Samples;
838
839 // convert absolute controller value to differential
840 int ctrldelta = itResonanceEvent->Param.CC.Value - VCFResonanceCtrl.value;
841 VCFResonanceCtrl.value = itResonanceEvent->Param.CC.Value;
842
843 float resonancedelta = (float) ctrldelta * 0.00787f; // 0.0..1.0
844
845 // apply cutoff frequency to the cutoff parameter sequence
846 for (uint i = itResonanceEvent->FragmentPos(); i < end; i++) {
847 pEngine->pSynthesisParameters[Event::destination_vcfr][i] += resonancedelta;
848 }
849
850 itResonanceEvent = itNextResonanceEvent;
851 }
852 if (!pResonanceEventList->isEmpty()) VCFResonanceCtrl.fvalue = pResonanceEventList->last()->Param.CC.Value * 0.00787f; // needed for initialization of parameter matrix next time
853 }
854 }
855
856 /**
857 * Calculate all necessary, final biquad filter parameters.
858 *
859 * @param Samples - number of samples to be rendered in this audio fragment cycle
860 */
861 void Voice::CalculateBiquadParameters(uint Samples) {
862 biquad_param_t bqbase;
863 biquad_param_t bqmain;
864 float prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][0];
865 float prev_res = pEngine->pSynthesisParameters[Event::destination_vcfr][0];
866 FilterLeft.SetParameters( &bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);
867 FilterRight.SetParameters(&bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);
868 pEngine->pBasicFilterParameters[0] = bqbase;
869 pEngine->pMainFilterParameters[0] = bqmain;
870
871 float* bq;
872 for (int i = 1; i < Samples; i++) {
873 // recalculate biquad parameters if cutoff or resonance differ from previous sample point
874 if (!(i & FILTER_UPDATE_MASK)) {
875 if (pEngine->pSynthesisParameters[Event::destination_vcfr][i] != prev_res ||
876 pEngine->pSynthesisParameters[Event::destination_vcfc][i] != prev_cutoff)
877 {
878 prev_cutoff = pEngine->pSynthesisParameters[Event::destination_vcfc][i];
879 prev_res = pEngine->pSynthesisParameters[Event::destination_vcfr][i];
880 FilterLeft.SetParameters( &bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);
881 FilterRight.SetParameters(&bqbase, &bqmain, prev_cutoff + CONFIG_FILTER_CUTOFF_MIN, prev_res, pEngine->SampleRate);
882 }
883 }
884
885 //same as 'pEngine->pBasicFilterParameters[i] = bqbase;'
886 bq = (float*) &pEngine->pBasicFilterParameters[i];
887 bq[0] = bqbase.b0;
888 bq[1] = bqbase.b1;
889 bq[2] = bqbase.b2;
890 bq[3] = bqbase.a1;
891 bq[4] = bqbase.a2;
892
893 // same as 'pEngine->pMainFilterParameters[i] = bqmain;'
894 bq = (float*) &pEngine->pMainFilterParameters[i];
895 bq[0] = bqmain.b0;
896 bq[1] = bqmain.b1;
897 bq[2] = bqmain.b2;
898 bq[3] = bqmain.a1;
899 bq[4] = bqmain.a2;
900 }
901 }
902
903 /**
904 * Synthesizes the current audio fragment for this voice.
905 *
906 * @param Samples - number of sample points to be rendered in this audio
907 * fragment cycle
908 * @param pSrc - pointer to input sample data
909 * @param Skip - number of sample points to skip in output buffer
910 */
911 void Voice::Synthesize(uint Samples, sample_t* pSrc, uint Skip) {
912 RunSynthesisFunction(SynthesisMode, *this, Samples, pSrc, Skip);
913 }
914
915 /**
916 * Immediately kill the voice. This method should not be used to kill
917 * a normal, active voice, because it doesn't take care of things like
918 * fading down the volume level to avoid clicks and regular processing
919 * until the kill event actually occured!
920 *
921 * @see Kill()
922 */
923 void Voice::KillImmediately() {
924 if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
925 pDiskThread->OrderDeletionOfStream(&DiskStreamRef);
926 }
927 Reset();
928 }
929
930 /**
931 * Kill the voice in regular sense. Let the voice render audio until
932 * the kill event actually occured and then fade down the volume level
933 * very quickly and let the voice die finally. Unlike a normal release
934 * of a voice, a kill process cannot be cancalled and is therefore
935 * usually used for voice stealing and key group conflicts.
936 *
937 * @param itKillEvent - event which caused the voice to be killed
938 */
939 void Voice::Kill(Pool<Event>::Iterator& itKillEvent) {
940 #if CONFIG_DEVMODE
941 if (!itKillEvent) dmsg(1,("gig::Voice::Kill(): ERROR, !itKillEvent !!!\n"));
942 if (itKillEvent && !itKillEvent.isValid()) dmsg(1,("gig::Voice::Kill(): ERROR, itKillEvent invalid !!!\n"));
943 #endif // CONFIG_DEVMODE
944
945 if (itTriggerEvent && itKillEvent->FragmentPos() <= itTriggerEvent->FragmentPos()) return;
946 this->itKillEvent = itKillEvent;
947 }
948
949 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC