1 //=========================================================
2 // MusE
3 // Linux Music Editor
4 // $Id: node.cpp,v 1.36.2.25 2009/12/20 05:00:35 terminator356 Exp $
5 //
6 // (C) Copyright 2000-2004 Werner Schweer (ws@seh.de)
7 // (C) Copyright 2011-2013 Tim E. Real (terminator356 on sourceforge)
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License
11 // as published by the Free Software Foundation; version 2 of
12 // the License, or (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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 //
23 //=========================================================
24
25 #include "muse_math.h"
26 #include <sndfile.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29
30 #include <QString>
31
32 #include "globals.h"
33 #include "gconfig.h"
34 #include "song.h"
35 #include "xml.h"
36 #include "plugin.h"
37 #include "synth.h"
38 #include "audiodev.h"
39 #include "midiport.h"
40 #include "audio.h"
41 #include "wave.h"
42 #include "utils.h" //debug
43 #include "ticksynth.h" // metronome
44 #include "wavepreview.h"
45 #include "al/dsp.h"
46 #include "latency_compensator.h"
47
48 // REMOVE Tim. Persistent routes. Added. Make this permanent later if it works OK and makes good sense.
49 #define _USE_SIMPLIFIED_SOLO_CHAIN_
50
51 // Turn on debugging messages
52 //#define NODE_DEBUG
53
54 // Turn on constant flow of process debugging messages
55 //#define NODE_DEBUG_PROCESS
56
57 // Turn on some cool terminal 'peak' meters for debugging
58 // presence of actual audio at various places
59 //#define NODE_DEBUG_TERMINAL_PEAK_METERS
60
61 //#define FIFO_DEBUG
62 //#define METRONOME_DEBUG
63
64 namespace MusECore {
65
66 //---------------------------------------------------------
67 // setSolo
68 //---------------------------------------------------------
69
setSolo(bool val)70 void MidiTrack::setSolo(bool val)
71 {
72 if(_solo != val)
73 {
74 _solo = val;
75 updateSoloStates(false);
76 }
77 }
78
setSolo(bool val)79 void AudioTrack::setSolo(bool val)
80 {
81 if(_solo != val)
82 {
83 _solo = val;
84 updateSoloStates(false);
85 }
86
87 if (isMute())
88 resetMeter();
89 }
90
91
92 //---------------------------------------------------------
93 // setInternalSolo
94 //---------------------------------------------------------
95
setInternalSolo(unsigned int val)96 void Track::setInternalSolo(unsigned int val)
97 {
98 _internalSolo = val;
99 }
100
101 //---------------------------------------------------------
102 // clearSoloRefCounts
103 // This is a static member function. Required for outside access.
104 // Clears the internal static reference counts.
105 //---------------------------------------------------------
106
clearSoloRefCounts()107 void Track::clearSoloRefCounts()
108 {
109 _soloRefCnt = 0;
110 }
111
112 //---------------------------------------------------------
113 // updateSoloState
114 //---------------------------------------------------------
115
updateSoloState()116 void Track::updateSoloState()
117 {
118 if(_solo)
119 _soloRefCnt++;
120 else
121 if(_soloRefCnt && !_tmpSoloChainNoDec)
122 _soloRefCnt--;
123 }
124
125 //---------------------------------------------------------
126 // updateInternalSoloStates
127 //---------------------------------------------------------
128
updateInternalSoloStates()129 void Track::updateInternalSoloStates()
130 {
131 if(_tmpSoloChainTrack->solo())
132 {
133 _internalSolo++;
134 _soloRefCnt++;
135 }
136 else
137 if(!_tmpSoloChainNoDec)
138 {
139 if(_internalSolo)
140 _internalSolo--;
141 if(_soloRefCnt)
142 _soloRefCnt--;
143 }
144 }
145
146 //---------------------------------------------------------
147 // updateInternalSoloStates
148 //---------------------------------------------------------
149
updateInternalSoloStates()150 void MidiTrack::updateInternalSoloStates()
151 {
152 if(_nodeTraversed) // Anti circular mechanism.
153 {
154 fprintf(stderr, "MidiTrack::updateInternalSoloStates %s :\n MusE Warning: Please check your routes: Circular path found!\n", name().toLatin1().constData());
155 return;
156 }
157 //if(this == _tmpSoloChainTrack)
158 // return;
159
160 _nodeTraversed = true;
161
162 Track::updateInternalSoloStates();
163
164 _nodeTraversed = false; // Reset.
165 }
166
167
168 //---------------------------------------------------------
169 // updateInternalSoloStates
170 //---------------------------------------------------------
171
updateInternalSoloStates()172 void AudioTrack::updateInternalSoloStates()
173 {
174 if(_nodeTraversed) // Anti circular mechanism.
175 {
176 fprintf(stderr, "AudioTrack::updateInternalSoloStates %s :\n MusE Warning: Please check your routes: Circular path found!\n", name().toLatin1().constData());
177 return;
178 }
179 //if(this == _tmpSoloChainTrack)
180 // return;
181
182 _nodeTraversed = true;
183
184 Track::updateInternalSoloStates();
185
186 if(_tmpSoloChainDoIns)
187 {
188 if(type() == AUDIO_SOFTSYNTH)
189 {
190 const MusECore::MidiTrackList* ml = MusEGlobal::song->midis();
191 for(MusECore::ciMidiTrack im = ml->begin(); im != ml->end(); ++im)
192 {
193 MusECore::MidiTrack* mt = *im;
194 if(mt->outPort() >= 0 && mt->outPort() == ((SynthI*)this)->midiPort())
195 mt->updateInternalSoloStates();
196 }
197 }
198
199 const RouteList* rl = inRoutes();
200 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
201 {
202 if(ir->type == Route::TRACK_ROUTE)
203 ir->track->updateInternalSoloStates();
204 #ifndef _USE_SIMPLIFIED_SOLO_CHAIN_
205 else
206 // Support Midi Port -> Audio Input solo chains.
207 if(ir->type == Route::MIDI_PORT_ROUTE)
208 {
209 const MidiTrackList* ml = MusEGlobal::song->midis();
210 for(ciMidiTrack im = ml->begin(); im != ml->end(); ++im)
211 {
212 MidiTrack* mt = *im;
213 if(mt->outPort() == ir->midiPort && ((1 << mt->outChannel()) & ir->channel) )
214 mt->updateInternalSoloStates();
215 }
216 }
217 #endif
218 }
219 }
220 else
221 {
222 const RouteList* rl = outRoutes();
223 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
224 {
225 if(ir->type == Route::TRACK_ROUTE)
226 ir->track->updateInternalSoloStates();
227 }
228 }
229
230 _nodeTraversed = false; // Reset.
231 }
232
233
234 //---------------------------------------------------------
235 // updateSoloStates
236 //---------------------------------------------------------
237
updateSoloStates(bool noDec)238 void MidiTrack::updateSoloStates(bool noDec)
239 {
240 if(noDec && !_solo)
241 return;
242
243 _nodeTraversed = true; // Anti circular mechanism.
244
245 _tmpSoloChainTrack = this;
246 _tmpSoloChainDoIns = false;
247 _tmpSoloChainNoDec = noDec;
248 updateSoloState();
249
250 if(outPort() >= 0)
251 {
252 MidiPort* mp = &MusEGlobal::midiPorts[outPort()];
253 MidiDevice *md = mp->device();
254 if(md && md->isSynti())
255 ((SynthI*)md)->updateInternalSoloStates();
256 }
257
258 #ifdef _USE_SIMPLIFIED_SOLO_CHAIN_
259 // Support Midi Track to Audio Input track soloing chain routes.
260 // Support omni routes only, because if channels are supported, the graphical router becomes more complicated.
261 const RouteList* rl = outRoutes();
262 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
263 {
264 if(ir->type == Route::TRACK_ROUTE && ir->track && ir->track->type() == Track::AUDIO_INPUT && ir->channel == -1)
265 ir->track->updateInternalSoloStates();
266 }
267 #else
268 // Support Midi Port -> Audio Input solo chains.
269 const int chbits = 1 << outChannel();
270 const RouteList* rl = mp->outRoutes();
271 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
272 {
273 if(ir->type == Route::TRACK_ROUTE && ir->track && ir->track->type() == Track::AUDIO_INPUT && (ir->channel & chbits) )
274 ir->track->updateInternalSoloStates();
275 }
276 #endif
277
278 _nodeTraversed = false; // Reset.
279 }
280
281
282 //---------------------------------------------------------
283 // updateSoloStates
284 //---------------------------------------------------------
285
updateSoloStates(bool noDec)286 void AudioTrack::updateSoloStates(bool noDec)
287 {
288 if(noDec && !_solo)
289 return;
290
291 _nodeTraversed = true; // Anti circular mechanism.
292
293 _tmpSoloChainTrack = this;
294 _tmpSoloChainNoDec = noDec;
295 updateSoloState();
296
297 _tmpSoloChainDoIns = true;
298 if(type() == AUDIO_SOFTSYNTH)
299 {
300 const MidiTrackList* ml = MusEGlobal::song->midis();
301 for(ciMidiTrack im = ml->begin(); im != ml->end(); ++im)
302 {
303 MidiTrack* mt = *im;
304 if(mt->outPort() >= 0 && mt->outPort() == ((SynthI*)this)->midiPort())
305 mt->updateInternalSoloStates();
306 }
307 }
308
309 const RouteList* rl = inRoutes();
310 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
311 {
312 if(ir->type == Route::TRACK_ROUTE)
313 ir->track->updateInternalSoloStates();
314 #ifndef _USE_SIMPLIFIED_SOLO_CHAIN_
315 else
316 // Support Midi Port -> Audio Input solo chains.
317 if(ir->type == Route::MIDI_PORT_ROUTE)
318 {
319 const MidiTrackList* ml = MusEGlobal::song->midis();
320 for(ciMidiTrack im = ml->begin(); im != ml->end(); ++im)
321 {
322 MidiTrack* mt = *im;
323 if(mt->outPort() == ir->midiPort && ((1 << mt->outChannel()) & ir->channel) )
324 mt->updateInternalSoloStates();
325 }
326 }
327 #endif
328 }
329
330 _tmpSoloChainDoIns = false;
331 {
332 const RouteList* rl = outRoutes();
333 for(ciRoute ir = rl->begin(); ir != rl->end(); ++ir)
334 {
335 if(ir->type == Route::TRACK_ROUTE)
336 ir->track->updateInternalSoloStates();
337 }
338 }
339
340 _nodeTraversed = false; // Reset.
341 }
342
preProcessAlways()343 void AudioTrack::preProcessAlways()
344 {
345 _processed = false;
346 Track::preProcessAlways();
347 }
348
349 //---------------------------------------------------------
350 // processTrackCtrls
351 // If trackChans is 0, just process controllers only, not audio (do not 'run').
352 //---------------------------------------------------------
353
processTrackCtrls(unsigned pos,int trackChans,unsigned nframes,float ** buffer)354 void AudioTrack::processTrackCtrls(unsigned pos, int trackChans, unsigned nframes, float** buffer)
355 {
356 const unsigned long syncFrame = MusEGlobal::audio->curSyncFrame();
357 const unsigned long min_per = (MusEGlobal::config.minControlProcessPeriod > nframes) ? nframes : MusEGlobal::config.minControlProcessPeriod;
358 unsigned long sample = 0;
359
360 const AutomationType at = automationType();
361 const bool no_auto = !MusEGlobal::automation || at == AUTO_OFF;
362 CtrlListList* cll = controller();
363 CtrlList* vol_ctrl = 0;
364 CtrlList* pan_ctrl = 0;
365 {
366 ciCtrlList icl = cll->find(AC_VOLUME);
367 if(icl == cll->end())
368 return;
369 vol_ctrl = icl->second;
370 icl = cll->find(AC_PAN);
371 if(icl == cll->end())
372 return;
373 pan_ctrl = icl->second;
374 }
375
376 int cur_slice = 0;
377 while(sample < nframes)
378 {
379 unsigned long nsamp = nframes - sample;
380 const unsigned long slice_frame = pos + sample;
381
382 // Process automation control values, while also determining the maximum acceptable
383 // size of this run. Further processing, from FIFOs for example, can lower the size
384 // from there, but this section determines where the next highest maximum frame
385 // absolutely needs to be for smooth playback of the controller value stream...
386 //
387 if(trackChans != 0 && !_prefader) // Don't bother if we don't want to run, or prefader is on.
388 {
389 ciCtrlList icl = cll->begin();
390 for(unsigned long k = 0; k < _controlPorts; ++k)
391 {
392 CtrlList* cl = (icl != cll->end() ? icl->second : NULL);
393 CtrlInterpolate& ci = _controls[k].interp;
394 // Always refresh the interpolate struct at first, since things may have changed.
395 // Or if the frame is outside of the interpolate range - and eStop is not true. // FIXME TODO: Be sure these comparisons are correct.
396 if(cur_slice == 0 || (!ci.eStop && MusEGlobal::audio->isPlaying() &&
397 (slice_frame < (unsigned long)ci.sFrame || (ci.eFrameValid && slice_frame >= (unsigned long)ci.eFrame)) ) )
398 {
399 if(cl && (unsigned long)cl->id() == k)
400 {
401 cl->getInterpolation(slice_frame, no_auto || !_controls[k].enCtrl, &ci);
402 if(icl != cll->end())
403 ++icl;
404 }
405 else
406 {
407 // No matching controller, or end. Just copy the current value into the interpolator.
408 // Keep the current icl iterator, because since they are sorted by frames,
409 // if the IDs didn't match it means we can just let k catch up with icl.
410 ci.sFrame = 0;
411 ci.eFrame = 0;
412 ci.eFrameValid = false;
413 ci.sVal = _controls[k].dval;
414 ci.eVal = ci.sVal;
415 ci.doInterp = false;
416 ci.eStop = false;
417 }
418 }
419 else
420 {
421 if(ci.eStop && ci.eFrameValid && slice_frame >= (unsigned long)ci.eFrame) // FIXME TODO: Get that comparison right.
422 {
423 // Clear the stop condition and set up the interp struct appropriately as an endless value.
424 ci.sFrame = 0; //ci->eFrame;
425 ci.eFrame = 0;
426 ci.eFrameValid = false;
427 ci.sVal = ci.eVal;
428 ci.doInterp = false;
429 ci.eStop = false;
430 }
431 if(icl != cll->end())
432 ++icl;
433 }
434
435 if(MusEGlobal::audio->isPlaying())
436 {
437 unsigned long samps = nsamp;
438 if(ci.eFrameValid)
439 samps = (unsigned long)ci.eFrame - slice_frame;
440 if(samps < nsamp)
441 nsamp = samps;
442 }
443
444 #ifdef NODE_DEBUG_PROCESS
445 fprintf(stderr, "AudioTrack::processTrackCtrls k:%lu sample:%lu frame:%lu nextFrame:%d nsamp:%lu \n", k, sample, slice_frame, ci.eFrame, nsamp);
446 #endif
447 }
448 }
449
450 #ifdef NODE_DEBUG_PROCESS
451 fprintf(stderr, "AudioTrack::processTrackCtrls sample:%lu nsamp:%lu\n", sample, nsamp);
452 #endif
453
454 //
455 // Process all control ring buffer items valid for this time period...
456 //
457 bool found = false;
458 unsigned long frame = 0;
459 unsigned long evframe;
460 while(!_controlFifo.isEmpty())
461 {
462 const ControlEvent& v = _controlFifo.peek();
463 // The events happened in the last period or even before that. Shift into this period with + n. This will sync with audio.
464 // If the events happened even before current frame - n, make sure they are counted immediately as zero-frame.
465 evframe = (syncFrame > v.frame + nframes) ? 0 : v.frame - syncFrame + nframes;
466
467 // Protection. Observed this condition. Why? Supposed to be linear timestamps.
468 if(found && evframe < frame)
469 {
470 fprintf(stderr,
471 "AudioTrack::processTrackCtrls *** Error: Event out of order: evframe:%lu < frame:%lu idx:%lu val:%f unique:%d syncFrame:%lu nframes:%u v.frame:%lu\n",
472 evframe, frame, v.idx, v.value, v.unique, syncFrame, nframes, v.frame);
473
474 // No choice but to ignore it.
475 _controlFifo.remove(); // Done with the ring buffer's item. Remove it.
476 continue;
477 }
478
479 if(evframe >= nframes // Next events are for a later period.
480 || (!found && !v.unique && (evframe - sample >= nsamp)) // Next events are for a later run in this period. (Autom took prio.)
481 || (found && !v.unique && (evframe - sample >= min_per))) // Eat up events within minimum slice - they're too close.
482 break;
483 // _controlFifo.remove(); // Done with the ring buffer's item. Remove it.
484
485 if(v.idx >= _controlPorts) // Sanity check
486 {
487 _controlFifo.remove(); // Done with the ring buffer's item. Remove it.
488 break;
489 }
490
491 found = true;
492 frame = evframe;
493
494 if(trackChans != 0 && !_prefader) // Only if we want to run, and prefader is off.
495 {
496 CtrlInterpolate* ci = &_controls[v.idx].interp;
497 ci->eFrame = frame;
498 ci->eFrameValid = true;
499 ci->eVal = v.value;
500 ci->eStop = true;
501 }
502
503 // Need to update the automation value, otherwise it overwrites later with the last automation value.
504 setPluginCtrlVal(v.idx, v.value);
505
506 _controlFifo.remove(); // Done with the ring buffer's item. Remove it.
507 }
508
509 if(found && trackChans != 0 && !_prefader) // If a control FIFO item was found, takes priority over automation controller stream.
510 nsamp = frame - sample;
511
512 if(sample + nsamp > nframes) // Safety check.
513 nsamp = nframes - sample;
514
515 // TODO: Don't allow zero-length runs. This could/should be checked in the control loop instead.
516 // Note this means it is still possible to get stuck in the top loop (at least for a while).
517 if(nsamp != 0)
518 {
519 if(trackChans != 0 && !_prefader)
520 {
521 const CtrlInterpolate& vol_interp = _controls[AC_VOLUME].interp;
522 const CtrlInterpolate& pan_interp = _controls[AC_PAN].interp;
523 unsigned long k;
524 //const float up_fact = 1.002711275; // 3.01.. dB / 256
525 //const float down_fact = 0.997296056;
526 const double up_fact = 1.003471749; // 3.01.. dB / 200
527 const double down_fact = 0.996540262;
528
529 float *sp1, *sp2, *dp1, *dp2;
530 sp1 = sp2 = dp1 = dp2 = NULL;
531 double _volume, v, _pan, v1, v2;
532
533 if(trackChans == 1)
534 {
535 sp1 = sp2 = buffer[0] + sample;
536 dp1 = outBuffersExtraMix[0] + sample;
537 dp2 = outBuffersExtraMix[1] + sample;
538 }
539 else
540 {
541 sp1 = buffer[0] + sample;
542 sp2 = buffer[1] + sample;
543 dp1 = outBuffers[0] + sample;
544 dp2 = outBuffers[1] + sample;
545 }
546
547 if(trackChans != 2)
548 {
549 const int start_ch = trackChans == 1 ? 0 : 2;
550
551 k = 0;
552 if(vol_interp.doInterp && MusEGlobal::audio->isPlaying())
553 {
554 for( ; k < nsamp; ++k)
555 {
556 _volume = vol_ctrl->interpolate(slice_frame + k, vol_interp);
557 v = _volume * _gain;
558 if(v > _curVolume)
559 {
560 if(_curVolume == 0.0)
561 _curVolume = 0.001; // Kick-start it from zero at -30dB.
562 _curVolume *= up_fact;
563 if(_curVolume >= v)
564 _curVolume = v;
565 }
566 else
567 if(v < _curVolume)
568 {
569 _curVolume *= down_fact;
570 if(_curVolume <= v || _curVolume <= 0.001) // Or if less than -30dB.
571 _curVolume = v;
572 }
573 const unsigned long smp = sample + k;
574 for(int ch = start_ch; ch < trackChans; ++ch)
575 *(outBuffers[ch] + smp) = *(buffer[ch] + smp) * _curVolume;
576 }
577 _controls[AC_VOLUME].dval = _volume; // Update the port.
578 }
579 else
580 {
581 if(vol_interp.doInterp) // And not playing...
582 _volume = vol_ctrl->interpolate(pos, vol_interp);
583 else
584 _volume = vol_interp.sVal;
585 _controls[AC_VOLUME].dval = _volume; // Update the port.
586 v = _volume * _gain;
587 if(v > _curVolume)
588 {
589 //fprintf(stderr, "A %f %f\n", v, _curVolume);
590 if(_curVolume == 0.0)
591 _curVolume = 0.001; // Kick-start it from zero at -30dB.
592 for( ; k < nsamp; ++k)
593 {
594 _curVolume *= up_fact;
595 if(_curVolume >= v)
596 {
597 _curVolume = v;
598 break;
599 }
600 const unsigned long smp = sample + k;
601 for(int ch = start_ch; ch < trackChans; ++ch)
602 *(outBuffers[ch] + smp) = *(buffer[ch] + smp) * _curVolume;
603 }
604 }
605 else
606 if(v < _curVolume)
607 {
608 //fprintf(stderr, "B %f %f\n", v, _curVolume);
609 for( ; k < nsamp; ++k)
610 {
611 _curVolume *= down_fact;
612 if(_curVolume <= v || _curVolume <= 0.001) // Or if less than -30dB.
613 {
614 _curVolume = v;
615 break;
616 }
617 const unsigned long smp = sample + k;
618 for(int ch = start_ch; ch < trackChans; ++ch)
619 *(outBuffers[ch] + smp) = *(buffer[ch] + smp) * _curVolume;
620 }
621 }
622
623 const unsigned long next_smp = sample + nsamp;
624 float* o_buf_p;
625 const float* buf_p;
626 for(int ch = start_ch; ch < trackChans; ++ch)
627 {
628 o_buf_p = outBuffers[ch];
629 buf_p = buffer[ch];
630 for(unsigned long smp = sample + k; smp < next_smp; ++smp)
631 o_buf_p[smp] = buf_p[smp] * _curVolume;
632 }
633 }
634 }
635
636 k = 0;
637 if((vol_interp.doInterp || pan_interp.doInterp) && MusEGlobal::audio->isPlaying())
638 {
639 for( ; k < nsamp; ++k)
640 {
641 _volume = vol_ctrl->interpolate(slice_frame + k, vol_interp);
642 v = _volume * _gain;
643 _pan = pan_ctrl->interpolate(slice_frame + k, pan_interp);
644 v1 = v * (1.0 - _pan);
645 v2 = v * (1.0 + _pan);
646 if(v1 > _curVol1)
647 {
648 //fprintf(stderr, "C %f %f \n", v1, _curVol1);
649 if(_curVol1 == 0.0)
650 _curVol1 = 0.001; // Kick-start it from zero at -30dB.
651 _curVol1 *= up_fact;
652 if(_curVol1 >= v1)
653 _curVol1 = v1;
654 }
655 else
656 if(v1 < _curVol1)
657 {
658 //fprintf(stderr, "D %f %f \n", v1, _curVol1);
659 _curVol1 *= down_fact;
660 if(_curVol1 <= v1 || _curVol1 <= 0.001) // Or if less than -30dB.
661 _curVol1 = v1;
662 }
663 *dp1++ = *sp1++ * _curVol1;
664
665 if(v2 > _curVol2)
666 {
667 //fprintf(stderr, "E %f %f \n", v2, _curVol2);
668 if(_curVol2 == 0.0)
669 _curVol2 = 0.001; // Kick-start it from zero at -30dB.
670 _curVol2 *= up_fact;
671 if(_curVol2 >= v2)
672 _curVol2 = v2;
673 }
674 else
675 if(v2 < _curVol2)
676 {
677 //fprintf(stderr, "F %f %f \n", v2, _curVol2);
678 _curVol2 *= down_fact;
679 if(_curVol2 <= v2 || _curVol2 <= 0.001) // Or if less than -30dB.
680 _curVol2 = v2;
681 }
682 *dp2++ = *sp2++ * _curVol2;
683 }
684 _controls[AC_VOLUME].dval = _volume; // Update the ports.
685 _controls[AC_PAN].dval = _pan;
686 }
687 else
688 {
689 if(vol_interp.doInterp) // And not playing...
690 _volume = vol_ctrl->interpolate(pos, vol_interp);
691 else
692 _volume = vol_interp.sVal;
693 if(pan_interp.doInterp) // And not playing...
694 _pan = pan_ctrl->interpolate(pos, pan_interp);
695 else
696 _pan = pan_interp.sVal;
697 _controls[AC_VOLUME].dval = _volume; // Update the ports.
698 _controls[AC_PAN].dval = _pan;
699 v = _volume * _gain;
700 v1 = v * (1.0 - _pan);
701 v2 = v * (1.0 + _pan);
702 if(v1 > _curVol1)
703 {
704 //fprintf(stderr, "C %f %f \n", v1, _curVol1);
705 if(_curVol1 == 0.0)
706 _curVol1 = 0.001; // Kick-start it from zero at -30dB.
707 for( ; k < nsamp; ++k)
708 {
709 _curVol1 *= up_fact;
710 if(_curVol1 >= v1)
711 {
712 _curVol1 = v1;
713 break;
714 }
715 *dp1++ = *sp1++ * _curVol1;
716 }
717 }
718 else
719 if(v1 < _curVol1)
720 {
721 //fprintf(stderr, "D %f %f \n", v1, _curVol1);
722 for( ; k < nsamp; ++k)
723 {
724 _curVol1 *= down_fact;
725 if(_curVol1 <= v1 || _curVol1 <= 0.001) // Or if less than -30dB.
726 {
727 _curVol1 = v1;
728 break;
729 }
730 *dp1++ = *sp1++ * _curVol1;
731 }
732 }
733 for( ; k < nsamp; ++k)
734 *dp1++ = *sp1++ * _curVol1;
735
736 k = 0;
737 if(v2 > _curVol2)
738 {
739 //fprintf(stderr, "E %f %f \n", v2, _curVol2);
740 if(_curVol2 == 0.0)
741 _curVol2 = 0.001; // Kick-start it from zero at -30dB.
742 for( ; k < nsamp; ++k)
743 {
744 _curVol2 *= up_fact;
745 if(_curVol2 >= v2)
746 {
747 _curVol2 = v2;
748 break;
749 }
750 *dp2++ = *sp2++ * _curVol2;
751 }
752 }
753 else
754 if(v2 < _curVol2)
755 {
756 //fprintf(stderr, "F %f %f \n", v2, _curVol2);
757 for( ; k < nsamp; ++k)
758 {
759 _curVol2 *= down_fact;
760 if(_curVol2 <= v2 || _curVol2 <= 0.001) // Or if less than -30dB.
761 {
762 _curVol2 = v2;
763 break;
764 }
765 *dp2++ = *sp2++ * _curVol2;
766 }
767 }
768 for( ; k < nsamp; ++k)
769 *dp2++ = *sp2++ * _curVol2;
770 }
771 }
772
773 #ifdef NODE_DEBUG_PROCESS
774 fprintf(stderr, "AudioTrack::processTrackCtrls end of sample:%lu nsamp:%lu\n", sample, nsamp);
775 #endif
776
777 sample += nsamp;
778 }
779
780 #ifdef NODE_DEBUG_PROCESS
781 fprintf(stderr, "AudioTrack::processTrackCtrls end of cur_slice:%d\n", cur_slice);
782 #endif
783
784 ++cur_slice; // Slice is done. Moving on to any next slice now...
785 }
786 }
787
788 //---------------------------------------------------------
789 // copyData
790 //---------------------------------------------------------
791
copyData(unsigned pos,int dstStartChan,int requestedDstChannels,int availDstChannels,int srcStartChan,int srcChannels,unsigned nframes,float ** dstBuffer,bool add,const bool * addArray)792 void AudioTrack::copyData(unsigned pos,
793 int dstStartChan, int requestedDstChannels, int availDstChannels,
794 int srcStartChan, int srcChannels,
795 unsigned nframes, float** dstBuffer,
796 bool add, const bool* addArray)
797 {
798 //Changed by T356. 12/12/09.
799 // Overhaul and streamline to eliminate multiple processing during one process loop.
800 // Was causing ticking sound with synths + multiple out routes because synths were being processed multiple times.
801 // Make better use of AudioTrack::outBuffers as a post-effect pre-volume cache system for multiple calls here during processing.
802 // Previously only WaveTrack used them. (Changed WaveTrack as well).
803
804 #ifdef NODE_DEBUG_PROCESS
805 fprintf(stderr, "MusE: AudioTrack::copyData name:%s processed:%d _haveData:%d\n", name().toLatin1().constData(), processed(), _haveData);
806 #endif
807
808 if(srcStartChan == -1)
809 srcStartChan = 0;
810 if(dstStartChan == -1)
811 dstStartChan = 0;
812
813 // Only the destination knows how many destination channels there are,
814 // while only the source (this track) knows how many source channels there are.
815 // So take care of the source channels here, and let the caller handle the destination channels.
816 const int trackChans = channels();
817 const int srcTotalOutChans = totalProcessBuffers();
818 const int requestedSrcChans = (srcChannels == -1) ? srcTotalOutChans : srcChannels;
819 int availableSrcChans = requestedSrcChans;
820 // Force a source range to fit actual available total out channels.
821 if((srcStartChan + availableSrcChans) > srcTotalOutChans)
822 availableSrcChans = srcTotalOutChans - srcStartChan;
823
824 // Special consideration for metronome: It is not part of the track list,
825 // and it has no in or out routes, yet multiple output tracks may call addData on it!
826 // We can't tell how many output tracks call it, so we can only assume there might be more than one.
827 // Not strictly necessary here because only addData is ever called, but just to be consistent...
828
829 int i;
830
831 // Protection for pre-allocated _dataBuffers.
832 if(nframes > MusEGlobal::segmentSize)
833 {
834 fprintf(stderr, "MusE: Error: AudioTrack::copyData: nframes:%u > segmentSize:%u\n", nframes, MusEGlobal::segmentSize);
835 nframes = MusEGlobal::segmentSize;
836 }
837
838 float* buffer[srcTotalOutChans];
839 double meter[trackChans];
840
841 #ifdef NODE_DEBUG_PROCESS
842 fprintf(stderr, "MusE: AudioTrack::copyData "
843 "trackChans:%d srcTotalOutChans:%d srcStartChan:%d srcChannels:%d "
844 "dstStartChan:%d"
845 "requestedSrcChans:%d availableSrcChans:%d "
846 "requestedDstChannels:%d availDstChannels:%d\n",
847 trackChans, srcTotalOutChans, srcStartChan, srcChannels,
848 dstStartChan,
849 requestedSrcChans, availableSrcChans,
850 requestedDstChannels, availDstChannels);
851 #endif
852
853 // Have we been here already during this process cycle?
854 if(processed())
855 {
856 // Is there already some data gathered from a previous call during this process cycle?
857 if(_haveData)
858 {
859 if(requestedSrcChans == 1 && requestedDstChannels >= 2)
860 {
861 const int cnt = availDstChannels > 2 ? 2 : availDstChannels;
862 int c = 0;
863 if(availableSrcChans >= 1)
864 {
865 for( ; c < cnt; ++c)
866 {
867 float* sp;
868 if(!_prefader && srcStartChan == 0 && trackChans == 1)
869 sp = outBuffersExtraMix[c]; // Use the pre-panned mono-to-stereo extra buffers.
870 else
871 sp = outBuffers[srcStartChan]; // In all other cases use the main buffers.
872 float* dp = dstBuffer[c + dstStartChan];
873 if(dp)
874 {
875 if(addArray ? addArray[c + dstStartChan] : add)
876 {
877 for(unsigned k = 0; k < nframes; ++k)
878 *dp++ += *sp++;
879 }
880 else
881 AL::dsp->cpy(dp, sp, nframes);
882 }
883 }
884 }
885 // Zero the rest of the supplied buffers.
886 for(i = dstStartChan + c; i < (dstStartChan + availDstChannels); ++i)
887 {
888 if(addArray ? addArray[i] : add)
889 continue;
890 if(dstBuffer[i])
891 {
892 if(MusEGlobal::config.useDenormalBias)
893 {
894 for(unsigned int q = 0; q < nframes; ++q)
895 dstBuffer[i][q] = MusEGlobal::denormalBias;
896 }
897 else
898 memset(dstBuffer[i], 0, sizeof(float) * nframes);
899 }
900 }
901 }
902 else if(requestedSrcChans >= 2 && requestedDstChannels == 1)
903 {
904 const int cnt = availableSrcChans > 2 ? 2 : availableSrcChans;
905 if(availDstChannels >= 1)
906 {
907 for(int sch = 0; sch < cnt; ++sch)
908 {
909 float* sp = outBuffers[srcStartChan + sch];
910 float* dp = dstBuffer[dstStartChan];
911 if(dp)
912 {
913 if((addArray ? addArray[dstStartChan] : add) || sch != 0)
914 {
915 for(unsigned k = 0; k < nframes; ++k)
916 *dp++ += *sp++;
917 }
918 else
919 AL::dsp->cpy(dp, sp, nframes);
920 }
921 }
922 }
923 else if(addArray ? !addArray[dstStartChan] : !add)
924 {
925 if(dstBuffer[dstStartChan])
926 {
927 // Zero the supplied buffer.
928 if(MusEGlobal::config.useDenormalBias)
929 {
930 for(unsigned int q = 0; q < nframes; ++q)
931 dstBuffer[dstStartChan][q] = MusEGlobal::denormalBias;
932 }
933 else
934 memset(dstBuffer[dstStartChan], 0, sizeof(float) * nframes);
935 }
936 }
937 }
938 else
939 {
940 const int cnt = availableSrcChans < availDstChannels ? availableSrcChans : availDstChannels;
941 for(int c = 0; c < cnt; ++c)
942 {
943 float* sp = outBuffers[c + srcStartChan];
944 float* dp = dstBuffer[c + dstStartChan];
945 if(dp)
946 {
947 if(addArray ? addArray[c + dstStartChan] : add)
948 {
949 for(unsigned k = 0; k < nframes; ++k)
950 *dp++ += *sp++;
951 }
952 else
953 AL::dsp->cpy(dp, sp, nframes);
954 }
955 }
956 // Zero the rest of the supplied buffers.
957 for(i = dstStartChan + cnt; i < (dstStartChan + availDstChannels); ++i)
958 {
959 if(addArray ? addArray[i] : add)
960 continue;
961 if(dstBuffer[i])
962 {
963 if(MusEGlobal::config.useDenormalBias)
964 {
965 for(unsigned int q = 0; q < nframes; ++q)
966 dstBuffer[i][q] = MusEGlobal::denormalBias;
967 }
968 else
969 memset(dstBuffer[i], 0, sizeof(float) * nframes);
970 }
971 }
972 }
973 }
974 else
975 {
976 // No data was available from a previous call during this process cycle.
977
978 //Zero the supplied buffers and just return.
979 for(i = dstStartChan; i < (dstStartChan + availDstChannels); ++i)
980 {
981 if(addArray ? addArray[i] : add)
982 continue;
983 if(dstBuffer[i])
984 {
985 if(MusEGlobal::config.useDenormalBias)
986 {
987 for(unsigned int q = 0; q < nframes; ++q)
988 dstBuffer[i][q] = MusEGlobal::denormalBias;
989 }
990 else
991 memset(dstBuffer[i], 0, sizeof(float) * nframes);
992 }
993 }
994 }
995 return;
996 }
997 else
998 {
999 // First time here during this process cycle.
1000
1001 _haveData = false; // Reset.
1002 _processed = true; // Set this now.
1003
1004 // Start by clearing the meters. There may be multiple contributions to them below.
1005 for(i = 0; i < trackChans; ++i)
1006 _meter[i] = 0.0;
1007
1008 if(off())
1009 {
1010 #ifdef NODE_DEBUG_PROCESS
1011 fprintf(stderr, "MusE: AudioTrack::copyData name:%s dstChannels:%d Off, zeroing buffers\n", name().toLatin1().constData(), availDstChannels);
1012 #endif
1013
1014 // Track is off. Zero the supplied buffers.
1015 for(i = dstStartChan; i < (dstStartChan + availDstChannels); ++i)
1016 {
1017 if(addArray ? addArray[i] : add)
1018 continue;
1019 if(dstBuffer[i])
1020 {
1021 if(MusEGlobal::config.useDenormalBias)
1022 {
1023 for(unsigned int q = 0; q < nframes; ++q)
1024 dstBuffer[i][q] = MusEGlobal::denormalBias;
1025 }
1026 else
1027 memset(dstBuffer[i], 0, sizeof(float) * nframes);
1028 }
1029 }
1030
1031 _efxPipe->apply(pos, 0, nframes, 0); // Just process controls only, not audio (do not 'run').
1032 processTrackCtrls(pos, 0, nframes, 0);
1033
1034 //for(i = 0; i < trackChans; ++i)
1035 // _meter[i] = 0.0;
1036
1037 return;
1038 }
1039
1040 // Point the input buffers at a temporary buffer.
1041 for(i = 0; i < srcTotalOutChans; ++i)
1042 buffer[i] = _dataBuffers[i];
1043
1044 // getData can use the supplied buffers, or change buffer to point to its own local buffers or Jack buffers etc.
1045 // For ex. if this is an audio input, Jack will set the pointers for us in AudioInput::getData!
1046 // Don't do any processing at all if off. Whereas, mute needs to be ready for action at all times,
1047 // so still call getData before it. Off is NOT meant to be toggled rapidly, but mute is !
1048 // Since the meters are cleared above, getData can contribute (add) to them directly and return HaveMeterDataOnly
1049 // if it does not want to pass the audio for listening.
1050 if(!getData(pos, srcTotalOutChans, nframes, buffer))
1051 {
1052 #ifdef NODE_DEBUG_PROCESS
1053 fprintf(stderr, "MusE: AudioTrack::copyData name:%s srcTotalOutChans:%d zeroing buffers\n", name().toLatin1().constData(), srcTotalOutChans);
1054 #endif
1055
1056 // No data was available. Track is not off. Zero the working buffers and continue on.
1057 unsigned int q;
1058 for(i = 0; i < srcTotalOutChans; ++i)
1059 {
1060 float* buf_p = buffer[i];
1061 if(MusEGlobal::config.useDenormalBias)
1062 {
1063 for(q = 0; q < nframes; /*++q*/)
1064 buf_p[q++] = MusEGlobal::denormalBias;
1065 }
1066 else
1067 memset(buf_p, 0, sizeof(float) * nframes);
1068 }
1069 }
1070
1071 //---------------------------------------------------
1072 // apply plugin chain
1073 //---------------------------------------------------
1074
1075 // Allow it to process even if muted so that when mute is turned off, left-over buffers (reverb tails etc) can die away.
1076 _efxPipe->apply(pos, trackChans, nframes, buffer);
1077
1078 //---------------------------------------------------
1079 // apply volume, pan
1080 //---------------------------------------------------
1081
1082 processTrackCtrls(pos, trackChans, nframes, buffer);
1083
1084 const int valid_out_bufs = _prefader ? 0 : trackChans;
1085
1086 //---------------------------------------------------
1087 // metering
1088 //---------------------------------------------------
1089
1090 // FIXME TODO Need multichannel changes here?
1091 for(int c = 0; c < trackChans; ++c)
1092 {
1093 meter[c] = 0.0;
1094 float* sp = (c >= valid_out_bufs) ? buffer[c] : outBuffers[c]; // Optimize: Don't all valid outBuffers just for meters
1095 for(unsigned k = 0; k < nframes; ++k)
1096 {
1097 const double f = fabs(*sp++); // If the track is mono pan has no effect on meters.
1098 if(f > meter[c])
1099 meter[c] = f;
1100 }
1101 if(meter[c] > _meter[c])
1102 _meter[c] = meter[c];
1103 if(_meter[c] > _peak[c])
1104 _peak[c] = _meter[c];
1105
1106 if(_meter [c] > 1.0)
1107 _isClipped[c] = true;
1108 }
1109
1110 // REMOVE Tim. monitor. Changed.
1111 // if(isMute())
1112 // Are both playback and input are muted?
1113 if(isMute() && !isRecMonitored())
1114 {
1115 // Nothing to do. Zero the supplied buffers.
1116 for(i = dstStartChan; i < (dstStartChan + availDstChannels); ++i)
1117 {
1118 if(addArray ? addArray[i] : add)
1119 continue;
1120 if(dstBuffer[i])
1121 {
1122 if(MusEGlobal::config.useDenormalBias)
1123 {
1124 for(unsigned int q = 0; q < nframes; q++)
1125 dstBuffer[i][q] = MusEGlobal::denormalBias;
1126 }
1127 else
1128 memset(dstBuffer[i], 0, sizeof(float) * nframes);
1129 }
1130 }
1131 return; // We're outta here.
1132 }
1133
1134 // Copy whole blocks that we can get away with here outside of the track control processing loop.
1135 for(i = valid_out_bufs; i < srcTotalOutChans; ++i)
1136 AL::dsp->cpy(outBuffers[i], buffer[i], nframes);
1137
1138 // We now have some data! Set to true.
1139 _haveData = true;
1140
1141 //---------------------------------------------------
1142 // aux sends
1143 //---------------------------------------------------
1144
1145 if(hasAuxSend())
1146 {
1147 AuxList* al = MusEGlobal::song->auxs();
1148 unsigned naux = al->size();
1149 for(unsigned k = 0; k < naux; ++k)
1150 {
1151 double m = _auxSend[k];
1152 if(m <= 0.0001) // optimize
1153 continue;
1154 AudioAux* a = (AudioAux*)((*al)[k]);
1155 float** dst = a->sendBuffer();
1156 int auxChannels = a->channels();
1157 if((trackChans ==1 && auxChannels==1) || trackChans == 2)
1158 {
1159 for(int ch = 0; ch < trackChans; ++ch)
1160 {
1161 float* db = dst[ch % a->channels()]; // no matter whether there's one or two dst buffers
1162 float* sb = outBuffers[ch];
1163 for(unsigned f = 0; f < nframes; ++f)
1164 *db++ += (*sb++ * m); // add to mix
1165 }
1166 }
1167 else if(trackChans==1 && auxChannels==2) // copy mono to both channels
1168 {
1169 for(int ch = 0; ch < auxChannels; ++ch)
1170 {
1171 float* db = dst[ch % a->channels()];
1172 float* sb = outBuffers[0];
1173 for(unsigned f = 0; f < nframes; ++f)
1174 *db++ += (*sb++ * m); // add to mix
1175 }
1176 }
1177 }
1178 }
1179
1180 //---------------------------------------------------
1181 // copy to destination buffers
1182 //---------------------------------------------------
1183
1184 // FIXME TODO Need multichannel changes here?
1185 // Sanity check. Is source starting channel out of range? Just zero and return.
1186 if(srcStartChan >= srcTotalOutChans)
1187 {
1188 for(i = dstStartChan; i < (dstStartChan + availDstChannels); ++i)
1189 {
1190 if(addArray ? addArray[i] : add)
1191 continue;
1192 if(dstBuffer[i])
1193 {
1194 if(MusEGlobal::config.useDenormalBias)
1195 {
1196 for(unsigned int q = 0; q < nframes; q++)
1197 dstBuffer[i][q] = MusEGlobal::denormalBias;
1198 }
1199 else
1200 memset(dstBuffer[i], 0, sizeof(float) * nframes);
1201 }
1202 }
1203 return;
1204 }
1205
1206 if(requestedSrcChans == 1 && requestedDstChannels >= 2)
1207 {
1208 const int cnt = availDstChannels > 2 ? 2 : availDstChannels;
1209 int c = 0;
1210 if(availableSrcChans >= 1)
1211 {
1212 for( ; c < cnt; ++c)
1213 {
1214 float* sp;
1215 if(!_prefader && srcStartChan == 0 && trackChans == 1)
1216 sp = outBuffersExtraMix[c]; // Use the pre-panned mono-to-stereo extra buffers.
1217 else
1218 sp = outBuffers[srcStartChan]; // In all other cases use the main buffers.
1219 float* dp = dstBuffer[c + dstStartChan];
1220 if(dp)
1221 {
1222 if(addArray ? addArray[c + dstStartChan] : add)
1223 {
1224 for(unsigned k = 0; k < nframes; ++k)
1225 *dp++ += *sp++;
1226 }
1227 else
1228 AL::dsp->cpy(dp, sp, nframes);
1229 }
1230 }
1231 }
1232 // Zero the rest of the supplied buffers.
1233 for(i = dstStartChan + c; i < (dstStartChan + availDstChannels); ++i)
1234 {
1235 if(addArray ? addArray[i] : add)
1236 continue;
1237 if(dstBuffer[i])
1238 {
1239 if(MusEGlobal::config.useDenormalBias)
1240 {
1241 for(unsigned int q = 0; q < nframes; ++q)
1242 dstBuffer[i][q] = MusEGlobal::denormalBias;
1243 }
1244 else
1245 memset(dstBuffer[i], 0, sizeof(float) * nframes);
1246 }
1247 }
1248 }
1249 else if(requestedSrcChans >= 2 && requestedDstChannels == 1)
1250 {
1251 const int cnt = availableSrcChans > 2 ? 2 : availableSrcChans;
1252 if(availDstChannels >= 1)
1253 {
1254 for(int sch = 0; sch < cnt; ++sch)
1255 {
1256 float* sp = outBuffers[srcStartChan + sch];
1257 float* dp = dstBuffer[dstStartChan];
1258 if(dp)
1259 {
1260 if((addArray ? addArray[dstStartChan] : add) || sch != 0)
1261 {
1262 for(unsigned k = 0; k < nframes; ++k)
1263 *dp++ += *sp++;
1264 }
1265 else
1266 AL::dsp->cpy(dp, sp, nframes);
1267 }
1268 }
1269 }
1270 else if(addArray ? !addArray[dstStartChan] : !add)
1271 {
1272 if(dstBuffer[dstStartChan])
1273 {
1274 // Zero the supplied buffer.
1275 if(MusEGlobal::config.useDenormalBias)
1276 {
1277 for(unsigned int q = 0; q < nframes; ++q)
1278 dstBuffer[dstStartChan][q] = MusEGlobal::denormalBias;
1279 }
1280 else
1281 memset(dstBuffer[dstStartChan], 0, sizeof(float) * nframes);
1282 }
1283 }
1284 }
1285 else //if(srcChans == dstChans)
1286 {
1287 const int cnt = availableSrcChans < availDstChannels ? availableSrcChans : availDstChannels;
1288 for(int c = 0; c < cnt; ++c)
1289 {
1290 float* sp = outBuffers[c + srcStartChan];
1291 float* dp = dstBuffer[c + dstStartChan];
1292 if(dp)
1293 {
1294 if(addArray ? addArray[c + dstStartChan] : add)
1295 {
1296 for(unsigned k = 0; k < nframes; ++k)
1297 *dp++ += *sp++;
1298 }
1299 else
1300 AL::dsp->cpy(dp, sp, nframes);
1301 }
1302 }
1303 // Zero the rest of the supplied buffers.
1304 for(i = dstStartChan + cnt; i < (dstStartChan + availDstChannels); ++i)
1305 {
1306 if(addArray ? addArray[i] : add)
1307 continue;
1308 if(dstBuffer[i])
1309 {
1310 if(MusEGlobal::config.useDenormalBias)
1311 {
1312 for(unsigned int q = 0; q < nframes; ++q)
1313 dstBuffer[i][q] = MusEGlobal::denormalBias;
1314 }
1315 else
1316 memset(dstBuffer[i], 0, sizeof(float) * nframes);
1317 }
1318 }
1319 }
1320 }
1321 }
1322
1323 //---------------------------------------------------------
1324 // readVolume
1325 //---------------------------------------------------------
1326
readVolume(Xml & xml)1327 void AudioTrack::readVolume(Xml& xml)
1328 {
1329 for (;;) {
1330 Xml::Token token = xml.parse();
1331 switch (token) {
1332 case Xml::Error:
1333 case Xml::End:
1334 return;
1335 case Xml::TagStart:
1336 xml.unknown("readVolume");
1337 break;
1338 case Xml::Text:
1339 setVolume(xml.s1().toDouble());
1340 break;
1341 case Xml::Attribut:
1342 if (xml.s1() == "ch")
1343 //ch = xml.s2().toInt();
1344 xml.s2();
1345 break;
1346 case Xml::TagEnd:
1347 if (xml.s1() == "volume")
1348 return;
1349 default:
1350 break;
1351 }
1352 }
1353 }
1354
1355 //---------------------------------------------------------
1356 // setChannels
1357 //---------------------------------------------------------
1358
setChannels(int n)1359 void Track::setChannels(int n)
1360 {
1361 if(n > MusECore::MAX_CHANNELS)
1362 _channels = MusECore::MAX_CHANNELS;
1363 else
1364 _channels = n;
1365 for (int i = 0; i < _channels; ++i) {
1366 _meter[i] = 0.0;
1367 _peak[i] = 0.0;
1368 }
1369 }
1370
isLatencyInputTerminal()1371 bool AudioTrack::isLatencyInputTerminal()
1372 {
1373 // Have we been here before during this scan?
1374 // Just return the cached value.
1375 if(_latencyInfo._isLatencyInputTerminalProcessed)
1376 return _latencyInfo._isLatencyInputTerminal;
1377
1378 // If we're asking for the view from the record side, check if we're
1379 // passing the signal through the track via monitoring.
1380 if(!canPassThruLatency())
1381 {
1382 _latencyInfo._isLatencyInputTerminal = true;
1383 _latencyInfo._isLatencyInputTerminalProcessed = true;
1384 return true;
1385 }
1386
1387 const RouteList* rl = outRoutes();
1388 for (ciRoute ir = rl->begin(); ir != rl->end(); ++ir) {
1389 switch(ir->type)
1390 {
1391 case Route::TRACK_ROUTE:
1392 if(!ir->track)
1393 continue;
1394 if(ir->track->isMidiTrack())
1395 {
1396 // TODO
1397 }
1398 else
1399 {
1400 Track* track = ir->track;
1401 if(track->off()) // ||
1402 //(atrack->canRecordMonitor() && (MusEGlobal::config.monitoringAffectsLatency || !atrack->isRecMonitored())))
1403 //&& atrack->canRecord() && !atrack->recordFlag()))
1404 continue;
1405
1406 _latencyInfo._isLatencyInputTerminal = false;
1407 _latencyInfo._isLatencyInputTerminalProcessed = true;
1408 return false;
1409 }
1410 break;
1411
1412 default:
1413 break;
1414 }
1415 }
1416
1417 _latencyInfo._isLatencyInputTerminal = true;
1418 _latencyInfo._isLatencyInputTerminalProcessed = true;
1419 return true;
1420 }
1421
isLatencyOutputTerminal()1422 bool AudioTrack::isLatencyOutputTerminal()
1423 {
1424 // Have we been here before during this scan?
1425 // Just return the cached value.
1426 if(_latencyInfo._isLatencyOutputTerminalProcessed)
1427 return _latencyInfo._isLatencyOutputTerminal;
1428
1429 const RouteList* rl = outRoutes();
1430 for (ciRoute ir = rl->begin(); ir != rl->end(); ++ir) {
1431 switch(ir->type)
1432 {
1433 case Route::TRACK_ROUTE:
1434 if(!ir->track)
1435 continue;
1436 if(ir->track->isMidiTrack())
1437 {
1438 // TODO
1439 }
1440 else
1441 {
1442 Track* track = ir->track;
1443 if(track->off()) // ||
1444 //(atrack->canRecordMonitor() && (MusEGlobal::config.monitoringAffectsLatency || !atrack->isRecMonitored())))
1445 //&& atrack->canRecord() && !atrack->recordFlag()))
1446 continue;
1447
1448 _latencyInfo._isLatencyOutputTerminal = false;
1449 _latencyInfo._isLatencyOutputTerminalProcessed = true;
1450 return false;
1451 }
1452 break;
1453
1454 default:
1455 break;
1456 }
1457 }
1458
1459 _latencyInfo._isLatencyOutputTerminal = true;
1460 _latencyInfo._isLatencyOutputTerminalProcessed = true;
1461 return true;
1462 }
1463
1464 //---------------------------------------------------------
1465 // putFifo
1466 //---------------------------------------------------------
1467
putFifo(int channels,unsigned long n,float ** bp)1468 bool AudioTrack::putFifo(int channels, unsigned long n, float** bp)
1469 {
1470 float route_worst_case_latency = 0.0f;
1471 const bool use_latency_corr = useLatencyCorrection();
1472 if(use_latency_corr)
1473 {
1474 // Are we bouncing this (audio output) track to a file,
1475 // or bouncing an audio output track to this (wave) track?
1476 if(MusEGlobal::song->bounceOutput == this ||
1477 (MusEGlobal::song->bounceOutput && MusEGlobal::song->bounceTrack == this))
1478 {
1479 // We want the bounce audio output track's output latency - without the port latency.
1480 const TrackLatencyInfo& li = MusEGlobal::song->bounceOutput->getLatencyInfo(false /*output*/);
1481 route_worst_case_latency = li._inputLatency + li._worstPluginLatency;
1482 }
1483 else
1484 {
1485 // We want this (wave) track's input latency.
1486 const TrackLatencyInfo& li = getLatencyInfo(true /*input*/);
1487 route_worst_case_latency = li._inputLatency;
1488 }
1489 }
1490
1491 const unsigned int fin_frame = MusEGlobal::audio->pos().frame();
1492
1493 //fprintf(stderr, "AudioTrack::putFifo: latency:%f\n", route_worst_case_latency);
1494
1495 if(fifo.put(channels, n, bp, fin_frame, route_worst_case_latency))
1496 {
1497 fprintf(stderr, "AudioTrack::putFifo: fifo overrun: frame:%d, channels:%d, nframes:%lu\n", fin_frame, channels, n);
1498 return false;
1499 }
1500
1501 return true;
1502 }
1503
1504 //---------------------------------------------------------
1505 // getData
1506 // return false if no data available
1507 //---------------------------------------------------------
1508
getData(unsigned pos,int channels,unsigned nframes,float ** buffer)1509 bool AudioTrack::getData(unsigned pos, int channels, unsigned nframes, float** buffer)
1510 {
1511 // use supplied buffers
1512 const RouteList* rl = inRoutes();
1513 const bool use_latency_corr = useLatencyCorrection();
1514
1515 #ifdef NODE_DEBUG_PROCESS
1516 fprintf(stderr, "AudioTrack::getData name:%s channels:%d inRoutes:%d\n", name().toLatin1().constData(), channels, int(rl->size()));
1517 #endif
1518
1519 int dst_ch, dst_chs, src_ch, src_chs, fin_dst_chs, next_chan, i;
1520 unsigned int q;
1521 unsigned long int l;
1522
1523 bool have_data = false;
1524 bool used_in_chan_array[channels];
1525 for(i = 0; i < channels; ++i)
1526 used_in_chan_array[i] = false;
1527
1528 for (ciRoute ir = rl->begin(); ir != rl->end(); ++ir) {
1529 if(ir->type != Route::TRACK_ROUTE || !ir->track || ir->track->isMidiTrack())
1530 continue;
1531
1532 // Only this track knows how many destination channels there are,
1533 // while only the route track knows how many source channels there are.
1534 // So take care of the destination channels here, and let the route track handle the source channels.
1535 dst_ch = ir->channel <= -1 ? 0 : ir->channel;
1536 if(dst_ch >= channels)
1537 continue;
1538 dst_chs = ir->channels <= -1 ? channels : ir->channels;
1539 src_ch = ir->remoteChannel <= -1 ? 0 : ir->remoteChannel;
1540 src_chs = ir->channels;
1541
1542 fin_dst_chs = dst_chs;
1543 if(dst_ch + fin_dst_chs > channels)
1544 fin_dst_chs = channels - dst_ch;
1545
1546 #ifdef NODE_DEBUG_PROCESS
1547 fprintf(stderr, " calling copy/addData on %s dst_ch:%d dst_chs:%d fin_dst_chs:%d src_ch:%d src_chs:%d ...\n",
1548 ir->track->name().toLatin1().constData(),
1549 dst_ch, dst_chs, fin_dst_chs,
1550 src_ch, src_chs);
1551 #endif
1552
1553 static_cast<AudioTrack*>(ir->track)->copyData(pos,
1554 dst_ch, dst_chs, fin_dst_chs,
1555 src_ch, src_chs,
1556 nframes, buffer,
1557 false, use_latency_corr ? nullptr : used_in_chan_array);
1558
1559 // Prepare the latency value to be passed to the compensator's writer,
1560 // by adjusting each route latency value. ie. the route with the worst-case
1561 // latency will get ZERO delay, while routes having smaller latency will get
1562 // MORE delay, to match all the signal timings together.
1563 // The route's audioLatencyOut should have already been calculated and
1564 // conveniently stored in the route.
1565 if((long int)ir->audioLatencyOut < 0)
1566 l = 0;
1567 else
1568 l = ir->audioLatencyOut;
1569
1570 next_chan = dst_ch + fin_dst_chs;
1571 for(i = dst_ch; i < next_chan; ++i)
1572 {
1573 if(use_latency_corr)
1574 {
1575 // Write the buffers to the latency compensator.
1576 // By now, each copied channel should have the same latency.
1577 // They will be read back later, in-place.
1578 _latencyComp->write(i, nframes, l + latencyCompWriteOffset(), buffer[i]);
1579 }
1580 used_in_chan_array[i] = true;
1581 }
1582 have_data = true;
1583 }
1584
1585 for(i = 0; i < channels; ++i)
1586 {
1587 if(used_in_chan_array[i])
1588 {
1589 // Read back the latency compensated signals, using the buffers in-place.
1590 if(use_latency_corr)
1591 _latencyComp->read(i, nframes, buffer[i]);
1592
1593 continue;
1594 }
1595 // Fill unused channels with silence.
1596 // Channel is unused. Zero the supplied buffer.
1597 if(MusEGlobal::config.useDenormalBias)
1598 {
1599 for(q = 0; q < nframes; ++q)
1600 buffer[i][q] = MusEGlobal::denormalBias;
1601 }
1602 else
1603 memset(buffer[i], 0, sizeof(float) * nframes);
1604 }
1605
1606 return have_data;
1607 }
1608
1609 //---------------------------------------------------------
1610 // getData
1611 // return true if data
1612 //---------------------------------------------------------
1613
getData(unsigned,int channels,unsigned nframes,float ** buffer)1614 bool AudioInput::getData(unsigned, int channels, unsigned nframes, float** buffer)
1615 {
1616 if (!MusEGlobal::checkAudioDevice()) return false;
1617
1618 const bool use_latency_corr = useLatencyCorrection();
1619 unsigned long latency_array[channels];
1620 unsigned long worst_case_latency = 0;
1621 for(int i = 0; i < channels; ++i) {
1622 // For Audio Input tracks this is the track latency (rack plugins etc)
1623 // PLUS the Jack latency, on the given channel.
1624 // Note that if there are multiple connections to one of our Jack ports,
1625 // we ask Jack for the maximum latency, even though there's nothing we
1626 // can do about it since the data has already been mixed.
1627 // (Therefore always best for user to use separate ports or channels or
1628 // input tracks for each input connection.)
1629 const float f = selfLatencyAudio(i);
1630 latency_array[i] = f;
1631 if(f > worst_case_latency)
1632 worst_case_latency = f;
1633 }
1634 // Adjust the array values to arrive at forward write offsets to be passed to the latency compensator.
1635 for(int i = 0; i < channels; ++i)
1636 latency_array[i] = worst_case_latency - latency_array[i];
1637
1638
1639
1640 for (int ch = 0; ch < channels; ++ch)
1641 {
1642 void* jackPort = jackPorts[ch];
1643
1644 // Do not get buffers of unconnected client ports. Causes repeating leftover data, can be loud, or DC !
1645 if (jackPort && MusEGlobal::audioDevice->connections(jackPort))
1646 {
1647 //buffer[ch] = MusEGlobal::audioDevice->getBuffer(jackPort, nframes);
1648 // If the client port buffer is also used by another channel (connected to the same jack port),
1649 // don't directly set pointer, copy the data instead.
1650 // Otherwise the next channel will interfere - it will overwrite the buffer !
1651 // Verified symptoms: Can't use a splitter. Mono noise source on a stereo track sounds in mono. Etc...
1652 // TODO: Problem: What if other Audio Input tracks share the same jack ports as this Audio Input track?
1653 // Users will expect that Audio Inputs just work even if the input routes originate from the same jack port.
1654 // Solution: Rather than having to iterate all other channels, and all other Audio Input tracks and check
1655 // their channel port buffers (if that's even possible) in order to determine if the buffer is shared,
1656 // let's just copy always, for now shall we ?
1657 float* jackbuf = MusEGlobal::audioDevice->getBuffer(jackPort, nframes);
1658 AL::dsp->cpy(buffer[ch], jackbuf, nframes);
1659
1660 // Take care of the denormals now if there's no latency compensator.
1661 if (!use_latency_corr && MusEGlobal::config.useDenormalBias)
1662 {
1663 for (unsigned int i=0; i < nframes; i++)
1664 buffer[ch][i] += MusEGlobal::denormalBias;
1665 }
1666
1667 // Write the buffers to the latency compensator.
1668 // They will be read back later, in-place.
1669 if(use_latency_corr)
1670 _latencyComp->write(ch, nframes, latency_array[ch], buffer[ch]);
1671 }
1672 else
1673 {
1674 // Don't bother setting the denormal data here if using the latency compensator.
1675 if(!use_latency_corr)
1676 {
1677
1678 if (MusEGlobal::config.useDenormalBias)
1679 {
1680 for (unsigned int i=0; i < nframes; i++)
1681 buffer[ch][i] = MusEGlobal::denormalBias;
1682 }
1683 else
1684 {
1685 memset(buffer[ch], 0, nframes * sizeof(float));
1686 }
1687
1688 }
1689
1690 }
1691 }
1692
1693
1694 //#ifdef NODE_DEBUG_TERMINAL_PEAK_METERS
1695 #if 0
1696 if(MusEGlobal::audio->isPlaying())
1697 {
1698 fprintf(stderr, "AudioInput::getData() name:%s\n",
1699 name().toLatin1().constData());
1700 for(int ch = 0; ch < _channels; ++ch)
1701 {
1702 fprintf(stderr, "channel:%d peak:", ch);
1703 float val;
1704 float peak = 0.0f;
1705 const float* buf = buffer[ch];
1706 for(unsigned int smp = 0; smp < nframes; ++smp)
1707 {
1708 val = buf[smp];
1709 if(val > peak)
1710 peak = val;
1711 }
1712 const int dots = peak * 20;
1713 for(int d = 0; d < dots; ++d)
1714 fprintf(stderr, "*");
1715 fprintf(stderr, "\n");
1716 }
1717 }
1718 #endif
1719
1720 if(use_latency_corr)
1721 {
1722 // Read back the latency compensated signals, using the buffers in-place.
1723 _latencyComp->read(nframes, buffer);
1724
1725 if(MusEGlobal::config.useDenormalBias)
1726 {
1727 for(int ch = 0; ch < channels; ++ch)
1728 {
1729 for(unsigned int i = 0; i < nframes; i++)
1730 buffer[ch][i] += MusEGlobal::denormalBias;
1731 }
1732 }
1733 }
1734
1735 return true;
1736 }
1737
1738 //---------------------------------------------------------
1739 // registerPorts
1740 //---------------------------------------------------------
1741
registerPorts(int idx)1742 bool AudioInput::registerPorts(int idx)
1743 {
1744 if (!MusEGlobal::checkAudioDevice()) return false;
1745 int b, e;
1746 if(idx < 0) { b = 0; e = channels(); }
1747 else { /*if(idx >= channels()) return false;*/ b = idx; e = idx + 1; }
1748 bool res = false;
1749 for (int i = b; i < e; ++i) {
1750 if (!jackPorts[i]) {
1751 const QString s = QString("%1-%2").arg(name()).arg(i).left(127);
1752 jackPorts[i] = MusEGlobal::audioDevice->registerInPort(s.toLatin1().constData(), false);
1753 if(jackPorts[i])
1754 res = true;
1755 else
1756 fprintf(stderr, "AudioInput::registerPorts: Port <%s> registration FAILED !\n", s.toLatin1().constData());
1757 }
1758 }
1759 return res;
1760 }
1761
1762 //---------------------------------------------------------
1763 // setName
1764 //---------------------------------------------------------
1765
setName(const QString & s)1766 void AudioInput::setName(const QString& s)
1767 {
1768 AudioTrack::setName(s);
1769 if (!MusEGlobal::checkAudioDevice()) return;
1770 const QString n("%1-%2");
1771 for (int i = 0; i < channels(); ++i) {
1772 if (jackPorts[i])
1773 MusEGlobal::audioDevice->setPortName(jackPorts[i], n.arg(name()).arg(i).left(127).toLatin1().constData());
1774 }
1775 }
1776
1777
1778 //---------------------------------------------------------
1779 // resetMeter
1780 //---------------------------------------------------------
1781
resetMeter()1782 void Track::resetMeter()
1783 {
1784 for (int i = 0; i < _channels; ++i)
1785 _meter[i] = 0.0;
1786 }
1787
1788 //---------------------------------------------------------
1789 // resetPeaks
1790 //---------------------------------------------------------
1791
resetPeaks()1792 void Track::resetPeaks()
1793 {
1794 for (int i = 0; i < _channels; ++i) {
1795 _peak[i] = 0.0;
1796 }
1797 _lastActivity = 0;
1798 }
1799
1800 //---------------------------------------------------------
1801 // resetAllMeter
1802 //---------------------------------------------------------
1803
resetAllMeter()1804 void Track::resetAllMeter()
1805 {
1806 TrackList* tl = MusEGlobal::song->tracks();
1807 for (iTrack i = tl->begin(); i != tl->end(); ++i)
1808 (*i)->resetMeter();
1809 }
1810
1811
1812 //---------------------------------------------------------
1813 // setRecordFlag2
1814 // real time part (executed in audio thread)
1815 //---------------------------------------------------------
1816
setRecordFlag2(bool f)1817 void AudioTrack::setRecordFlag2(bool f)
1818 {
1819 if(!canRecord())
1820 return;
1821 if (f == _recordFlag)
1822 return;
1823 _recordFlag = f;
1824 if (!_recordFlag)
1825 resetMeter();
1826 }
1827
setRecordFlag2AndCheckMonitor(bool f)1828 bool AudioTrack::setRecordFlag2AndCheckMonitor(bool f)
1829 {
1830 if (f != _recordFlag && canRecord())
1831 {
1832 _recordFlag = f;
1833 if (!_recordFlag)
1834 resetMeter();
1835 }
1836
1837 if(MusEGlobal::config.monitorOnRecord && canRecordMonitor())
1838 {
1839 if(f != _recMonitor)
1840 {
1841 _recMonitor = f;
1842 return true;
1843 }
1844 }
1845 return false;
1846 }
1847
1848 //---------------------------------------------------------
1849 // setMute
1850 //---------------------------------------------------------
1851
setMute(bool f)1852 void AudioTrack::setMute(bool f)
1853 {
1854 _mute = f;
1855 if (_mute)
1856 resetAllMeter();
1857 }
1858
1859 //---------------------------------------------------------
1860 // setOff
1861 //---------------------------------------------------------
1862
setOff(bool val)1863 void AudioTrack::setOff(bool val)
1864 {
1865 _off = val;
1866 if (val)
1867 resetAllMeter();
1868 }
1869
1870 //---------------------------------------------------------
1871 // setPrefader
1872 //---------------------------------------------------------
1873
setPrefader(bool val)1874 void AudioTrack::setPrefader(bool val)
1875 {
1876 _prefader = val;
1877 if (!_prefader && isMute())
1878 resetAllMeter();
1879 }
1880
1881
1882 //---------------------------------------------------------
1883 // canEnableRecord
1884 //---------------------------------------------------------
1885
canEnableRecord() const1886 bool WaveTrack::canEnableRecord() const
1887 {
1888 return (!noInRoute() || (this == MusEGlobal::song->bounceTrack));
1889 }
1890
1891
1892 //---------------------------------------------------------
1893 // record
1894 //---------------------------------------------------------
1895
record()1896 void AudioTrack::record()
1897 {
1898 MuseCount_t pos = 0;
1899 float latency = 0.0f;
1900 const bool use_latency_corr = useLatencyCorrection();
1901 float* buffer[_channels];
1902 while(fifo.getCount()) {
1903 if (fifo.get(_channels, MusEGlobal::segmentSize, buffer, &pos, &latency)) {
1904 fprintf(stderr, "AudioTrack::record(): empty fifo\n");
1905 return;
1906 }
1907 if (_recFile) {
1908 // Line removed by Tim. Oct 28, 2009
1909 //_recFile->seek(pos, 0);
1910 //
1911 // Fix for recorded waves being shifted ahead by an amount
1912 // equal to start record position.
1913 //
1914 // From libsndfile ChangeLog:
1915 // 2008-05-11 Erik de Castro Lopo <erikd AT mega-nerd DOT com>
1916 // * src/sndfile.c
1917 // Allow seeking past end of file during write.
1918 //
1919 // I don't know why this line would even be called, because the FIFOs'
1920 // 'pos' members operate in absolute frames, which at this point
1921 // would be shifted ahead by the start of the wave part.
1922 // So if you begin recording a new wave part at bar 4, for example, then
1923 // this line is seeking the record file to frame 288000 even before any audio is written!
1924 // Therefore, just let the write do its thing and progress naturally,
1925 // it should work OK since everything was OK before the libsndfile change...
1926 //
1927 // Tested: With the line, audio record looping sort of works, albeit with the start offset added to
1928 // the wave file. And it overwrites existing audio. (Check transport window 'overwrite' function. Tie in somehow...)
1929 // With the line, looping does NOT work with libsndfile from around early 2007 (my distro's version until now).
1930 // Therefore it seems sometime between libsndfile ~2007 and today, libsndfile must have allowed
1931 // "seek (behind) on write", as well as the "seek past end" change of 2008...
1932 //
1933 // Ok, so removing that line breaks *possible* record audio 'looping' functionality, revealed with
1934 // later libsndfile.
1935 // Try this... And while we're at it, honour the punchin/punchout, and loop functions !
1936 //
1937 // If punchin is on, or we have looped at least once, use left marker as offset.
1938 // Note that audio::startRecordPos is reset to (roughly) the left marker pos upon loop !
1939 // (Not any more! I changed Audio::Process)
1940 // Since it is possible to start loop recording before the left marker (with punchin off), we must
1941 // use startRecordPos or loopFrame or left marker, depending on punchin and whether we have looped yet.
1942 unsigned fr;
1943 if(MusEGlobal::song->punchin() && (MusEGlobal::audio->loopCount() == 0))
1944 fr = MusEGlobal::audio->getStartRecordPos().frame() > MusEGlobal::song->lPos().frame() ?
1945 MusEGlobal::audio->getStartRecordPos().frame() : MusEGlobal::song->lPos().frame();
1946 else
1947 if((MusEGlobal::audio->loopCount() > 0) && (MusEGlobal::audio->getStartRecordPos().frame() > MusEGlobal::audio->loopFrame()))
1948 fr = MusEGlobal::audio->loopFrame();
1949 else
1950 fr = MusEGlobal::audio->getStartRecordPos().frame();
1951 // Now seek and write. If we are looping and punchout is on, don't let punchout point interfere with looping point.
1952 if( (pos >= fr) && (!MusEGlobal::song->punchout() || (!MusEGlobal::song->loop() && pos < MusEGlobal::song->rPos().frame())) )
1953 {
1954 pos -= fr;
1955
1956 // Let's try to avoid accidental very large files by very large latency values?
1957 if(use_latency_corr && (latency < -1000000 || latency > 1000000))
1958 {
1959 // Try not to flood, normally.
1960 if(MusEGlobal::debugMsg)
1961 fprintf(stderr,
1962 "AudioNode::record(): Error: Latency seems excessively high:%f Trimming to +/-1000000\n",
1963 latency);
1964 if(latency < -1000000)
1965 latency = -1000000;
1966 else if(latency > 1000000)
1967 latency = 1000000;
1968 }
1969 if(!use_latency_corr || (pos >= latency))
1970 {
1971
1972 #ifdef NODE_DEBUG_TERMINAL_PEAK_METERS
1973 fprintf(stderr, "AudioNode::record(): pos:%u latency:%f\n", pos, latency);
1974 for(int ch = 0; ch < _channels; ++ch)
1975 {
1976 fprintf(stderr, "channel:%d peak:", ch);
1977 float val;
1978 float peak = 0.0f;
1979 const float* buf = buffer[ch];
1980 for(unsigned int smp = 0; smp < MusEGlobal::segmentSize; ++smp)
1981 {
1982 val = buf[smp];
1983 if(val > peak)
1984 peak = val;
1985 }
1986 const int dots = peak * 20;
1987 for(int d = 0; d < dots; ++d)
1988 fprintf(stderr, "*");
1989 fprintf(stderr, "\n");
1990 }
1991 #endif
1992
1993
1994 if(use_latency_corr)
1995 pos -= latency;
1996
1997 // FIXME If we are to support writing compressed file types, we probably shouldn't be seeking here. REMOVE Tim. Wave.
1998 _recFile->seek(pos, 0);
1999 _recFile->write(_channels, buffer, MusEGlobal::segmentSize, MusEGlobal::config.liveWaveUpdate);
2000 }
2001 }
2002
2003 }
2004 else {
2005 fprintf(stderr, "AudioNode::record(): no recFile\n");
2006 }
2007 }
2008 }
2009
2010 //---------------------------------------------------------
2011 // processInit
2012 //---------------------------------------------------------
2013
processInit(unsigned nframes)2014 void AudioOutput::processInit(unsigned nframes)
2015 {
2016 _nframes = nframes;
2017 if (!MusEGlobal::checkAudioDevice()) return;
2018 for (int i = 0; i < channels(); ++i) {
2019 buffer[i] = nullptr;
2020 if (jackPorts[i]) {
2021 buffer[i] = MusEGlobal::audioDevice->getBuffer(jackPorts[i], nframes);
2022 if(buffer[i]) {
2023 if (MusEGlobal::config.useDenormalBias) {
2024 for (unsigned int j=0; j < nframes; j++)
2025 buffer[i][j] += MusEGlobal::denormalBias;
2026 }
2027 }
2028 }
2029 }
2030 }
2031
2032 //---------------------------------------------------------
2033 // process
2034 // synthesize "n" frames at buffer offset "offset"
2035 // current frame position is "pos"
2036 //---------------------------------------------------------
2037
process(unsigned pos,unsigned offset,unsigned n)2038 void AudioOutput::process(unsigned pos, unsigned offset, unsigned n)
2039 {
2040 #ifdef NODE_DEBUG_PROCESS
2041 fprintf(stderr, "MusE: AudioOutput::process name:%s processed:%d\n", name().toLatin1().constData(), processed());
2042 #endif
2043
2044 for (int i = 0; i < _channels; ++i) {
2045 // Safety check. The port, and therefore the buffer, may be null.
2046 if(!buffer[i])
2047 return;
2048 buffer1[i] = buffer[i] + offset;
2049 }
2050 copyData(pos, -1, _channels, _channels, -1, -1, n, buffer1);
2051
2052 //#ifdef NODE_DEBUG_TERMINAL_PEAK_METERS
2053 #if 0
2054 if(MusEGlobal::audio->isPlaying())
2055 {
2056 fprintf(stderr, "AudioOutput::process() name:%s pos:%u offset:%u\n",
2057 name().toLatin1().constData(), pos, offset);
2058 for(int ch = 0; ch < _channels; ++ch)
2059 {
2060 fprintf(stderr, "channel:%d peak:", ch);
2061 float val;
2062 float peak = 0.0f;
2063 const float* buf = buffer1[ch];
2064 for(unsigned int smp = 0; smp < n; ++smp)
2065 {
2066 val = buf[smp];
2067 if(val > peak)
2068 peak = val;
2069 }
2070 const int dots = peak * 20;
2071 for(int d = 0; d < dots; ++d)
2072 fprintf(stderr, "*");
2073 fprintf(stderr, "\n");
2074 }
2075 }
2076 #endif
2077
2078 }
2079
2080 //---------------------------------------------------------
2081 // silence
2082 //---------------------------------------------------------
2083
silence(unsigned n)2084 void AudioOutput::silence(unsigned n)
2085 {
2086 processInit(n);
2087 for (int i = 0; i < channels(); ++i)
2088 if(buffer[i])
2089 {
2090 if (MusEGlobal::config.useDenormalBias) {
2091 for (unsigned int j=0; j < n; j++)
2092 buffer[i][j] = MusEGlobal::denormalBias;
2093 } else {
2094 memset(buffer[i], 0, n * sizeof(float));
2095 }
2096 }
2097 }
2098
2099 //---------------------------------------------------------
2100 // processWrite
2101 //---------------------------------------------------------
2102
processWrite()2103 void AudioOutput::processWrite()
2104 {
2105 MusECore::MetronomeSettings* metro_settings =
2106 MusEGlobal::metroUseSongSettings ? &MusEGlobal::metroSongSettings : &MusEGlobal::metroGlobalSettings;
2107
2108 if (MusEGlobal::audio->isRecording() && MusEGlobal::song->bounceOutput == this) {
2109
2110 if (MusEGlobal::audio->freewheel()) {
2111
2112 // NOTE: Tests showed that during freewheel, Jack reports zero latency on all ports.
2113 // But let's go through the motions here anyway.
2114 float latency = 0.0f;
2115 const bool use_latency_corr = useLatencyCorrection();
2116 if(use_latency_corr)
2117 {
2118 // We want this audio output track's output latency - without the port latency.
2119 const TrackLatencyInfo& li = getLatencyInfo(false /*output*/);
2120 latency = li._inputLatency + li._worstPluginLatency;
2121 // Let's try to avoid accidental very large files by very large latency values?
2122 if(latency < -1000000 || latency > 1000000)
2123 {
2124 // Try not to flood, normally.
2125 if(MusEGlobal::debugMsg)
2126 fprintf(stderr,
2127 "AudioOutput::processWrite(): Error: Latency seems excessively high:%f Trimming to +/-1000000\n",
2128 latency);
2129 if(latency < -1000000)
2130 latency = -1000000;
2131 else if(latency > 1000000)
2132 latency = 1000000;
2133 }
2134 }
2135
2136 //fprintf(stderr, "AudioOutput::processWrite(): Freewheel: _previousLatency:%f latency:%f _recFilePos:%ld audio pos frame:%u\n",
2137 // _previousLatency, latency, _recFilePos, MusEGlobal::audio->pos().frame());
2138
2139 MusECore::WaveTrack* track = MusEGlobal::song->bounceTrack;
2140 if (track && track->recordFlag() && track->recFile())
2141 {
2142
2143 if(!use_latency_corr || _recFilePos >= latency)
2144 {
2145 // Has the latency changed?
2146 if(use_latency_corr && latency != _previousLatency)
2147 {
2148 long int pos = _recFilePos;
2149 pos -= latency;
2150
2151 //fprintf(stderr, "AudioOutput::processWrite(): latency:%f Seeking track _recFile to:%ld\n", latency, pos);
2152
2153 track->recFile()->seek(pos, 0);
2154 _previousLatency = latency;
2155 }
2156
2157 //fprintf(stderr, "AudioOutput::processWrite(): Writing track _recFile\n");
2158
2159 track->recFile()->write(_channels, buffer, _nframes, MusEGlobal::config.liveWaveUpdate);
2160 }
2161 _recFilePos += _nframes;
2162 }
2163
2164 if (recordFlag() && recFile())
2165 {
2166 if(!use_latency_corr || _recFilePos >= latency)
2167 {
2168 // Has the latency changed?
2169 if(use_latency_corr && latency != _previousLatency)
2170 {
2171 long int pos = _recFilePos;
2172 pos -= latency;
2173
2174 //fprintf(stderr, "AudioOutput::processWrite(): latency:%f Seeking _recFile to:%ld\n", latency, pos);
2175
2176 _recFile->seek(pos, 0);
2177 _previousLatency = latency;
2178 }
2179
2180 //fprintf(stderr, "AudioOutput::processWrite(): Writing _recFile\n");
2181
2182 _recFile->write(_channels, buffer, _nframes, MusEGlobal::config.liveWaveUpdate);
2183 }
2184 _recFilePos += _nframes;
2185 }
2186 }
2187 else {
2188 MusECore::WaveTrack* track = MusEGlobal::song->bounceTrack;
2189 if (track && track->recordFlag() && track->recFile())
2190 track->putFifo(_channels, _nframes, buffer);
2191 if (recordFlag() && recFile())
2192 putFifo(_channels, _nframes, buffer);
2193 }
2194 }
2195 if (sendMetronome() && metro_settings->audioClickFlag && MusEGlobal::song->click()) {
2196
2197 #ifdef METRONOME_DEBUG
2198 fprintf(stderr, "MusE: AudioOutput::processWrite Calling metronome->addData frame:%u channels:%d frames:%lu\n",
2199 MusEGlobal::audio->pos().frame(), _channels, _nframes);
2200 #endif
2201 metronome->copyData(MusEGlobal::audio->pos().frame(), -1, _channels, _channels, -1, -1, _nframes, buffer, true);
2202 }
2203
2204 MusEGlobal::wavePreview->addData(_channels, _nframes, buffer);
2205 }
2206
2207 //---------------------------------------------------------
2208 // registerPorts
2209 //---------------------------------------------------------
2210
registerPorts(int idx)2211 bool AudioOutput::registerPorts(int idx)
2212 {
2213 if (!MusEGlobal::checkAudioDevice()) return false;
2214 int b, e;
2215 if(idx < 0) { b = 0; e = channels(); }
2216 else { /*if(idx >= channels()) return false;*/ b = idx; e = idx + 1; }
2217 bool res = false;
2218 for (int i = b; i < e; ++i) {
2219 if (!jackPorts[i]) {
2220 const QString s = QString("%1-%2").arg(name()).arg(i).left(127);
2221 jackPorts[i] = MusEGlobal::audioDevice->registerOutPort(s.toLatin1().constData(), false);
2222 if(jackPorts[i])
2223 res = true;
2224 else
2225 fprintf(stderr, "AudioOutput::registerPorts: Port <%s> registration FAILED !\n", s.toLatin1().constData());
2226 }
2227 }
2228 return res;
2229 }
2230
2231 //---------------------------------------------------------
2232 // setName
2233 //---------------------------------------------------------
2234
setName(const QString & s)2235 void AudioOutput::setName(const QString& s)
2236 {
2237 AudioTrack::setName(s);
2238 if (!MusEGlobal::checkAudioDevice()) return;
2239 const QString n("%1-%2");
2240 for (int i = 0; i < channels(); ++i) {
2241 if (jackPorts[i])
2242 MusEGlobal::audioDevice->setPortName(jackPorts[i], n.arg(name()).arg(i).left(127).toLatin1().constData());
2243 }
2244 }
2245
2246 //---------------------------------------------------------
2247 // setParam
2248 //---------------------------------------------------------
2249
setParam(unsigned long i,double val)2250 void AudioTrack::setParam(unsigned long i, double val)
2251 {
2252 addScheduledControlEvent(i, val, MusEGlobal::audio->curFrame());
2253 }
2254
2255 //---------------------------------------------------------
2256 // param
2257 //---------------------------------------------------------
2258
param(unsigned long i) const2259 double AudioTrack::param(unsigned long i) const
2260 {
2261 return _controls[i].dval;
2262 }
2263
2264 //---------------------------------------------------------
2265 // setChannels
2266 //---------------------------------------------------------
2267
setChannels(int n)2268 void AudioTrack::setChannels(int n)
2269 {
2270 Track::setChannels(n);
2271 if (_efxPipe)
2272 _efxPipe->setChannels(_channels);
2273
2274 if(useLatencyCorrection())
2275 _latencyComp->setChannels(totalProcessBuffers());
2276 }
2277
2278 //---------------------------------------------------------
2279 // setTotalOutChannels
2280 //---------------------------------------------------------
2281
setTotalOutChannels(int num)2282 void AudioTrack::setTotalOutChannels(int num)
2283 {
2284 int chans = _totalOutChannels;
2285 if(num != chans)
2286 {
2287 if(_dataBuffers)
2288 {
2289 for(int i = 0; i < _totalOutChannels; ++i)
2290 {
2291 if(_dataBuffers[i])
2292 {
2293 free(_dataBuffers[i]);
2294 _dataBuffers[i] = NULL;
2295 }
2296 }
2297 delete[] _dataBuffers;
2298 _dataBuffers = NULL;
2299 }
2300
2301 _totalOutChannels = num;
2302 int new_chans = num;
2303 // Number of allocated buffers is always MAX_CHANNELS or more, even if _totalOutChannels is less.
2304 if(new_chans < MusECore::MAX_CHANNELS)
2305 new_chans = MusECore::MAX_CHANNELS;
2306 if(chans < MusECore::MAX_CHANNELS)
2307 chans = MusECore::MAX_CHANNELS;
2308 if(new_chans != chans)
2309 {
2310 if(outBuffers)
2311 {
2312 for(int i = 0; i < chans; ++i)
2313 {
2314 if(outBuffers[i])
2315 {
2316 free(outBuffers[i]);
2317 outBuffers[i] = NULL;
2318 }
2319 }
2320 delete[] outBuffers;
2321 outBuffers = NULL;
2322 }
2323 }
2324
2325 initBuffers();
2326 }
2327 chans = num;
2328 // Limit the actual track (meters, copying etc, all 'normal' operation) to two-channel stereo.
2329 if(chans > MusECore::MAX_CHANNELS)
2330 chans = MusECore::MAX_CHANNELS;
2331 setChannels(chans);
2332 }
2333
2334 //---------------------------------------------------------
2335 // setTotalInChannels
2336 //---------------------------------------------------------
2337
setTotalInChannels(int num)2338 void AudioTrack::setTotalInChannels(int num)
2339 {
2340 if(num == _totalInChannels)
2341 return;
2342
2343 _totalInChannels = num;
2344 }
2345
2346 } // namespace MusECore
2347