1 /*
2  * Copyright (C) 2000-2019 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2006-2007 Sampo Savolainen <v2@iki.fi>
4  * Copyright (C) 2006-2014 David Robillard <d@drobilla.net>
5  * Copyright (C) 2006 Jesse Chappell <jesse@essej.net>
6  * Copyright (C) 2008-2012 Carl Hetherington <carl@carlh.net>
7  * Copyright (C) 2011-2012 Sakari Bergen <sakari.bergen@beatwaves.net>
8  * Copyright (C) 2013-2015 Nick Mainsbridge <mainsbridge@gmail.com>
9  * Copyright (C) 2013-2017 John Emmas <john@creativepost.co.uk>
10  * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
11  * Copyright (C) 2014-2018 Ben Loftis <ben@harrisonconsoles.com>
12  * Copyright (C) 2015-2018 Len Ovens <len@ovenwerks.net>
13  * Copyright (C) 2016 Julien "_FrnchFrgg_" RIVAUD <frnchfrgg@free.fr>
14  * Copyright (C) 2016 Tim Mayberry <mojofunk@gmail.com>
15  * Copyright (C) 2017-2018 Johannes Mueller <github@johannes-mueller.org>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License along
28  * with this program; if not, write to the Free Software Foundation, Inc.,
29  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30  */
31 
32 #ifdef WAF_BUILD
33 #include "libardour-config.h"
34 #endif
35 
36 #include <cmath>
37 #include <cassert>
38 #include <algorithm>
39 
40 #include <glibmm.h>
41 #include <boost/algorithm/string.hpp>
42 
43 #include "pbd/xml++.h"
44 #include "pbd/enumwriter.h"
45 #include "pbd/locale_guard.h"
46 #include "pbd/memento_command.h"
47 #include "pbd/types_convert.h"
48 #include "pbd/unwind.h"
49 
50 #include "ardour/amp.h"
51 #include "ardour/audio_buffer.h"
52 #include "ardour/audio_track.h"
53 #include "ardour/audio_port.h"
54 #include "ardour/audioengine.h"
55 #include "ardour/boost_debug.h"
56 #include "ardour/buffer.h"
57 #include "ardour/buffer_set.h"
58 #include "ardour/capturing_processor.h"
59 #include "ardour/debug.h"
60 #include "ardour/delivery.h"
61 #include "ardour/disk_reader.h"
62 #include "ardour/disk_writer.h"
63 #include "ardour/event_type_map.h"
64 #include "ardour/gain_control.h"
65 #include "ardour/internal_return.h"
66 #include "ardour/internal_send.h"
67 #include "ardour/meter.h"
68 #include "ardour/delayline.h"
69 #include "ardour/midi_buffer.h"
70 #include "ardour/midi_port.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/monitor_control.h"
73 #include "ardour/monitor_processor.h"
74 #include "ardour/monitor_return.h"
75 #include "ardour/pannable.h"
76 #include "ardour/panner.h"
77 #include "ardour/panner_shell.h"
78 #include "ardour/parameter_descriptor.h"
79 #include "ardour/phase_control.h"
80 #include "ardour/plugin_insert.h"
81 #include "ardour/plugin_manager.h"
82 #include "ardour/polarity_processor.h"
83 #include "ardour/port.h"
84 #include "ardour/port_insert.h"
85 #include "ardour/processor.h"
86 #include "ardour/profile.h"
87 #include "ardour/revision.h"
88 #include "ardour/route.h"
89 #include "ardour/route_group.h"
90 #include "ardour/send.h"
91 #include "ardour/session.h"
92 #include "ardour/solo_control.h"
93 #include "ardour/solo_isolate_control.h"
94 #include "ardour/types_convert.h"
95 #include "ardour/unknown_processor.h"
96 #include "ardour/utils.h"
97 #include "ardour/vca.h"
98 
99 #include "pbd/i18n.h"
100 
101 using namespace std;
102 using namespace ARDOUR;
103 using namespace PBD;
104 
105 PBD::Signal3<int,boost::shared_ptr<Route>, boost::shared_ptr<PluginInsert>, Route::PluginSetupOptions > Route::PluginSetup;
106 
107 PBD::Signal1<void, boost::weak_ptr<Route> > Route::FanOut;
108 
109 /** Base class for all routable/mixable objects (tracks and busses) */
Route(Session & sess,string name,PresentationInfo::Flag flag,DataType default_type)110 Route::Route (Session& sess, string name, PresentationInfo::Flag flag, DataType default_type)
111 	: Stripable (sess, name, PresentationInfo (flag))
112 	, GraphNode (sess._process_graph)
113 	, Muteable (sess, name)
114 	, _active (true)
115 	, _signal_latency (0)
116 	, _disk_io_point (DiskIOPreFader)
117 	, _meter_point (MeterPostFader)
118 	, _pending_meter_point (MeterPostFader)
119 	, _denormal_protection (false)
120 	, _recordable (true)
121 	, _have_internal_generator (false)
122 	, _default_type (default_type)
123 	, _instrument_fanned_out (false)
124 	, _loop_location (NULL)
125 	, _volume_applies_to_output (true)
126 	, _track_number (0)
127 	, _strict_io (false)
128 	, _in_configure_processors (false)
129 	, _initial_io_setup (false)
130 	, _in_sidechain_setup (false)
131 	, _monitor_gain (0)
132 	, _custom_meter_position_noted (false)
133 	, _pinmgr_proxy (0)
134 	, _patch_selector_dialog (0)
135 {
136 	processor_max_streams.reset();
137 
138 	g_atomic_int_set (&_pending_process_reorder, 0);
139 	g_atomic_int_set (&_pending_listen_change, 0);
140 	g_atomic_int_set (&_pending_signals, 0);
141 }
142 
143 boost::weak_ptr<Route>
weakroute()144 Route::weakroute () {
145 	return boost::weak_ptr<Route> (boost::dynamic_pointer_cast<Route> (shared_from_this ()));
146 }
147 
148 int
init()149 Route::init ()
150 {
151 	/* default master bus to use strict i/o */
152 	if (is_master() || is_monitor ()) {
153 		_strict_io = true;
154 		_meter_point = _pending_meter_point = MeterOutput;
155 	}
156 
157 	/* add standard controls */
158 
159 	_gain_control.reset (new GainControl (_session, GainAutomation));
160 	_trim_control.reset (new GainControl (_session, TrimAutomation));
161 	/* While the route has-a gain-control for consistency with Stripable and VCA
162 	 * ownership is handed over to the Amp Processor which manages the
163 	 * state of the Control and AutomationList as part of its
164 	 * Automatable API. -- Don't call add_control () here.
165 	 */
166 
167 	_solo_control.reset (new SoloControl (_session, X_("solo"), *this, *this));
168 	add_control (_solo_control);
169 	_solo_control->Changed.connect_same_thread (*this, boost::bind (&Route::solo_control_changed, this, _1, _2));
170 
171 	_mute_control.reset (new MuteControl (_session, X_("mute"), *this));
172 	add_control (_mute_control);
173 
174 	_phase_control.reset (new PhaseControl (_session, X_("phase")));
175 	add_control (_phase_control);
176 
177 	_solo_isolate_control.reset (new SoloIsolateControl (_session, X_("solo-iso"), *this));
178 	add_control (_solo_isolate_control);
179 
180 	_solo_safe_control.reset (new SoloSafeControl (_session, X_("solo-safe")));
181 	add_control (_solo_safe_control);
182 
183 	/* panning */
184 
185 	if (!(_presentation_info.flags() & PresentationInfo::MonitorOut)) {
186 		_pannable.reset (new Pannable (_session));
187 	}
188 
189 	/* input and output objects */
190 
191 	_input.reset (new IO (_session, _name, IO::Input, _default_type));
192 	_output.reset (new IO (_session, _name, IO::Output, _default_type));
193 
194 	_input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
195 	_input->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::input_port_count_changing, this, _1));
196 
197 	_output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
198 	_output->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::output_port_count_changing, this, _1));
199 
200 	/* add the amp/fader processor.
201 	 * it should be the first processor to be added on every route.
202 	 */
203 
204 	_amp.reset (new Amp (_session, X_("Fader"), _gain_control, true));
205 	_amp->activate ();
206 	_amp->set_owner (this);
207 
208 	_polarity.reset (new PolarityProcessor (_session, _phase_control));
209 	_polarity->activate();
210 	_polarity->set_owner (this);
211 
212 	if (is_monitor ()) {
213 		_amp->set_display_name (_("Monitor"));
214 	}
215 
216 	if (!is_master() && !is_monitor() && !is_auditioner()) {
217 		_delayline.reset (new DelayLine (_session, name ()));
218 	}
219 
220 	/* and input trim */
221 
222 	_trim.reset (new Amp (_session, X_("Trim"), _trim_control, false));
223 	_trim->set_display_to_user (false);
224 
225 	if (dynamic_cast<AudioTrack*>(this)) {
226 		/* we can't do this in the AudioTrack's constructor
227 		 * because _trim does not exit then
228 		 */
229 		_trim->activate();
230 	}
231 	else if (!dynamic_cast<Track*>(this) && ! (is_monitor() || is_auditioner())) {
232 		/* regular bus */
233 		_trim->activate();
234 	}
235 
236 	/* create standard processors: meter, main outs, monitor out;
237 	   they will be added to _processors by setup_invisible_processors ()
238 	*/
239 
240 	_meter.reset (new PeakMeter (_session, _name));
241 	_meter->set_owner (this);
242 	_meter->set_display_to_user (false);
243 	_meter->activate ();
244 
245 	/* set default meter type */
246 	if (is_master()) {
247 #ifdef MIXBUS
248 		set_meter_type (MeterK14);
249 #else
250 		set_meter_type (Config->get_meter_type_master ());
251 #endif
252 	} else if (dynamic_cast<Track*>(this)) {
253 		set_meter_type (Config->get_meter_type_track ());
254 	} else {
255 		set_meter_type (Config->get_meter_type_bus ());
256 	}
257 
258 	_main_outs.reset (new Delivery (_session, _output, _pannable, _mute_master, _name, Delivery::Main));
259 	/* master outut volume */
260 	if (is_master()) {
261 		_volume_control.reset (new GainControl (_session, MainOutVolume));
262 		_volume_control->set_flag (Controllable::NotAutomatable);
263 		_main_outs->add_gain (_volume_control);
264 		_volume.reset (new Amp (_session, X_("LAN Amp"), _volume_control, false));
265 		_volume->set_display_to_user (false);
266 		_volume->deactivate ();
267 	}
268 	_main_outs->activate ();
269 
270 	if (is_monitor()) {
271 		/* where we listen to tracks */
272 		_intreturn.reset (new MonitorReturn (_session));
273 		_intreturn->activate ();
274 
275 		/* the thing that provides proper control over a control/monitor/listen bus
276 		   (such as per-channel cut, dim, solo, invert, etc).
277 		*/
278 		_monitor_control.reset (new MonitorProcessor (_session));
279 		_monitor_control->activate ();
280 	}
281 	if (_presentation_info.flags() & PresentationInfo::FoldbackBus) {
282 		panner_shell()->select_panner_by_uri ("http://ardour.org/plugin/panner_balance");
283 	}
284 
285 	/* now set up processor chain and invisible processors */
286 	{
287 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
288 		{
289 			Glib::Threads::RWLock::WriterLock lm (_processor_lock);
290 			_processors.push_back (_amp);
291 		}
292 		if (!_session.loading()) {
293 			configure_processors (0);
294 		}
295 	}
296 
297 	return 0;
298 }
299 
~Route()300 Route::~Route ()
301 {
302 	DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
303 
304 	/* do this early so that we don't get incoming signals as we are going through destruction
305 	 */
306 
307 	drop_connections ();
308 
309 	/* don't use clear_processors here, as it depends on the session which may
310 	   be half-destroyed by now
311 	*/
312 
313 	Glib::Threads::RWLock::WriterLock lm (_processor_lock);
314 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
315 		(*i)->drop_references ();
316 	}
317 
318 	_processors.clear ();
319 }
320 
321 string
ensure_track_or_route_name(string newname) const322 Route::ensure_track_or_route_name (string newname) const
323 {
324 	while (!_session.io_name_is_legal (newname)) {
325 		newname = bump_name_once (newname, ' ');
326 		if (newname == name()) {
327 			break;
328 		}
329 	}
330 	return newname;
331 }
332 
333 /** Process this route for one (sub) cycle (process thread)
334  *
335  * @param bufs Scratch buffers to use for the signal path
336  * @param start_sample Initial transport sample
337  * @param end_sample Final transport sample
338  * @param nframes Number of samples to output (to ports)
339  *
340  * Note that (end_sample - start_sample) may not be equal to nframes when the
341  * transport speed isn't 1.0 (eg varispeed).
342  */
343 void
process_output_buffers(BufferSet & bufs,samplepos_t start_sample,samplepos_t end_sample,pframes_t nframes,bool gain_automation_ok,bool run_disk_reader)344 Route::process_output_buffers (BufferSet& bufs,
345 			       samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes,
346 			       bool gain_automation_ok, bool run_disk_reader)
347 {
348 	/* Caller must hold process lock */
349 	assert (!AudioEngine::instance()->process_lock().trylock());
350 
351 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
352 	if (!lm.locked()) {
353 		// can this actually happen?
354 		// Places that need a WriterLock on (_processor_lock) must also take the process-lock.
355 		bufs.silence (nframes, 0);
356 		assert (0); // ...one way to find out.
357 		return;
358 	}
359 
360 	/* We should offset the route-owned ctrls by the given latency, however
361 	 * this only affects Mute. Other route-owned controls (solo, polarity..)
362 	 * are not automatable.
363 	 *
364 	 * Mute has its own issues since there's not a single mute-point,
365 	 * but in general
366 	 */
367 	automation_run (start_sample, nframes);
368 
369 	if (_pannable) {
370 		_pannable->automation_run (start_sample + _signal_latency, nframes);
371 	}
372 
373 	/* figure out if we're going to use gain automation */
374 	if (gain_automation_ok) {
375 		_amp->set_gain_automation_buffer (_session.gain_automation_buffer ());
376 		_amp->setup_gain_automation (
377 				start_sample + _amp->output_latency (),
378 				end_sample + _amp->output_latency (),
379 				nframes);
380 
381 		_trim->set_gain_automation_buffer (_session.trim_automation_buffer ());
382 		_trim->setup_gain_automation (
383 				start_sample + _trim->output_latency (),
384 				end_sample + _trim->output_latency (),
385 				nframes);
386 	}
387 
388 	/* We align the playhead to output. The user hears what the clock says:
389 	 * When the playhead/clock says 1:00:00:00 the user will hear the audio sample
390 	 * at 1:00:00:00. sample_start will be [sample at] 1:00:00:00
391 	 *
392 	 * e.g. clock says Time T = 0,  sample_start = 0
393 	 * Disk-read(play) -> latent-plugin (+10) -> fader-automation -> output (+5)
394 	 * -> total playback latency "disk -> out" is 15.
395 	 * -> at Time T= -15, the disk-reader reads sample T=0.
396 	 * By the Time T=0 is reached (dt=15 later) that sample is audible.
397 	 */
398 
399 	const double speed = (is_auditioner() ? 1.0 : _session.transport_speed ());
400 
401 	const sampleoffset_t latency_offset = _signal_latency + output_latency ();
402 	if (speed < 0) {
403 		/* when rolling backwards this can become negative */
404 		start_sample -= latency_offset;
405 		end_sample -= latency_offset;
406 	} else {
407 		start_sample += latency_offset;
408 		end_sample += latency_offset;
409 	}
410 
411 	/* Note: during intial pre-roll 'start_sample' as passed as argument can be negative.
412 	 * Functions calling process_output_buffers() will set  "run_disk_reader"
413 	 * to false if the pre-roll count-down is larger than playback_latency ().
414 	 *
415 	 * playback_latency() is guarnteed to be <= _signal_latency + _output->latency ()
416 	 */
417 	assert (!_disk_reader || !run_disk_reader || start_sample >= 0 || speed < 0);
418 
419 	/* however the disk-writer may need to pick up output from other tracks
420 	 * during pre-roll (in particular if this route has latent effects after the disk).
421 	 *
422 	 * e.g. track 1 play -> latency A --port--> track2 capture -> latency B ---> out
423 	 * total pre-roll = A + B.
424 	 *
425 	 * Note the disk-writer has built-in overlap detection (it's safe to run it early)
426 	 * given that
427 	 */
428 	bool run_disk_writer = false;
429 	if (_disk_writer && speed > 0) {
430 		samplecnt_t latency_preroll = _session.remaining_latency_preroll ();
431 		run_disk_writer = latency_preroll < nframes + (_signal_latency + _output_latency);
432 		if (end_sample - _disk_writer->input_latency () < _session.transport_sample ()) {
433 			run_disk_writer = true;
434 		}
435 	}
436 
437 	/* Tell main outs what to do about monitoring.  We do this so that
438 	 * on a transition between monitoring states we get a de-clicking gain
439 	 * change in the _main_outs delivery, if config.get_use_monitor_fades()
440 	 * is true.
441 	 *
442 	 * We override this in the case where we have an internal generator.
443 	 *
444 	 * FIXME: when punching in/out this also depends on latency compensated time
445 	 * for this route. monitoring_state() does not currently handle that correctly,.
446 	 *
447 	 * Also during remaining_latency_preroll, transport_rolling () is false, but
448 	 * we may need to monitor disk instead.
449 	 */
450 	const MonitorState ms = monitoring_state ();
451 	const bool silent = _have_internal_generator ? false : (ms == MonitoringSilence);
452 
453 	_main_outs->no_outs_cuz_we_no_monitor (silent);
454 
455 	/* -------------------------------------------------------------------------------------------
456 	   DENORMAL CONTROL
457 	   ----------------------------------------------------------------------------------------- */
458 	/* XXX We'll need to protect silent inputs as well as silent disk
459 	 * (when not monitoring input or monitoring disk and there's no region
460 	 * for a longer time).
461 	 *
462 	 * ...or simply drop that feature.
463 	 */
464 	if (_denormal_protection || Config->get_denormal_protection()) {
465 
466 		for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
467 			Sample* const sp = i->data();
468 			for (pframes_t nx = 0; nx < nframes; ++nx) {
469 				sp[nx] += 1.0e-27f;
470 			}
471 		}
472 	}
473 
474 
475 	/* -------------------------------------------------------------------------------------------
476 	   and go ....
477 	   ----------------------------------------------------------------------------------------- */
478 
479 	samplecnt_t latency = 0;
480 
481 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
482 
483 		bool re_inject_oob_data = false;
484 		if ((*i) == _disk_reader) {
485 			/* ignore port-count from prior plugins, use DR's count.
486 			 * see also Route::try_configure_processors_unlocked
487 			 */
488 			bufs.set_count ((*i)->output_streams());
489 
490 			/* Well now, we've made it past the disk-writer and to the disk-reader.
491 			 * Time to decide what to do about monitoring.
492 			 *
493 			 * Even when not doing MonitoringDisk, we need to run the processors,
494 			 * so that it advances its internal buffers (IFF run_disk_reader is true).
495 			 *
496 			 */
497 			if (ms == MonitoringDisk || ms == MonitoringSilence) {
498 				/* this will clear out-of-band data, too (e.g. MIDI-PC, Panic etc.
499 				 * OOB data is written at the end of the cycle (nframes - 1),
500 				 * and jack does not re-order events, so we push them back later */
501 				re_inject_oob_data = true;
502 				bufs.silence (nframes, 0);
503 			}
504 		}
505 
506 		double pspeed = speed;
507 		if ((!run_disk_reader && (*i) == _disk_reader) || (!run_disk_writer && (*i) == _disk_writer)) {
508 			/* run with speed 0, no-roll */
509 			pspeed = 0;
510 		}
511 
512 		/* Note: plugin latency may change. The plugin does inform the session via
513 		 * processor_latency_changed(). But the session may not yet have gotten around to
514 		 * update the actual worste-case and update this track's _signal_latency.
515 		 * So there can be cases where adding up all latencies may not equal _signal_latency.
516 		 *
517 		 * Also running a plugin may change the plugin's latency, so we need to
518 		 * add the latency first. Otherwise this can lead to bistable case
519 		 * in case of automation playback. e.g.
520 		 *
521 		 * cycle 1: run (t): automation (t) = on: -> increase latency
522 		 * cycle 2: run (t-latency): automation (t-latency) = off -> decrease latency
523 		 * reapeat.
524 		 */
525 
526 		if ((*i)->active ()) {
527 			if (speed < 0) {
528 				latency -= (*i)->effective_latency ();
529 			} else {
530 				latency += (*i)->effective_latency ();
531 			}
532 		}
533 
534 		if (speed < 0) {
535 			(*i)->run (bufs, start_sample + latency, end_sample + latency, pspeed, nframes, *i != _processors.back());
536 		} else {
537 			(*i)->run (bufs, start_sample - latency, end_sample - latency, pspeed, nframes, *i != _processors.back());
538 		}
539 
540 		bufs.set_count ((*i)->output_streams());
541 
542 		if (re_inject_oob_data) {
543 			write_out_of_band_data (bufs, nframes);
544 		}
545 
546 #if 0
547 		if ((*i) == _delayline) {
548 			latency += _delayline->delay ();
549 		}
550 #endif
551 	}
552 }
553 
554 void
bounce_process(BufferSet & buffers,samplepos_t start,samplecnt_t nframes,boost::shared_ptr<Processor> endpoint,bool include_endpoint,bool for_export,bool for_freeze)555 Route::bounce_process (BufferSet& buffers, samplepos_t start, samplecnt_t nframes,
556 		boost::shared_ptr<Processor> endpoint,
557 		bool include_endpoint, bool for_export, bool for_freeze)
558 {
559 	/* If no processing is required, there's no need to go any further. */
560 	if (!endpoint && !include_endpoint) {
561 		return;
562 	}
563 
564 	samplecnt_t latency = bounce_get_latency(_amp, false, for_export, for_freeze);
565 	_amp->set_gain_automation_buffer (_session.gain_automation_buffer ());
566 	_amp->setup_gain_automation (start - latency, start - latency + nframes, nframes);
567 
568 	/* trim is always at the top, for bounce no latency compensation is needed */
569 	_trim->set_gain_automation_buffer (_session.trim_automation_buffer ());
570 	_trim->setup_gain_automation (start, start + nframes, nframes);
571 
572 	latency = 0;
573 	bool seen_disk_io = false;
574 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
575 
576 		if (!include_endpoint && (*i) == endpoint) {
577 			break;
578 		}
579 
580 		if (!for_export && !seen_disk_io) {
581 			if (boost::dynamic_pointer_cast<DiskReader> (*i)) {
582 				seen_disk_io = true;
583 				buffers.set_count ((*i)->output_streams());
584 			}
585 			continue;
586 		}
587 
588 		/* if we're *not* exporting, stop processing if we come across a routing processor. */
589 		if (!for_export && !can_freeze_processor (*i, !for_freeze)) {
590 			break;
591 		}
592 
593 		/* special case the panner (export outputs)
594 		 * Ideally we'd only run the panner, not the delivery itself...
595 		 * but panners need separate input/output buffers and some context
596 		 * (panshell, panner type, etc). AFAICT there is no ill side effect
597 		 * of re-using the main delivery when freewheeling/exporting a region.
598 		 */
599 		if ((*i) == _main_outs) {
600 			assert ((*i)->does_routing());
601 			(*i)->run (buffers, start - latency, start - latency + nframes, 1.0, nframes, true);
602 			buffers.set_count ((*i)->output_streams());
603 		}
604 
605 		/* don't run any processors that do routing.
606 		 * Also don't bother with metering.
607 		 */
608 		if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
609 			(*i)->run (buffers, start - latency, start - latency + nframes, 1.0, nframes, true);
610 			buffers.set_count ((*i)->output_streams());
611 			latency += (*i)->effective_latency ();
612 		}
613 
614 		if ((*i) == endpoint) {
615 			break;
616 		}
617 	}
618 }
619 
620 samplecnt_t
bounce_get_latency(boost::shared_ptr<Processor> endpoint,bool include_endpoint,bool for_export,bool for_freeze) const621 Route::bounce_get_latency (boost::shared_ptr<Processor> endpoint,
622 		bool include_endpoint, bool for_export, bool for_freeze) const
623 {
624 	samplecnt_t latency = 0;
625 	if (!endpoint && !include_endpoint) {
626 		return latency;
627 	}
628 
629 	bool seen_disk_io = false;
630 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
631 		if (!include_endpoint && (*i) == endpoint) {
632 			break;
633 		}
634 		if (!for_export && !seen_disk_io) {
635 			if (boost::dynamic_pointer_cast<DiskReader> (*i)) {
636 				seen_disk_io = true;
637 			}
638 			continue;
639 		}
640 		if (!for_export && !can_freeze_processor (*i, !for_freeze)) {
641 			break;
642 		}
643 		if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
644 			latency += (*i)->effective_latency ();
645 		}
646 		if ((*i) == endpoint) {
647 			break;
648 		}
649 	}
650 	return latency;
651 }
652 
653 ChanCount
bounce_get_output_streams(ChanCount & cc,boost::shared_ptr<Processor> endpoint,bool include_endpoint,bool for_export,bool for_freeze) const654 Route::bounce_get_output_streams (ChanCount &cc, boost::shared_ptr<Processor> endpoint,
655 		bool include_endpoint, bool for_export, bool for_freeze) const
656 {
657 	if (!endpoint && !include_endpoint) {
658 		return cc;
659 	}
660 
661 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
662 
663 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
664 		if (!include_endpoint && (*i) == endpoint) {
665 			break;
666 		}
667 		if (!for_export && !can_freeze_processor (*i, !for_freeze)) {
668 			break;
669 		}
670 		if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
671 			cc = (*i)->output_streams();
672 		} else if (*i == _main_outs) {
673 			cc = (*i)->output_streams();
674 		}
675 		if ((*i) == endpoint) {
676 			break;
677 		}
678 	}
679 	return cc;
680 }
681 
682 ChanCount
n_process_buffers()683 Route::n_process_buffers ()
684 {
685 	return max (_input->n_ports(), processor_max_streams);
686 }
687 
688 void
monitor_run(samplepos_t start_sample,samplepos_t end_sample,pframes_t nframes)689 Route::monitor_run (samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes)
690 {
691 	assert (is_monitor());
692 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
693 	run_route (start_sample, end_sample, nframes, true, false);
694 }
695 
696 void
run_route(samplepos_t start_sample,samplepos_t end_sample,pframes_t nframes,bool gain_automation_ok,bool run_disk_reader)697 Route::run_route (samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes, bool gain_automation_ok, bool run_disk_reader)
698 {
699 	BufferSet& bufs (_session.get_route_buffers (n_process_buffers()));
700 
701 	fill_buffers_with_input (bufs, _input, nframes);
702 
703 	/* filter captured data before meter sees it */
704 	filter_input (bufs);
705 
706 	if (is_monitor()) {
707 		/* control/monitor bus ignores input ports when something is
708 		 * feeding the listen "stream". data will "arrive" into the
709 		 * route from the intreturn processor element.
710 		 */
711 		gain_t monitor_target_gain = _session.listening() && !_session.is_auditioning() ? 0. : 1.;
712 		_monitor_gain = Amp::apply_gain (bufs, _session.nominal_sample_rate (), nframes, _monitor_gain, monitor_target_gain);
713 	}
714 
715 	snapshot_out_of_band_data (nframes);
716 	/* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
717 
718 	write_out_of_band_data (bufs, nframes);
719 
720 	/* run processor chain */
721 
722 	process_output_buffers (bufs, start_sample, end_sample, nframes, gain_automation_ok, run_disk_reader);
723 
724 	/* map events (e.g. MIDI-CC) back to control-parameters */
725 	update_controls (bufs);
726 
727 	flush_processor_buffers_locked (nframes);
728 }
729 
730 void
set_listen(bool yn)731 Route::set_listen (bool yn)
732 {
733 	if (_monitor_send) {
734 		if (_monitor_send->active() == yn) {
735 			return;
736 		}
737 		if (yn) {
738 			_monitor_send->activate ();
739 		} else {
740 			_monitor_send->deactivate ();
741 		}
742 	}
743 }
744 
745 void
solo_control_changed(bool,Controllable::GroupControlDisposition)746 Route::solo_control_changed (bool, Controllable::GroupControlDisposition)
747 {
748 	/* nothing to do if we're not using AFL/PFL. But if we are, we need
749 	   to alter the active state of the monitor send.
750 	*/
751 
752 	if (Config->get_solo_control_is_listen_control ()) {
753 		set_listen (_solo_control->self_soloed() || _solo_control->get_masters_value());
754 	}
755 }
756 
757 void
push_solo_isolate_upstream(int32_t delta)758 Route::push_solo_isolate_upstream (int32_t delta)
759 {
760 	/* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
761 
762 	boost::shared_ptr<RouteList> routes = _session.get_routes ();
763 	for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
764 
765 		if ((*i).get() == this || !(*i)->can_solo()) {
766 			continue;
767 		}
768 
769 		if (feeds (*i)) {
770 			(*i)->solo_isolate_control()->mod_solo_isolated_by_upstream (delta);
771 		}
772 	}
773 }
774 
775 void
push_solo_upstream(int delta)776 Route::push_solo_upstream (int delta)
777 {
778 	DEBUG_TRACE (DEBUG::Solo, string_compose("\t ... INVERT push from %1\n", _name));
779 	for (FedBy::iterator i = _fed_by.begin(); i != _fed_by.end(); ++i) {
780 		boost::shared_ptr<Route> sr (i->r.lock());
781 		if (sr) {
782 			sr->solo_control()->mod_solo_by_others_downstream (-delta);
783 		}
784 	}
785 }
786 
787 #if 0
788 static void
789 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
790 {
791 	cerr << name << " {" << endl;
792 	for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
793 			p != procs.end(); ++p) {
794 		cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << " @ " << (*p) << endl;
795 	}
796 	cerr << "}" << endl;
797 }
798 #endif
799 
800 /** Supposing that we want to insert a Processor at a given Placement, return
801  *  the processor to add the new one before (or 0 to add at the end).
802  */
803 boost::shared_ptr<Processor>
before_processor_for_placement(Placement p)804 Route::before_processor_for_placement (Placement p)
805 {
806 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
807 
808 	ProcessorList::iterator loc;
809 
810 	if (p == PreFader) {
811 		/* generic pre-fader: insert immediately before the amp */
812 		loc = find (_processors.begin(), _processors.end(), _amp);
813 	} else {
814 		/* generic post-fader: insert right before the main outs */
815 		loc = find (_processors.begin(), _processors.end(), _main_outs);
816 	}
817 
818 	return loc != _processors.end() ? *loc : boost::shared_ptr<Processor> ();
819 }
820 
821 /** Supposing that we want to insert a Processor at a given index, return
822  *  the processor to add the new one before (or -1 to add at the end).
823  */
824 boost::shared_ptr<Processor>
before_processor_for_index(int index)825 Route::before_processor_for_index (int index)
826 {
827 	if (index == -1) {
828 		return boost::shared_ptr<Processor> ();
829 	}
830 
831 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
832 
833 	ProcessorList::iterator i = _processors.begin ();
834 	int j = 0;
835 	while (i != _processors.end() && (!(*i)->display_to_user() || j < index)) {
836 		if ((*i)->display_to_user()) {
837 			++j;
838 		}
839 
840 		++i;
841 	}
842 
843 	return (i != _processors.end() ? *i : boost::shared_ptr<Processor> ());
844 }
845 
846 /** Add a processor either pre- or post-fader
847  *  @return 0 on success, non-0 on failure.
848  */
849 int
add_processor(boost::shared_ptr<Processor> processor,Placement placement,ProcessorStreams * err,bool activation_allowed)850 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err, bool activation_allowed)
851 {
852 	return add_processor (processor, before_processor_for_placement (placement), err, activation_allowed);
853 }
854 
855 
856 /** Add a processor to a route such that it ends up with a given index into the visible processors.
857  *  @param index Index to add the processor at, or -1 to add at the end of the list.
858  *  @return 0 on success, non-0 on failure.
859  */
860 int
add_processor_by_index(boost::shared_ptr<Processor> processor,int index,ProcessorStreams * err,bool activation_allowed)861 Route::add_processor_by_index (boost::shared_ptr<Processor> processor, int index, ProcessorStreams* err, bool activation_allowed)
862 {
863 	return add_processor (processor, before_processor_for_index (index), err, activation_allowed);
864 }
865 
866 /** Add a processor to the route.
867  *  @param before An existing processor in the list, or 0; the new processor will be inserted immediately before it (or at the end).
868  *  @return 0 on success, non-0 on failure.
869  */
870 int
add_processor(boost::shared_ptr<Processor> processor,boost::shared_ptr<Processor> before,ProcessorStreams * err,bool activation_allowed)871 Route::add_processor (boost::shared_ptr<Processor> processor, boost::shared_ptr<Processor> before, ProcessorStreams* err, bool activation_allowed)
872 {
873 	assert (processor != _meter);
874 	assert (processor != _main_outs);
875 
876 	DEBUG_TRACE (DEBUG::Processors, string_compose (
877 		             "%1 adding processor %2\n", name(), processor->name()));
878 
879 	ProcessorList pl;
880 
881 	pl.push_back (processor);
882 	int rv = add_processors (pl, before, err);
883 
884 	if (rv) {
885 		return rv;
886 	}
887 
888 	if (activation_allowed && (!_session.get_bypass_all_loaded_plugins () || !processor->display_to_user ())) {
889 		processor->activate ();
890 	}
891 
892 	return 0;
893 }
894 
895 void
processor_selfdestruct(boost::weak_ptr<Processor> wp)896 Route::processor_selfdestruct (boost::weak_ptr<Processor> wp)
897 {
898 	/* We cannot destruct the processor here (usually RT-thread
899 	 * with various locks held - in case of sends also io_locks).
900 	 * Queue for deletion in low-priority thread.
901 	 */
902 	Glib::Threads::Mutex::Lock lx (selfdestruct_lock);
903 	selfdestruct_sequence.push_back (wp);
904 }
905 
906 bool
add_processor_from_xml_2X(const XMLNode & node,int version)907 Route::add_processor_from_xml_2X (const XMLNode& node, int version)
908 {
909 	XMLProperty const * prop;
910 
911 	try {
912 		boost::shared_ptr<Processor> processor;
913 
914 		/* bit of a hack: get the `placement' property from the <Redirect> tag here
915 		   so that we can add the processor in the right place (pre/post-fader)
916 		*/
917 
918 		XMLNodeList const & children = node.children ();
919 		XMLNodeList::const_iterator i = children.begin ();
920 
921 		while (i != children.end() && (*i)->name() != X_("Redirect")) {
922 			++i;
923 		}
924 
925 		Placement placement = PreFader;
926 
927 		if (i != children.end()) {
928 			if ((prop = (*i)->property (X_("placement"))) != 0) {
929 				placement = Placement (string_2_enum (prop->value(), placement));
930 			}
931 		}
932 
933 		if (node.name() == "Insert") {
934 
935 			if ((prop = node.property ("type")) != 0) {
936 
937 				if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
938 						prop->value() == "lv2" ||
939 						prop->value() == "windows-vst" ||
940 						prop->value() == "mac-vst" ||
941 						prop->value() == "lxvst" ||
942 						prop->value() == "audiounit") {
943 
944 					if (_session.get_disable_all_loaded_plugins ()) {
945 						processor.reset (new UnknownProcessor (_session, node));
946 					} else {
947 						processor.reset (new PluginInsert (_session));
948 						processor->set_owner (this);
949 					}
950 
951 				} else {
952 
953 					processor.reset (new PortInsert (_session, _pannable, _mute_master));
954 				}
955 
956 			}
957 
958 		} else if (node.name() == "Send") {
959 
960 			boost::shared_ptr<Pannable> sendpan (new Pannable (_session));
961 			processor.reset (new Send (_session, sendpan, _mute_master));
962 
963 		} else {
964 
965 			error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
966 			return false;
967 		}
968 
969 		if (processor->set_state (node, version)) {
970 			return false;
971 		}
972 
973 		//A2 uses the "active" flag in the toplevel redirect node, not in the child plugin/IO
974 		if (i != children.end()) {
975 			if ((prop = (*i)->property (X_("active"))) != 0) {
976 				if (string_to<bool> (prop->value()) && (!_session.get_bypass_all_loaded_plugins () || !processor->display_to_user ()))
977 					processor->activate();
978 				else
979 					processor->deactivate();
980 			}
981 		}
982 
983 		return (add_processor (processor, placement, 0, false) == 0);
984 	}
985 
986 	catch (failed_constructor &err) {
987 		warning << _("processor could not be created. Ignored.") << endmsg;
988 		return false;
989 	}
990 }
991 
992 
operator |=(Route::PluginSetupOptions & a,const Route::PluginSetupOptions & b)993 inline Route::PluginSetupOptions operator|= (Route::PluginSetupOptions& a, const Route::PluginSetupOptions& b) {
994 	return a = static_cast<Route::PluginSetupOptions> (static_cast <int>(a) | static_cast<int> (b));
995 }
996 
operator &=(Route::PluginSetupOptions & a,const Route::PluginSetupOptions & b)997 inline Route::PluginSetupOptions operator&= (Route::PluginSetupOptions& a, const Route::PluginSetupOptions& b) {
998 	return a = static_cast<Route::PluginSetupOptions> (static_cast <int>(a) & static_cast<int> (b));
999 }
1000 
1001 int
add_processors(const ProcessorList & others,boost::shared_ptr<Processor> before,ProcessorStreams * err)1002 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
1003 {
1004 	ProcessorList::iterator loc;
1005 	boost::shared_ptr <PluginInsert> fanout;
1006 
1007 	if (g_atomic_int_get (&_pending_process_reorder) || g_atomic_int_get (&_pending_listen_change)) {
1008 		/* we need to flush any pending re-order changes */
1009 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1010 		apply_processor_changes_rt ();
1011 	}
1012 
1013 	if (before) {
1014 		loc = find(_processors.begin(), _processors.end(), before);
1015 		if (loc == _processors.end ()) {
1016 			return 1;
1017 		}
1018 	} else {
1019 		/* nothing specified - at end */
1020 		loc = _processors.end ();
1021 	}
1022 
1023 	if (others.empty()) {
1024 		return 0;
1025 	}
1026 
1027 	ProcessorList to_skip;
1028 
1029 	// check if there's an instrument to replace or configure
1030 	for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1031 		boost::shared_ptr<PluginInsert> pi;
1032 		if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) == 0) {
1033 			continue;
1034 		}
1035 		if (!pi->plugin ()->get_info ()->is_instrument ()) {
1036 			continue;
1037 		}
1038 		boost::shared_ptr<Processor> instrument = the_instrument ();
1039 		ChanCount in (DataType::MIDI, 1);
1040 		ChanCount out (DataType::AUDIO, 2); // XXX route's out?!
1041 
1042 		PluginSetupOptions flags = None;
1043 		if (instrument) {
1044 			flags |= CanReplace;
1045 			in = instrument->input_streams ();
1046 			out = instrument->output_streams ();
1047 		}
1048 		if (pi->has_output_presets (in, out)) {
1049 			flags |= MultiOut;
1050 		}
1051 
1052 		pi->set_strict_io (_strict_io);
1053 
1054 		if (is_auditioner()) {
1055 			continue;
1056 		}
1057 
1058 		PluginSetupOptions mask = None;
1059 		if (Config->get_ask_replace_instrument ()) {
1060 			mask |= CanReplace;
1061 		}
1062 		if (Config->get_ask_setup_instrument ()) {
1063 			mask |= MultiOut;
1064 		}
1065 
1066 		flags &= mask;
1067 
1068 		if (flags != None) {
1069 			boost::optional<int> rv = PluginSetup (boost::dynamic_pointer_cast<Route>(shared_from_this ()), pi, flags);  /* EMIT SIGNAL */
1070 			int mode = rv.value_or (0);
1071 			switch (mode & 3) {
1072 				case 1:
1073 					to_skip.push_back (*i); // don't add this one;
1074 					break;
1075 				case 2:
1076 					replace_processor (instrument, *i, err);
1077 					to_skip.push_back (*i);
1078 					break;
1079 				default:
1080 					break;
1081 			}
1082 			if ((mode & 5) == 4) {
1083 				fanout = pi;
1084 			}
1085 		}
1086 	}
1087 
1088 	{
1089 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1090 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1091 		ProcessorState pstate (this);
1092 
1093 		for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1094 
1095 			if (*i == _meter) {
1096 				continue;
1097 			}
1098 			ProcessorList::iterator check = find (to_skip.begin(), to_skip.end(), *i);
1099 			if (check != to_skip.end()) {
1100 				continue;
1101 			}
1102 
1103 			boost::shared_ptr<PluginInsert> pi;
1104 
1105 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1106 				PluginManager::instance().stats_use_plugin (pi->plugin()->get_info());
1107 				pi->set_strict_io (_strict_io);
1108 			}
1109 
1110 			if (*i == _amp) {
1111 				/* Ensure that only one amp is in the list at any time */
1112 				ProcessorList::iterator check = find (_processors.begin(), _processors.end(), *i);
1113 				if (check != _processors.end()) {
1114 					if (before == _amp) {
1115 						/* Already in position; all is well */
1116 						continue;
1117 					} else {
1118 						_processors.erase (check);
1119 					}
1120 				}
1121 			}
1122 
1123 			assert (find (_processors.begin(), _processors.end(), *i) == _processors.end ());
1124 
1125 			_processors.insert (loc, *i);
1126 			(*i)->set_owner (this);
1127 
1128 			{
1129 				if (configure_processors_unlocked (err, &lm)) {
1130 					pstate.restore ();
1131 					configure_processors_unlocked (0, &lm); // it worked before we tried to add it ...
1132 					return -1;
1133 				}
1134 			}
1135 
1136 			if (pi && pi->has_sidechain ()) {
1137 				pi->update_sidechain_name ();
1138 				pi->sidechain_input ()->changed.connect_same_thread (*pi, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
1139 			}
1140 
1141 			if ((*i)->active()) {
1142 				// emit ActiveChanged() and latency_changed() if needed
1143 				(*i)->activate ();
1144 			}
1145 
1146 			(*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, &_session));
1147 
1148 			boost::shared_ptr<Send> send;
1149 			if ((send = boost::dynamic_pointer_cast<Send> (*i))) {
1150 				send->SelfDestruct.connect_same_thread (**i,
1151 						boost::bind (&Route::processor_selfdestruct, this, boost::weak_ptr<Processor> (*i)));
1152 				if (send->output()) {
1153 					send->output()->changed.connect_same_thread (**i, boost::bind (&Route::output_change_handler, this, _1, _2));
1154 				}
1155 			}
1156 		}
1157 
1158 		for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1159 			boost::shared_ptr<PluginInsert> pi;
1160 
1161 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1162 				if (pi->has_no_inputs ()) {
1163 					_have_internal_generator = true;
1164 					break;
1165 				}
1166 			}
1167 		}
1168 	}
1169 
1170 	reset_instrument_info ();
1171 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1172 	set_processor_positions ();
1173 
1174 	if (fanout && fanout->configured ()
1175 			&& fanout->output_streams().n_audio() > 2
1176 			&& boost::dynamic_pointer_cast<PluginInsert> (the_instrument ()) == fanout) {
1177 		/* This adds new tracks or busses, and changes connections.
1178 		 * This cannot be done here, and needs to be delegated to the GUI thread. */
1179 		_instrument_fanned_out = true;
1180 		FanOut (boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this())); /* EMIT SIGNAL */
1181 	}
1182 	return 0;
1183 }
1184 
1185 void
placement_range(Placement p,ProcessorList::iterator & start,ProcessorList::iterator & end)1186 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1187 {
1188 	if (p == PreFader) {
1189 		start = _processors.begin();
1190 		end = find(_processors.begin(), _processors.end(), _amp);
1191 	} else {
1192 		start = find(_processors.begin(), _processors.end(), _amp);
1193 		++start;
1194 		end = _processors.end();
1195 	}
1196 }
1197 
1198 /** Turn off all processors with a given placement
1199  * @param p Placement of processors to disable
1200  */
1201 void
disable_processors(Placement p)1202 Route::disable_processors (Placement p)
1203 {
1204 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1205 
1206 	ProcessorList::iterator start, end;
1207 	placement_range(p, start, end);
1208 
1209 	for (ProcessorList::iterator i = start; i != end; ++i) {
1210 		(*i)->enable (false);
1211 	}
1212 
1213 	_session.set_dirty ();
1214 }
1215 
1216 /** Turn off all redirects
1217  */
1218 void
disable_processors()1219 Route::disable_processors ()
1220 {
1221 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1222 
1223 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1224 		(*i)->enable (false);
1225 	}
1226 
1227 	_session.set_dirty ();
1228 }
1229 
1230 /** Turn off all redirects with a given placement
1231  * @param p Placement of redirects to disable
1232  */
1233 void
disable_plugins(Placement p)1234 Route::disable_plugins (Placement p)
1235 {
1236 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1237 
1238 	ProcessorList::iterator start, end;
1239 	placement_range(p, start, end);
1240 
1241 	for (ProcessorList::iterator i = start; i != end; ++i) {
1242 		if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1243 			(*i)->enable (false);
1244 		}
1245 	}
1246 
1247 	_session.set_dirty ();
1248 }
1249 
1250 /** Turn off all plugins
1251  */
1252 void
disable_plugins()1253 Route::disable_plugins ()
1254 {
1255 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1256 
1257 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1258 		if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1259 			(*i)->enable (false);
1260 		}
1261 	}
1262 
1263 	_session.set_dirty ();
1264 }
1265 
1266 
1267 void
ab_plugins(bool forward)1268 Route::ab_plugins (bool forward)
1269 {
1270 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1271 
1272 	if (forward) {
1273 
1274 		/* forward = turn off all active redirects, and mark them so that the next time
1275 		   we go the other way, we will revert them
1276 		*/
1277 
1278 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1279 			if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1280 				continue;
1281 			}
1282 			if (!(*i)->display_to_user () || is_internal_processor (*i)) {
1283 				continue;
1284 			}
1285 #ifdef MIXBUS
1286 			if (boost::dynamic_pointer_cast<PluginInsert> (*i)->is_channelstrip()) {
1287 				continue;
1288 			}
1289 #endif
1290 
1291 			if ((*i)->enabled ()) {
1292 				(*i)->enable (false);
1293 				(*i)->set_next_ab_is_active (true);
1294 			} else {
1295 				(*i)->set_next_ab_is_active (false);
1296 			}
1297 		}
1298 
1299 	} else {
1300 
1301 		/* backward = if the redirect was marked to go active on the next ab, do so */
1302 
1303 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1304 			if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1305 				continue;
1306 			}
1307 			if (!(*i)->display_to_user () || is_internal_processor (*i)) {
1308 				continue;
1309 			}
1310 #ifdef MIXBUS
1311 			if (boost::dynamic_pointer_cast<PluginInsert> (*i)->is_channelstrip()) {
1312 				continue;
1313 			}
1314 #endif
1315 
1316 			(*i)->enable ((*i)->get_next_ab_is_active ());
1317 		}
1318 	}
1319 
1320 	_session.set_dirty ();
1321 }
1322 
1323 
1324 /** Remove processors with a given placement.
1325  * @param p Placement of processors to remove.
1326  */
1327 void
clear_processors(Placement p)1328 Route::clear_processors (Placement p)
1329 {
1330 	if (!_session.engine().running()) {
1331 		return;
1332 	}
1333 
1334 	bool already_deleting = _session.deletion_in_progress();
1335 	if (!already_deleting) {
1336 		_session.set_deletion_in_progress();
1337 	}
1338 
1339 	ProcessorList old_list = _processors;
1340 	{
1341 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1342 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1343 		ProcessorList new_list;
1344 		ProcessorStreams err;
1345 		bool seen_amp = false;
1346 
1347 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1348 
1349 			if (*i == _amp) {
1350 				seen_amp = true;
1351 			}
1352 
1353 			if (is_internal_processor (*i)) {
1354 
1355 				/* you can't remove these */
1356 
1357 				new_list.push_back (*i);
1358 
1359 			} else {
1360 				if (seen_amp) {
1361 
1362 					switch (p) {
1363 					case PreFader:
1364 						new_list.push_back (*i);
1365 						break;
1366 					case PostFader:
1367 						(*i)->drop_references ();
1368 						break;
1369 					}
1370 
1371 				} else {
1372 
1373 					switch (p) {
1374 					case PreFader:
1375 						(*i)->drop_references ();
1376 						break;
1377 					case PostFader:
1378 						new_list.push_back (*i);
1379 						break;
1380 					}
1381 				}
1382 			}
1383 		}
1384 
1385 		_processors = new_list;
1386 		configure_processors_unlocked (&err, &lm); // this can't fail
1387 	}
1388 	/* drop references w/o process-lock (I/O procs may re-take it in ~IO() */
1389 	old_list.clear ();
1390 
1391 	processor_max_streams.reset();
1392 	_have_internal_generator = false;
1393 	reset_instrument_info ();
1394 	set_processor_positions ();
1395 
1396 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1397 
1398 	if (!already_deleting) {
1399 		_session.clear_deletion_in_progress();
1400 	}
1401 }
1402 
1403 bool
is_internal_processor(boost::shared_ptr<Processor> p) const1404 Route::is_internal_processor (boost::shared_ptr<Processor> p) const
1405 {
1406 	if (p == _amp || p == _meter || p == _main_outs || p == _delayline || p == _trim || p == _polarity || (_volume && p == _volume)) {
1407 		return true;
1408 	}
1409 #ifdef MIXBUS
1410 	if (p == _ch_pre || p == _ch_post || p == _ch_eq  || p == _ch_comp) {
1411 		return true;
1412 	}
1413 #endif
1414 	return false;
1415 }
1416 
1417 int
remove_processor(boost::shared_ptr<Processor> processor,ProcessorStreams * err,bool need_process_lock)1418 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err, bool need_process_lock)
1419 {
1420 	// TODO once the export point can be configured properly, do something smarter here
1421 	if (processor == _capturing_processor) {
1422 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1423 		if (need_process_lock) {
1424 			lx.acquire();
1425 		}
1426 
1427 		_capturing_processor.reset();
1428 
1429 		if (need_process_lock) {
1430 			lx.release();
1431 		}
1432 	}
1433 
1434 	/* these can never be removed */
1435 
1436 	if (is_internal_processor (processor)) {
1437 		return 0;
1438 	}
1439 
1440 	if (!_session.engine().running()) {
1441 		return 1;
1442 	}
1443 
1444 	processor_max_streams.reset();
1445 
1446 	{
1447 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1448 		if (need_process_lock) {
1449 			lx.acquire();
1450 		}
1451 
1452 		/* Caller must hold process lock */
1453 		assert (!AudioEngine::instance()->process_lock().trylock());
1454 
1455 		Glib::Threads::RWLock::WriterLock lm (_processor_lock); // XXX deadlock after export
1456 
1457 		ProcessorState pstate (this);
1458 
1459 		ProcessorList::iterator i = find (_processors.begin(), _processors.end(), processor);
1460 		if (i == _processors.end ()) {
1461 			/* what? */
1462 			return 1;
1463 		}
1464 
1465 		/* stop redirects that send signals to JACK ports
1466 		 * from causing noise as a result of no longer being run
1467 		 */
1468 		boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
1469 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
1470 
1471 		if (pi != 0) {
1472 			assert (iop == 0);
1473 			iop = pi->sidechain();
1474 		}
1475 
1476 		if (iop != 0) {
1477 			/* This calls Route::sidechain_change_handler -> Route::input_change_handler()
1478 			 * When the route is implicitly soloed this further calls
1479 			 * Route::direct_feeds_according_to_reality() which takes a
1480 			 * ReaderLock (_processor_lock). So we need to release the lock first.
1481 			 */
1482 			lm.release ();
1483 			iop->disconnect ();
1484 			lm.acquire ();
1485 		}
1486 
1487 		_processors.erase (i);
1488 
1489 		if (configure_processors_unlocked (err, &lm)) {
1490 			pstate.restore ();
1491 			/* we know this will work, because it worked before :) */
1492 			configure_processors_unlocked (0, &lm);
1493 			return -1;
1494 		}
1495 
1496 		_have_internal_generator = false;
1497 
1498 		for (i = _processors.begin(); i != _processors.end(); ++i) {
1499 			boost::shared_ptr<PluginInsert> pi;
1500 
1501 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1502 				if (pi->has_no_inputs ()) {
1503 					_have_internal_generator = true;
1504 					break;
1505 				}
1506 			}
1507 		}
1508 		if (need_process_lock) {
1509 			lx.release();
1510 		}
1511 	}
1512 
1513 	reset_instrument_info ();
1514 	processor->drop_references ();
1515 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1516 	set_processor_positions ();
1517 
1518 	return 0;
1519 }
1520 
1521 int
replace_processor(boost::shared_ptr<Processor> old,boost::shared_ptr<Processor> sub,ProcessorStreams * err)1522 Route::replace_processor (boost::shared_ptr<Processor> old, boost::shared_ptr<Processor> sub, ProcessorStreams* err)
1523 {
1524 	/* these can never be removed */
1525 	if (is_internal_processor (old)) {
1526 		return 1;
1527 	}
1528 	/* and can't be used as substitute, either */
1529 	if (is_internal_processor (sub)) {
1530 		return 1;
1531 	}
1532 
1533 	/* I/Os are out, too */
1534 	if (boost::dynamic_pointer_cast<IOProcessor> (old) || boost::dynamic_pointer_cast<IOProcessor> (sub)) {
1535 		return 1;
1536 	}
1537 
1538 	/* this function cannot be used to swap/reorder processors */
1539 	if (find (_processors.begin(), _processors.end(), sub) != _processors.end ()) {
1540 		return 1;
1541 	}
1542 
1543 	if (!AudioEngine::instance()->running() || !old || !sub) {
1544 		return 1;
1545 	}
1546 
1547 	/* ensure that sub is not owned by another route */
1548 	if (sub->owner ()) {
1549 		return 1;
1550 	}
1551 
1552 	{
1553 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1554 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1555 		ProcessorState pstate (this);
1556 
1557 		assert (find (_processors.begin(), _processors.end(), sub) == _processors.end ());
1558 
1559 		ProcessorList::iterator i;
1560 		bool replaced = false;
1561 		bool enable = old->enabled ();
1562 
1563 		for (i = _processors.begin(); i != _processors.end(); ) {
1564 			if (*i == old) {
1565 				i = _processors.erase (i);
1566 				_processors.insert (i, sub);
1567 				sub->set_owner (this);
1568 				replaced = true;
1569 				break;
1570 			} else {
1571 				++i;
1572 			}
1573 		}
1574 
1575 		if (!replaced) {
1576 			return 1;
1577 		}
1578 
1579 		if (_strict_io) {
1580 			boost::shared_ptr<PluginInsert> pi;
1581 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(sub)) != 0) {
1582 				pi->set_strict_io (true);
1583 			}
1584 		}
1585 
1586 		if (configure_processors_unlocked (err, &lm)) {
1587 			pstate.restore ();
1588 			configure_processors_unlocked (0, &lm);
1589 			return -1;
1590 		}
1591 
1592 		_have_internal_generator = false;
1593 
1594 		for (i = _processors.begin(); i != _processors.end(); ++i) {
1595 			boost::shared_ptr<PluginInsert> pi;
1596 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1597 				if (pi->has_no_inputs ()) {
1598 					_have_internal_generator = true;
1599 					break;
1600 				}
1601 			}
1602 		}
1603 
1604 		if (enable) {
1605 			sub->enable (true);
1606 		}
1607 
1608 		sub->ActiveChanged.connect_same_thread (*sub, boost::bind (&Session::queue_latency_recompute, &_session));
1609 	}
1610 
1611 	reset_instrument_info ();
1612 	old->drop_references ();
1613 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1614 	set_processor_positions ();
1615 	return 0;
1616 }
1617 
1618 int
remove_processors(const ProcessorList & to_be_deleted,ProcessorStreams * err)1619 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1620 {
1621 	ProcessorList deleted;
1622 
1623 	if (!_session.engine().running()) {
1624 		return 1;
1625 	}
1626 
1627 	processor_max_streams.reset();
1628 
1629 	{
1630 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1631 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1632 		ProcessorState pstate (this);
1633 
1634 		ProcessorList::iterator i;
1635 		boost::shared_ptr<Processor> processor;
1636 
1637 		for (i = _processors.begin(); i != _processors.end(); ) {
1638 
1639 			processor = *i;
1640 
1641 			/* these can never be removed */
1642 
1643 			if (is_internal_processor (processor)) {
1644 				++i;
1645 				continue;
1646 			}
1647 
1648 			/* see if its in the list of processors to delete */
1649 
1650 			if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1651 				++i;
1652 				continue;
1653 			}
1654 
1655 			/* stop IOProcessors that send to JACK ports
1656 			   from causing noise as a result of no longer being
1657 			   run.
1658 			*/
1659 
1660 			boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(processor);
1661 			boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
1662 			if (pi != 0) {
1663 				assert (iop == 0);
1664 				iop = pi->sidechain();
1665 			}
1666 
1667 			if (iop != 0) {
1668 				iop->disconnect ();
1669 			}
1670 
1671 			deleted.push_back (processor);
1672 			i = _processors.erase (i);
1673 		}
1674 
1675 		if (deleted.empty()) {
1676 			/* none of those in the requested list were found */
1677 			return 0;
1678 		}
1679 
1680 		if (configure_processors_unlocked (err, &lm)) {
1681 			pstate.restore ();
1682 			/* we know this will work, because it worked before :) */
1683 			configure_processors_unlocked (0, &lm);
1684 			return -1;
1685 		}
1686 		//lx.unlock();
1687 
1688 		_have_internal_generator = false;
1689 
1690 		for (i = _processors.begin(); i != _processors.end(); ++i) {
1691 			boost::shared_ptr<PluginInsert> pi;
1692 
1693 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1694 				if (pi->has_no_inputs ()) {
1695 					_have_internal_generator = true;
1696 					break;
1697 				}
1698 			}
1699 		}
1700 	}
1701 
1702 	/* now try to do what we need to so that those that were removed will be deleted */
1703 
1704 	for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1705 		(*i)->drop_references ();
1706 	}
1707 
1708 	reset_instrument_info ();
1709 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1710 	set_processor_positions ();
1711 
1712 	return 0;
1713 }
1714 
1715 void
reset_instrument_info()1716 Route::reset_instrument_info ()
1717 {
1718 	boost::shared_ptr<Processor> instr = the_instrument();
1719 	if (!instr) {
1720 		_instrument_fanned_out = false;
1721 	}
1722 	_instrument_info.set_internal_instrument (instr);
1723 }
1724 
1725 /** Caller must hold process lock */
1726 int
configure_processors(ProcessorStreams * err)1727 Route::configure_processors (ProcessorStreams* err)
1728 {
1729 #ifndef PLATFORM_WINDOWS
1730 	assert (!AudioEngine::instance()->process_lock().trylock());
1731 #endif
1732 
1733 	if (!_in_configure_processors) {
1734 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1735 		return configure_processors_unlocked (err, &lm);
1736 	}
1737 
1738 	return 0;
1739 }
1740 
1741 ChanCount
input_streams() const1742 Route::input_streams () const
1743 {
1744 	return _input->n_ports ();
1745 }
1746 
1747 list<pair<ChanCount, ChanCount> >
try_configure_processors(ChanCount in,ProcessorStreams * err)1748 Route::try_configure_processors (ChanCount in, ProcessorStreams* err)
1749 {
1750 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1751 
1752 	return try_configure_processors_unlocked (in, err);
1753 }
1754 
1755 list<pair<ChanCount, ChanCount> >
try_configure_processors_unlocked(ChanCount in,ProcessorStreams * err)1756 Route::try_configure_processors_unlocked (ChanCount in, ProcessorStreams* err)
1757 {
1758 	// Check each processor in order to see if we can configure as requested
1759 	ChanCount out;
1760 	list<pair<ChanCount, ChanCount> > configuration;
1761 	uint32_t index = 0;
1762 
1763 	DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1764 	DEBUG_TRACE (DEBUG::Processors, "{\n");
1765 
1766 	ChanCount disk_io = in;
1767 
1768 	for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1769 
1770 		if (boost::dynamic_pointer_cast<DiskReader> (*p)) {
1771 			/* disk-reader has the same i/o as disk-writer */
1772 			in = max (in, disk_io);
1773 		}
1774 
1775 		if ((*p)->can_support_io_configuration(in, out)) {
1776 
1777 			if (boost::dynamic_pointer_cast<Delivery> (*p)
1778 					&& boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main
1779 					&& !is_auditioner()
1780 					&& (is_monitor() || _strict_io || Profile->get_mixbus ())) {
1781 				/* with strict I/O the panner + output are forced to
1782 				 * follow the last processor's output.
1783 				 *
1784 				 * Delivery::can_support_io_configuration() will only add ports,
1785 				 * but not remove excess ports.
1786 				 *
1787 				 * This works because the delivery only requires
1788 				 * as many outputs as there are inputs.
1789 				 * Delivery::configure_io() will do the actual removal
1790 				 * by calling _output->ensure_io()
1791 				 */
1792 				if (!is_master() && _session.master_out () && in.n_audio() > 0) {
1793 					if (!is_monitor()) {
1794 						/* ..but at least as many as there are master-inputs, if
1795 						 * the delivery is dealing with audio */
1796 						out = ChanCount::max (in, _session.master_out ()->n_inputs ());
1797 					} else {
1798 						/* monitor-bus follows the master-bus' output */
1799 						out = ChanCount::max (in, _session.master_out ()->n_outputs ());
1800 					}
1801 				} else {
1802 					out = in;
1803 				}
1804 			}
1805 
1806 			DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID=%2 in=%3 out=%4\n",(*p)->name(), (*p)->id(), in, out));
1807 			configuration.push_back(make_pair(in, out));
1808 
1809 			if (is_monitor()) {
1810 				// restriction for Monitor Section Processors
1811 				if (in.n_audio() != out.n_audio() || out.n_midi() > 0) {
1812 					/* Note: The Monitor follows the master-bus and has no panner.
1813 					 *
1814 					 * The general idea is to only allow plugins that retain the channel-count
1815 					 * and plugins with MIDI in (e.g VSTs with control that will remain unconnected).
1816 					 * Then again 5.1 in, monitor stereo is a valid use-case.
1817 					 *
1818 					 * and worse: we only refuse adding plugins *here*.
1819 					 *
1820 					 * 1) stereo-master, stereo-mon, add a stereo-plugin, OK
1821 					 * 2) change master-bus, add a channel
1822 					 * 2a) monitor-secion follows
1823 					 * 3) monitor processors fail to re-reconfigure (stereo plugin)
1824 					 * 4) re-load session, monitor-processor remains unconfigured, crash.
1825 					 */
1826 					DEBUG_TRACE (DEBUG::Processors, "Monitor: Channel configuration change.\n");
1827 				}
1828 				if (boost::dynamic_pointer_cast<InternalSend> (*p)) {
1829 					// internal sends make no sense, only feedback
1830 					DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
1831 					return list<pair<ChanCount, ChanCount> > ();
1832 				}
1833 				if (boost::dynamic_pointer_cast<PortInsert> (*p)) {
1834 					/* External Sends can be problematic. one can add/remove ports
1835 					 * there signal leaves the DAW to external monitors anyway, so there's
1836 					 * no real use for allowing them here anyway.
1837 					 */
1838 					DEBUG_TRACE (DEBUG::Processors, "Monitor: No External Sends allowed.\n");
1839 					return list<pair<ChanCount, ChanCount> > ();
1840 				}
1841 				if (boost::dynamic_pointer_cast<Send> (*p)) {
1842 					// ditto
1843 					DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
1844 					return list<pair<ChanCount, ChanCount> > ();
1845 				}
1846 			}
1847 
1848 			if (boost::dynamic_pointer_cast<DiskWriter> (*p)) {
1849 				assert (in == out);
1850 				disk_io = out;
1851 			}
1852 
1853 
1854 			/* next processor's in == this processor's out*/
1855 			in = out;
1856 		} else {
1857 			if (err) {
1858 				err->index = index;
1859 				err->count = in;
1860 			}
1861 			DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
1862 			DEBUG_TRACE (DEBUG::Processors, string_compose ("---- %1 cannot support in=%2 out=%3\n", (*p)->name(), in, out));
1863 			DEBUG_TRACE (DEBUG::Processors, "}\n");
1864 			return list<pair<ChanCount, ChanCount> > ();
1865 		}
1866 	}
1867 
1868 	DEBUG_TRACE (DEBUG::Processors, "}\n");
1869 
1870 	return configuration;
1871 }
1872 
1873 /** Set the input/output configuration of each processor in the processors list.
1874  *  Caller must hold process lock.
1875  *  Return 0 on success, otherwise configuration is impossible.
1876  */
1877 int
configure_processors_unlocked(ProcessorStreams * err,Glib::Threads::RWLock::WriterLock * lm)1878 Route::configure_processors_unlocked (ProcessorStreams* err, Glib::Threads::RWLock::WriterLock* lm)
1879 {
1880 #ifndef PLATFORM_WINDOWS
1881 	assert (!AudioEngine::instance()->process_lock().trylock());
1882 #endif
1883 
1884 	if (_in_configure_processors) {
1885 		return 0;
1886 	}
1887 
1888 	/* put invisible processors where they should be */
1889 	setup_invisible_processors ();
1890 
1891 	_in_configure_processors = true;
1892 
1893 	list<pair<ChanCount, ChanCount> > configuration = try_configure_processors_unlocked (input_streams (), err);
1894 
1895 	if (configuration.empty ()) {
1896 		_in_configure_processors = false;
1897 		return -1;
1898 	}
1899 
1900 	ChanCount out;
1901 	bool seen_mains_out = false;
1902 	processor_out_streams = _input->n_ports();
1903 	processor_max_streams.reset();
1904 
1905 	/* processor configure_io() may result in adding ports
1906 	 * e.g. Delivery::configure_io -> ARDOUR::IO::ensure_io ()
1907 	 *
1908 	 * with jack2 adding ports results in a graph-order callback,
1909 	 * which calls Session::resort_routes() and eventually
1910 	 * Route::direct_feeds_according_to_reality()
1911 	 * which takes a ReaderLock (_processor_lock).
1912 	 *
1913 	 * so we can't hold a WriterLock here until jack2 threading
1914 	 * is fixed.
1915 	 *
1916 	 * NB. we still hold the process lock
1917 	 *
1918 	 * (ardour's own engines do call graph-order from the
1919 	 * process-thread and hence do not have this issue; besides
1920 	 * merely adding ports won't trigger a graph-order, only
1921 	 * making connections does)
1922 	 */
1923 	lm->release ();
1924 
1925 	// TODO check for a potential ReaderLock after ReaderLock ??
1926 	Glib::Threads::RWLock::ReaderLock lr (_processor_lock);
1927 
1928 	list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1929 	for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1930 
1931 		if (!(*p)->configure_io(c->first, c->second)) {
1932 			DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration failed\n", _name));
1933 			_in_configure_processors = false;
1934 			lr.release ();
1935 			lm->acquire ();
1936 			return -1;
1937 		}
1938 
1939 		processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1940 		processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1941 
1942 		boost::shared_ptr<IOProcessor> iop;
1943 		boost::shared_ptr<PluginInsert> pi;
1944 		if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
1945 			/* plugins connected via Split or Hide Match may have more channels.
1946 			 * route/scratch buffers are needed for all of them
1947 			 * The configuration may only be a subset (both input and output)
1948 			 */
1949 			processor_max_streams = ChanCount::max(processor_max_streams, pi->required_buffers());
1950 		}
1951 		else if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*p)) != 0) {
1952 			processor_max_streams = ChanCount::max(processor_max_streams, iop->natural_input_streams());
1953 			processor_max_streams = ChanCount::max(processor_max_streams, iop->natural_output_streams());
1954 		}
1955 		out = c->second;
1956 
1957 		if (boost::dynamic_pointer_cast<Delivery> (*p)
1958 				&& boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main) {
1959 			/* main delivery will increase port count to match input.
1960 			 * the Delivery::Main is usually the last processor - followed only by
1961 			 * 'MeterOutput'.
1962 			 */
1963 			seen_mains_out = true;
1964 		}
1965 		if (!seen_mains_out) {
1966 			processor_out_streams = out;
1967 		}
1968 	}
1969 
1970 	lr.release ();
1971 	lm->acquire ();
1972 
1973 
1974 	if (_meter) {
1975 		_meter->set_max_channels (processor_max_streams);
1976 	}
1977 
1978 	/* make sure we have sufficient scratch buffers to cope with the new processor
1979 	   configuration
1980 	*/
1981 	_session.ensure_buffers (n_process_buffers ());
1982 
1983 	DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration complete\n", _name));
1984 
1985 	_in_configure_processors = false;
1986 	return 0;
1987 }
1988 
1989 /** Set all visible processors to a given active state (except Fader, whose state is not changed)
1990  *  @param state New active state for those processors.
1991  */
1992 void
all_visible_processors_active(bool state)1993 Route::all_visible_processors_active (bool state)
1994 {
1995 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1996 
1997 	if (_processors.empty()) {
1998 		return;
1999 	}
2000 
2001 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2002 		if (!(*i)->display_to_user () || is_internal_processor (*i)) {
2003 			continue;
2004 		}
2005 #ifdef MIXBUS
2006 		boost::shared_ptr<PluginInsert> pi;
2007 		if (0 != (pi = boost::dynamic_pointer_cast<PluginInsert>(*i))) {
2008 			if (pi->is_channelstrip ()) {
2009 				continue;
2010 			}
2011 		}
2012 #endif
2013 		(*i)->enable (state);
2014 	}
2015 
2016 	_session.set_dirty ();
2017 }
2018 
2019 bool
processors_reorder_needs_configure(const ProcessorList & new_order)2020 Route::processors_reorder_needs_configure (const ProcessorList& new_order)
2021 {
2022 	/* check if re-order requires re-configuration of any processors
2023 	 * -> compare channel configuration for all processors
2024 	 */
2025 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2026 	ChanCount c = input_streams ();
2027 
2028 	for (ProcessorList::const_iterator j = new_order.begin(); j != new_order.end(); ++j) {
2029 		bool found = false;
2030 		if (c != (*j)->input_streams()) {
2031 			return true;
2032 		}
2033 		for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2034 			if (*i == *j) {
2035 				found = true;
2036 				if ((*i)->input_streams() != c) {
2037 					return true;
2038 				}
2039 				c = (*i)->output_streams();
2040 				break;
2041 			}
2042 		}
2043 		if (!found) {
2044 			return true;
2045 		}
2046 	}
2047 	return false;
2048 }
2049 
2050 #ifdef __clang__
2051 __attribute__((annotate("realtime")))
2052 #endif
2053 void
apply_processor_order(const ProcessorList & new_order)2054 Route::apply_processor_order (const ProcessorList& new_order)
2055 {
2056 	/* need to hold processor_lock; either read or write lock
2057 	 * and the engine process_lock.
2058 	 * Due to r/w lock ambiguity we can only assert the latter
2059 	 */
2060 	assert (!AudioEngine::instance()->process_lock().trylock());
2061 
2062 
2063 	/* "new_order" is an ordered list of processors to be positioned according to "placement".
2064 	 * NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
2065 	 * processors in the current actual processor list that are hidden. Any visible processors
2066 	 * in the current list but not in "new_order" will be assumed to be deleted.
2067 	 */
2068 
2069 	/* "as_it_will_be" and "_processors" are lists of shared pointers.
2070 	 * actual memory usage is small, but insert/erase is not actually rt-safe :(
2071 	 * (note though that  ::processors_reorder_needs_configure() ensured that
2072 	 * this function will only ever be called from the rt-thread if no processor were removed)
2073 	 *
2074 	 * either way, I can't proove it, but an xrun due to re-order here is less likley
2075 	 * than an xrun-less 'ardour-silent cycle' both of which effectively "click".
2076 	 */
2077 
2078 	ProcessorList as_it_will_be;
2079 	ProcessorList::iterator oiter;
2080 	ProcessorList::const_iterator niter;
2081 
2082 	oiter = _processors.begin();
2083 	niter = new_order.begin();
2084 
2085 	while (niter != new_order.end ()) {
2086 
2087 		/* if the next processor in the old list is invisible (i.e. should not be in the new order)
2088 		 * then append it to the temp list.
2089 		 *
2090 		 * Otherwise, see if the next processor in the old list is in the new list. if not,
2091 		 * its been deleted. If its there, append it to the temp list.
2092 		 */
2093 
2094 		if (oiter == _processors.end()) {
2095 
2096 			/* no more elements in the old list, so just stick the rest of
2097 			 * the new order onto the temp list.
2098 			 */
2099 
2100 			as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
2101 			while (niter != new_order.end()) {
2102 				++niter;
2103 			}
2104 			break;
2105 
2106 		} else {
2107 
2108 			if (!(*oiter)->display_to_user()) {
2109 
2110 				as_it_will_be.push_back (*oiter);
2111 
2112 			} else {
2113 
2114 				/* visible processor: check that its in the new order */
2115 
2116 				if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
2117 					/* deleted: do nothing, shared_ptr<> will clean up */
2118 				} else {
2119 					/* ignore this one, and add the next item from the new order instead */
2120 					as_it_will_be.push_back (*niter);
2121 					++niter;
2122 				}
2123 			}
2124 
2125 			/* now remove from old order - its taken care of no matter what */
2126 			oiter = _processors.erase (oiter);
2127 		}
2128 
2129 	}
2130 	_processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
2131 
2132 	/* If the meter is in a custom position, find it and make a rough note of its position */
2133 	maybe_note_meter_position ();
2134 
2135 	/* if any latent plugins were re-ordered and sends or side-chains are present
2136 	 * in the signal-flow, a full latency-recompute is needed.
2137 	 *
2138 	 * The Session will be informed about the new order via
2139 	 *  processors_changed()
2140 	 * and test if a full latency-recompute is required by comparing
2141 	 * _signal_latency != ::update_signal_latency();
2142 	 *
2143 	 * Since the route's latency itself does not initially change by
2144 	 * re-ordering, we need to force this:
2145 	 */
2146 	bool need_latency_recompute = false;
2147 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2148 		if (boost::dynamic_pointer_cast<PortInsert> (*i)) {
2149 			need_latency_recompute = true;
2150 			break;
2151 		} else if (boost::dynamic_pointer_cast<LatentSend> (*i)) {
2152 			need_latency_recompute = true;
2153 			break;
2154 		} else if (boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) {
2155 			if (pi->sidechain_input ()) {
2156 				need_latency_recompute = true;
2157 				break;
2158 			}
2159 		}
2160 	}
2161 	if (need_latency_recompute) {
2162 		/* force a change, the correct value will be set
2163 		 * ::update_signal_latency() will be called via
2164 		 *
2165 		 * SIGNAL processors_changed () ->
2166 		 * -> Session::route_processors_changed ()
2167 		 * -> Session::update_latency_compensation ()
2168 		 * -> Route::::update_signal_latency ()
2169 		 */
2170 	_signal_latency = 0;
2171 	}
2172 }
2173 
2174 void
move_instrument_down(bool postfader)2175 Route::move_instrument_down (bool postfader)
2176 {
2177 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2178 	ProcessorList new_order;
2179 	boost::shared_ptr<Processor> instrument;
2180 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2181 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
2182 		if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
2183 			instrument = *i;
2184 		} else if (instrument && *i == _amp) {
2185 			if (postfader) {
2186 				new_order.push_back (*i);
2187 				new_order.push_back (instrument);
2188 			} else {
2189 				new_order.push_back (instrument);
2190 				new_order.push_back (*i);
2191 			}
2192 		} else {
2193 			new_order.push_back (*i);
2194 		}
2195 	}
2196 	if (!instrument) {
2197 		return;
2198 	}
2199 	lm.release ();
2200 	reorder_processors (new_order, 0);
2201 }
2202 
2203 int
reorder_processors(const ProcessorList & new_order,ProcessorStreams * err)2204 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
2205 {
2206 	/* If a change is already queued, wait for it
2207 	 * (unless engine is stopped. apply immediately and proceed
2208 	 */
2209 	while (g_atomic_int_get (&_pending_process_reorder)) {
2210 		if (!AudioEngine::instance()->running()) {
2211 			DEBUG_TRACE (DEBUG::Processors, "offline apply queued processor re-order.\n");
2212 			Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2213 
2214 			g_atomic_int_set (&_pending_process_reorder, 0);
2215 			g_atomic_int_set (&_pending_listen_change, 0);
2216 
2217 			apply_processor_order(_pending_processor_order);
2218 			_pending_processor_order.clear ();
2219 			setup_invisible_processors ();
2220 
2221 			update_signal_latency (true);
2222 
2223 			processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2224 			set_processor_positions ();
2225 		} else {
2226 			// TODO rather use a semaphore or something.
2227 			// but since ::reorder_processors() is called
2228 			// from the GUI thread, this is fine..
2229 			Glib::usleep(500);
2230 		}
2231 	}
2232 
2233 	if (processors_reorder_needs_configure (new_order) || !AudioEngine::instance()->running()) {
2234 
2235 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2236 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2237 		ProcessorState pstate (this);
2238 
2239 		apply_processor_order (new_order);
2240 
2241 		if (configure_processors_unlocked (err, &lm)) {
2242 			pstate.restore ();
2243 			return -1;
2244 		}
2245 
2246 		lm.release();
2247 
2248 		/* update processor input/output latency (total signal_latency does not change).
2249 		 * delaylines may changes, so the Engine Lock is required.
2250 		 */
2251 		update_signal_latency (true);
2252 
2253 		lx.release();
2254 
2255 		processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2256 		set_processor_positions ();
2257 
2258 	} else {
2259 		DEBUG_TRACE (DEBUG::Processors, "Queue clickless processor re-order.\n");
2260 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2261 
2262 		// _pending_processor_order is protected by _processor_lock
2263 		_pending_processor_order = new_order;
2264 		g_atomic_int_set (&_pending_process_reorder, 1);
2265 	}
2266 
2267 	return 0;
2268 }
2269 
2270 bool
add_remove_sidechain(boost::shared_ptr<Processor> proc,bool add)2271 Route::add_remove_sidechain (boost::shared_ptr<Processor> proc, bool add)
2272 {
2273 	if (_session.actively_recording () || _in_sidechain_setup) {
2274 		return false;
2275 	}
2276 
2277 	boost::shared_ptr<PluginInsert> pi;
2278 	if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2279 		return false;
2280 	}
2281 
2282 	if (pi->has_sidechain () == add) {
2283 		return true; // ?? call failed, but result is as expected.
2284 	}
2285 
2286 	{
2287 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2288 		ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2289 		if (i == _processors.end ()) {
2290 			return false;
2291 		}
2292 	}
2293 
2294 	{
2295 		PBD::Unwinder<bool> uw (_in_sidechain_setup, true);
2296 
2297 		if (add) {
2298 			if (!pi->add_sidechain ()) {
2299 				return false;
2300 			}
2301 		} else {
2302 			if (!pi->del_sidechain ()) {
2303 				return false;
2304 			}
2305 		}
2306 
2307 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ()); // take before Writerlock to avoid deadlock
2308 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2309 
2310 		list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2311 
2312 		if (c.empty()) {
2313 			lm.release ();
2314 			lx.release ();
2315 
2316 			if (add) {
2317 				pi->del_sidechain ();
2318 			} else {
2319 				pi->add_sidechain ();
2320 				// TODO restore side-chain's state.
2321 			}
2322 			return false;
2323 		}
2324 
2325 		configure_processors_unlocked (0, &lm);
2326 	}
2327 
2328 	if (pi->has_sidechain ()) {
2329 		pi->sidechain_input ()->changed.connect_same_thread (*pi, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
2330 	}
2331 
2332 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2333 	_session.set_dirty ();
2334 	return true;
2335 }
2336 
2337 bool
plugin_preset_output(boost::shared_ptr<Processor> proc,ChanCount outs)2338 Route::plugin_preset_output (boost::shared_ptr<Processor> proc, ChanCount outs)
2339 {
2340 	if (_session.actively_recording ()) {
2341 		return false;
2342 	}
2343 
2344 	boost::shared_ptr<PluginInsert> pi;
2345 	if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2346 		return false;
2347 	}
2348 
2349 	{
2350 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2351 		ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2352 		if (i == _processors.end ()) {
2353 			return false;
2354 		}
2355 	}
2356 
2357 	{
2358 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2359 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2360 
2361 		const ChanCount& old (pi->preset_out ());
2362 		if (!pi->set_preset_out (outs)) {
2363 			return true; // no change, OK
2364 		}
2365 
2366 		list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2367 		if (c.empty()) {
2368 			/* not possible */
2369 			pi->set_preset_out (old);
2370 			return false;
2371 		}
2372 		configure_processors_unlocked (0, &lm);
2373 	}
2374 
2375 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2376 	_session.set_dirty ();
2377 	return true;
2378 }
2379 
2380 bool
reset_plugin_insert(boost::shared_ptr<Processor> proc)2381 Route::reset_plugin_insert (boost::shared_ptr<Processor> proc)
2382 {
2383 	ChanCount unused;
2384 	return customize_plugin_insert (proc, 0, unused, unused);
2385 }
2386 
2387 bool
customize_plugin_insert(boost::shared_ptr<Processor> proc,uint32_t count,ChanCount outs,ChanCount sinks)2388 Route::customize_plugin_insert (boost::shared_ptr<Processor> proc, uint32_t count, ChanCount outs, ChanCount sinks)
2389 {
2390 	if (_session.actively_recording ()) {
2391 		return false;
2392 	}
2393 	boost::shared_ptr<PluginInsert> pi;
2394 	if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2395 		return false;
2396 	}
2397 
2398 	{
2399 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2400 		ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2401 		if (i == _processors.end ()) {
2402 			return false;
2403 		}
2404 	}
2405 
2406 	{
2407 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2408 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2409 
2410 		bool      old_cust  = pi->custom_cfg ();
2411 		uint32_t  old_cnt   = pi->get_count ();
2412 		ChanCount old_chan  = pi->output_streams ();
2413 		ChanCount old_sinks = pi->natural_input_streams ();
2414 
2415 		if (count == 0) {
2416 			pi->set_custom_cfg (false);
2417 		} else {
2418 			pi->set_custom_cfg (true);
2419 			pi->set_count (count);
2420 			pi->set_outputs (outs);
2421 			pi->set_sinks (sinks);
2422 		}
2423 
2424 		list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2425 		if (c.empty()) {
2426 			/* not possible */
2427 
2428 			pi->set_count (old_cnt);
2429 			pi->set_sinks (old_sinks);
2430 			pi->set_outputs (old_chan);
2431 			pi->set_custom_cfg (old_cust);
2432 
2433 			return false;
2434 		}
2435 		configure_processors_unlocked (0, &lm);
2436 	}
2437 
2438 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2439 	_session.set_dirty ();
2440 	return true;
2441 }
2442 
2443 bool
set_strict_io(const bool enable)2444 Route::set_strict_io (const bool enable)
2445 {
2446 	Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2447 
2448 	if (_strict_io != enable) {
2449 		_strict_io = enable;
2450 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2451 		for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2452 			boost::shared_ptr<PluginInsert> pi;
2453 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2454 				pi->set_strict_io (_strict_io);
2455 			}
2456 		}
2457 
2458 		list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2459 
2460 		if (c.empty()) {
2461 			// not possible
2462 			_strict_io = !enable; // restore old value
2463 			for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2464 				boost::shared_ptr<PluginInsert> pi;
2465 				if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2466 					pi->set_strict_io (_strict_io);
2467 				}
2468 			}
2469 			return false;
2470 		}
2471 		lm.release ();
2472 
2473 		configure_processors (0);
2474 		lx.release ();
2475 
2476 		processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2477 		_session.set_dirty ();
2478 	}
2479 	return true;
2480 }
2481 
2482 XMLNode&
get_state()2483 Route::get_state()
2484 {
2485 	return state (false);
2486 }
2487 
2488 XMLNode&
get_template()2489 Route::get_template()
2490 {
2491 	return state (true);
2492 }
2493 
2494 XMLNode&
state(bool save_template)2495 Route::state (bool save_template)
2496 {
2497 	if (!_session._template_state_dir.empty()) {
2498 		foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), _session._template_state_dir));
2499 	}
2500 
2501 	XMLNode *node = new XMLNode("Route");
2502 	ProcessorList::iterator i;
2503 
2504 	if(save_template) {
2505 		XMLNode* child = node->add_child("ProgramVersion");
2506 		child->set_property("created-with", _session.created_with);
2507 
2508 		std::string modified_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
2509 		child->set_property("modified-with", modified_with);
2510 	}
2511 
2512 	/* This is needed for templates and when duplicating routes, in which case
2513 	 * the route-state is directly passed to new_route_from_template().
2514 	 */
2515 	node->set_property("version", CURRENT_SESSION_FILE_VERSION);
2516 
2517 	node->set_property (X_("id"), id ());
2518 	node->set_property (X_("name"), name());
2519 	node->set_property (X_("default-type"), _default_type);
2520 	node->set_property (X_("strict-io"), _strict_io);
2521 
2522 	if (is_master ()) {
2523 		node->set_property (X_("volume-applies-to-output"), _volume_applies_to_output);
2524 	}
2525 
2526 	node->add_child_nocopy (_presentation_info.get_state());
2527 
2528 	node->set_property (X_("active"), _active);
2529 	node->set_property (X_("denormal-protection"), _denormal_protection);
2530 	node->set_property (X_("meter-point"), _meter_point);
2531 	node->set_property (X_("disk-io-point"), _disk_io_point);
2532 
2533 	node->set_property (X_("meter-type"), _meter->meter_type ());
2534 
2535 	if (_route_group) {
2536 		node->set_property (X_("route-group"), _route_group->name());
2537 	}
2538 
2539 	node->add_child_nocopy (_solo_control->get_state ());
2540 	node->add_child_nocopy (_solo_isolate_control->get_state ());
2541 	node->add_child_nocopy (_solo_safe_control->get_state ());
2542 
2543 	node->add_child_nocopy (_input->get_state ());
2544 	node->add_child_nocopy (_output->get_state ());
2545 	node->add_child_nocopy (_mute_master->get_state ());
2546 
2547 	node->add_child_nocopy (_mute_control->get_state ());
2548 	node->add_child_nocopy (_phase_control->get_state ());
2549 
2550 	if (_volume_control) {
2551 		node->add_child_nocopy (_volume_control->get_state ());
2552 	}
2553 
2554 	if (!skip_saving_automation) {
2555 		node->add_child_nocopy (Automatable::get_automation_xml_state ());
2556 	}
2557 
2558 	if (_comment.length()) {
2559 		XMLNode *cmt = node->add_child ("Comment");
2560 		cmt->add_content (_comment);
2561 	}
2562 
2563 	if (_pannable) {
2564 		node->add_child_nocopy (_pannable->get_state ());
2565 	}
2566 
2567 	{
2568 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2569 		for (i = _processors.begin(); i != _processors.end(); ++i) {
2570 			if (*i == _delayline) {
2571 				continue;
2572 			}
2573 			if (save_template) {
2574 				/* template save: do not include internal sends functioning as
2575 					 aux sends because the chance of the target ID
2576 					 in the session where this template is used
2577 					 is not very likely.
2578 
2579 					 similarly, do not save listen sends which connect to
2580 					 the monitor section, because these will always be
2581 					 added if necessary.
2582 					 */
2583 				boost::shared_ptr<InternalSend> is;
2584 
2585 				if ((is = boost::dynamic_pointer_cast<InternalSend> (*i)) != 0) {
2586 					if (is->role() == Delivery::Listen) {
2587 						continue;
2588 					}
2589 				}
2590 			}
2591 			node->add_child_nocopy((*i)->get_state ());
2592 		}
2593 	}
2594 
2595 	if (_extra_xml) {
2596 		node->add_child_copy (*_extra_xml);
2597 	}
2598 
2599 	if (_custom_meter_position_noted) {
2600 		boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
2601 		if (after) {
2602 			node->set_property (X_("processor-after-last-custom-meter"), after->id());
2603 		}
2604 	}
2605 
2606 	if (!_session._template_state_dir.empty()) {
2607 		foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), ""));
2608 	}
2609 
2610 	node->add_child_copy (Slavable::get_state());
2611 
2612 	return *node;
2613 }
2614 
2615 int
set_state(const XMLNode & node,int version)2616 Route::set_state (const XMLNode& node, int version)
2617 {
2618 	if (version < 3000) {
2619 		return set_state_2X (node, version);
2620 	}
2621 
2622 	XMLNodeList nlist;
2623 	XMLNodeConstIterator niter;
2624 	XMLNode *child;
2625 
2626 	if (node.name() != "Route"){
2627 		error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2628 		return -1;
2629 	}
2630 
2631 	std::string route_name;
2632 	if (node.get_property (X_("name"), route_name)) {
2633 		set_name (route_name);
2634 	}
2635 
2636 	set_id (node);
2637 	_initial_io_setup = true;
2638 
2639 	Stripable::set_state (node, version);
2640 
2641 	/*  "This should never happen"
2642 	Stripable's job is to save/recall the PresentationInfo flags for bus/track audio/midi VCA etc.
2643 	But I found a case where no "type" flag is set, so the strip never shows up on any UI.
2644 	Since I don't know the source of the error, I have to assume that it could happen again.
2645 	So: if a stripable doesn't have any flags set, populate them from our audio/midi track/bus identity.
2646 	*/
2647 	PresentationInfo::Flag file_flags = _presentation_info.flags();
2648 	if ( !(file_flags & PresentationInfo::TypeMask) ) {
2649 		if (dynamic_cast<AudioTrack*>(this)) {
2650 			_presentation_info.set_flags ( PresentationInfo::Flag (file_flags | PresentationInfo::AudioTrack) );
2651 		} else if (dynamic_cast<MidiTrack*>(this)) {
2652 			_presentation_info.set_flags ( PresentationInfo::Flag (file_flags | PresentationInfo::MidiTrack) );
2653 		} else {
2654 			//no idea what this is, so let's call it an audio bus
2655 			_presentation_info.set_flags ( PresentationInfo::Flag (file_flags | PresentationInfo::AudioBus) );
2656 		}
2657 	}
2658 
2659 	node.get_property (X_("strict-io"), _strict_io);
2660 
2661 	if (is_monitor()) {
2662 		/* monitor bus does not get a panner, but if (re)created
2663 		   via XML, it will already have one by the time we
2664 		   call ::set_state(). so ... remove it.
2665 		*/
2666 		unpan ();
2667 	}
2668 
2669 	/* add all processors (except amp, which is always present) */
2670 
2671 	nlist = node.children();
2672 	XMLNode processor_state (X_("processor_state"));
2673 
2674 	Stateful::save_extra_xml (node);
2675 
2676 	for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2677 
2678 		child = *niter;
2679 
2680 		if (child->name() == IO::state_node_name) {
2681 			std::string direction;
2682 			if (!child->get_property (X_("direction"), direction)) {
2683 				continue;
2684 			}
2685 
2686 			if (direction == "Input") {
2687 				_input->set_state (*child, version);
2688 			} else if (direction == "Output") {
2689 				_output->set_state (*child, version);
2690 			}
2691 
2692 		} else if (child->name() == X_("Processor")) {
2693 			processor_state.add_child_copy (*child);
2694 		} else if (child->name() == X_("Pannable")) {
2695 			if (_pannable) {
2696 				_pannable->set_state (*child, version);
2697 			} else {
2698 				warning << string_compose (_("Panner state mismatches for track/bus (%1)."), name()) << endmsg;
2699 			}
2700 		} else if (child->name() == Slavable::xml_node_name) {
2701 			Slavable::set_state (*child, version);
2702 		}
2703 	}
2704 
2705 	DiskIOPoint diop;
2706 	if (node.get_property (X_("disk-io-point"), diop)) {
2707 		if (_disk_writer) {
2708 			_disk_writer->set_display_to_user (diop == DiskIOCustom);
2709 		}
2710 		if (_disk_reader) {
2711 			_disk_reader->set_display_to_user (diop == DiskIOCustom);
2712 		}
2713 		set_disk_io_point (diop);
2714 	}
2715 
2716 	MeterType meter_type;
2717 	if (node.get_property (X_("meter-type"), meter_type)) {
2718 		set_meter_type (meter_type);
2719 	}
2720 
2721 	_initial_io_setup = false;
2722 
2723 	if (is_master ()) {
2724 		node.get_property (X_("volume-applies-to-output"), _volume_applies_to_output);
2725 		if (_volume_applies_to_output) {
2726 			_volume->deactivate ();
2727 			_volume->set_display_to_user (false);
2728 			main_outs()->add_gain (_volume_control);
2729 		} else {
2730 			_volume->set_display_to_user (true);
2731 			_volume->activate ();
2732 			main_outs()->add_gain (boost::shared_ptr<GainControl> ());
2733 		}
2734 	}
2735 
2736 	set_processor_state (processor_state, version);
2737 
2738 	// this looks up the internal instrument in processors
2739 	reset_instrument_info();
2740 
2741 	MeterPoint mp;
2742 	if (node.get_property (X_("meter-point"), mp)) {
2743 		set_meter_point (mp);
2744 		if (_meter) {
2745 			_meter->set_display_to_user (_meter_point == MeterCustom);
2746 		}
2747 	}
2748 
2749 	bool denormal_protection;
2750 	if (node.get_property (X_("denormal-protection"), denormal_protection)) {
2751 		set_denormal_protection (denormal_protection);
2752 	}
2753 
2754 	/* convert old 3001 state */
2755 	std::string phase_invert_str;
2756 	if (node.get_property (X_("phase-invert"), phase_invert_str)) {
2757 		_phase_control->set_phase_invert (boost::dynamic_bitset<> (phase_invert_str));
2758 	}
2759 
2760 	bool is_active;
2761 	if (node.get_property (X_("active"), is_active)) {
2762 		set_active (is_active, this);
2763 	}
2764 
2765 	std::string id_string;
2766 	if (node.get_property (X_("processor-after-last-custom-meter"), id_string)) {
2767 		PBD::ID id (id_string);
2768 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2769 		ProcessorList::const_iterator i = _processors.begin ();
2770 		while (i != _processors.end() && (*i)->id() != id) {
2771 			++i;
2772 		}
2773 
2774 		if (i != _processors.end ()) {
2775 			_processor_after_last_custom_meter = *i;
2776 			_custom_meter_position_noted = true;
2777 		}
2778 	}
2779 
2780 	for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2781 		child = *niter;
2782 
2783 		if (child->name() == X_("Comment")) {
2784 
2785 			/* XXX this is a terrible API design in libxml++ */
2786 
2787 			XMLNode *cmt = *(child->children().begin());
2788 			_comment = cmt->content();
2789 
2790 		}  else if (child->name() == Controllable::xml_node_name) {
2791 			std::string control_name;
2792 			if (!child->get_property (X_("name"), control_name)) {
2793 				continue;
2794 			}
2795 
2796 			if (control_name == _solo_control->name()) {
2797 				_solo_control->set_state (*child, version);
2798 			} else if (control_name == _solo_safe_control->name()) {
2799 				_solo_safe_control->set_state (*child, version);
2800 			} else if (control_name == _solo_isolate_control->name()) {
2801 				_solo_isolate_control->set_state (*child, version);
2802 			} else if (control_name == _mute_control->name()) {
2803 				_mute_control->set_state (*child, version);
2804 			} else if (_volume_control && control_name == _volume_control->name()) {
2805 				_volume_control->set_state (*child, version);
2806 			} else if (control_name == _phase_control->name()) {
2807 				_phase_control->set_state (*child, version);
2808 			} else {
2809 				Evoral::Parameter p = EventTypeMap::instance().from_symbol (control_name);
2810 				if (p.type () >= MidiCCAutomation && p.type () < MidiSystemExclusiveAutomation) {
2811 					boost::shared_ptr<AutomationControl> ac = automation_control (p, true);
2812 					if (ac) {
2813 						ac->set_state (*child, version);
2814 					}
2815 				}
2816 			}
2817 		} else if (child->name() == MuteMaster::xml_node_name) {
2818 			_mute_master->set_state (*child, version);
2819 
2820 		} else if (child->name() == Automatable::xml_node_name) {
2821 			set_automation_xml_state (*child, Evoral::Parameter(NullAutomation));
2822 		}
2823 	}
2824 
2825 	if (_delayline) {
2826 		_delayline->set_name (name ());
2827 	}
2828 
2829 	return 0;
2830 }
2831 
2832 int
set_state_2X(const XMLNode & node,int version)2833 Route::set_state_2X (const XMLNode& node, int version)
2834 {
2835 	LocaleGuard lg;
2836 	XMLNodeList nlist;
2837 	XMLNodeConstIterator niter;
2838 	XMLNode *child;
2839 	XMLProperty const * prop;
2840 
2841 	/* 2X things which still remain to be handled:
2842 	 * default-type
2843 	 * automation
2844 	 * controlouts
2845 	 */
2846 
2847 	if (node.name() != "Route") {
2848 		error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2849 		return -1;
2850 	}
2851 
2852 	Stripable::set_state (node, version);
2853 
2854 	if ((prop = node.property (X_("denormal-protection"))) != 0) {
2855 		set_denormal_protection (string_to<bool> (prop->value()));
2856 	}
2857 
2858 	if ((prop = node.property (X_("muted"))) != 0) {
2859 
2860 		bool first = true;
2861 		bool muted = string_to<bool> (prop->value());
2862 
2863 		if (muted) {
2864 
2865 			string mute_point;
2866 
2867 			if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2868 
2869 				if (string_to<bool> (prop->value())){
2870 					mute_point = mute_point + "PreFader";
2871 					first = false;
2872 				}
2873 			}
2874 
2875 			if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2876 
2877 				if (string_to<bool> (prop->value())){
2878 
2879 					if (!first) {
2880 						mute_point = mute_point + ",";
2881 					}
2882 
2883 					mute_point = mute_point + "PostFader";
2884 					first = false;
2885 				}
2886 			}
2887 
2888 			if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2889 
2890 				if (string_to<bool> (prop->value())){
2891 
2892 					if (!first) {
2893 						mute_point = mute_point + ",";
2894 					}
2895 
2896 					mute_point = mute_point + "Listen";
2897 					first = false;
2898 				}
2899 			}
2900 
2901 			if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2902 
2903 				if (string_to<bool> (prop->value())){
2904 
2905 					if (!first) {
2906 						mute_point = mute_point + ",";
2907 					}
2908 
2909 					mute_point = mute_point + "Main";
2910 				}
2911 			}
2912 
2913 			_mute_master->set_mute_points (mute_point);
2914 			_mute_master->set_muted_by_self (true);
2915 		}
2916 	}
2917 
2918 	if ((prop = node.property (X_("meter-point"))) != 0) {
2919 		_meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2920 	}
2921 
2922 	/* IOs */
2923 
2924 	nlist = node.children ();
2925 	for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2926 
2927 		child = *niter;
2928 
2929 		if (child->name() == IO::state_node_name) {
2930 
2931 			/* there is a note in IO::set_state_2X() about why we have to call
2932 			   this directly.
2933 			   */
2934 
2935 			_input->set_state_2X (*child, version, true);
2936 			_output->set_state_2X (*child, version, false);
2937 
2938 			if ((prop = child->property (X_("name"))) != 0) {
2939 				Route::set_name (prop->value ());
2940 			}
2941 
2942 			set_id (*child);
2943 
2944 			if ((prop = child->property (X_("active"))) != 0) {
2945 				bool yn = string_to<bool> (prop->value());
2946 				_active = !yn; // force switch
2947 				set_active (yn, this);
2948 			}
2949 
2950 			if ((prop = child->property (X_("gain"))) != 0) {
2951 				gain_t val;
2952 
2953 				if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2954 					_amp->gain_control()->set_value (val, Controllable::NoGroup);
2955 				}
2956 			}
2957 
2958 			/* Set up Panners in the IO */
2959 			XMLNodeList io_nlist = child->children ();
2960 
2961 			XMLNodeConstIterator io_niter;
2962 			XMLNode *io_child;
2963 
2964 			for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2965 
2966 				io_child = *io_niter;
2967 
2968 				if (io_child->name() == X_("Panner")) {
2969 					_main_outs->panner_shell()->set_state(*io_child, version);
2970 				} else if (io_child->name() == X_("Automation")) {
2971 					/* IO's automation is for the fader */
2972 					_amp->set_automation_xml_state (*io_child, Evoral::Parameter (GainAutomation));
2973 				}
2974 			}
2975 		}
2976 	}
2977 
2978 	XMLNodeList redirect_nodes;
2979 
2980 	for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2981 
2982 		child = *niter;
2983 
2984 		if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2985 			redirect_nodes.push_back(child);
2986 		}
2987 
2988 	}
2989 
2990 	set_processor_state_2X (redirect_nodes, version);
2991 
2992 	Stateful::save_extra_xml (node);
2993 
2994 	for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2995 		child = *niter;
2996 
2997 		if (child->name() == X_("Comment")) {
2998 
2999 			/* XXX this is a terrible API design in libxml++ */
3000 
3001 			XMLNode *cmt = *(child->children().begin());
3002 			_comment = cmt->content();
3003 
3004 		} else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
3005 			if (prop->value() == X_("solo")) {
3006 				_solo_control->set_state (*child, version);
3007 			} else if (prop->value() == X_("mute")) {
3008 				_mute_control->set_state (*child, version);
3009 			}
3010 
3011 		}
3012 	}
3013 
3014 	bool phase_invert; /* yes / no - apply to all channels */
3015 	if (node.get_property (X_("phase-invert"), phase_invert)) {
3016 		/* phase_control is not usually configured at this point in time
3017 		 * _phase_control->count() == 0. However in v2, polarity invert
3018 		 * is directly after the input, so the input channel count can be used.
3019 		 * NB. v2 busses: polarity invert was only applied to inputs. Aux-return
3020 		 * was not affected. This is no longer the case (and may break sessions).
3021 		 */
3022 		uint64_t pol_cnt = std::max ((uint64_t)_input->n_ports().n_audio (), _phase_control->count ());
3023 		for (uint64_t c = 0; c < pol_cnt; ++c) {
3024 			_phase_control->set_phase_invert (c, phase_invert);
3025 		}
3026 	}
3027 
3028 	return 0;
3029 }
3030 
3031 XMLNode&
get_processor_state()3032 Route::get_processor_state ()
3033 {
3034 	XMLNode* root = new XMLNode (X_("redirects"));
3035 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3036 		root->add_child_nocopy ((*i)->get_state ());
3037 	}
3038 
3039 	return *root;
3040 }
3041 
3042 void
set_processor_state_2X(XMLNodeList const & nList,int version)3043 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
3044 {
3045 	/* We don't bother removing existing processors not in nList, as this
3046 	   method will only be called when creating a Route from scratch, not
3047 	   for undo purposes.  Just put processors in at the appropriate place
3048 	   in the list.
3049 	*/
3050 
3051 	for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
3052 		add_processor_from_xml_2X (**i, version);
3053 	}
3054 }
3055 
3056 void
set_processor_state(const XMLNode & node,int version)3057 Route::set_processor_state (const XMLNode& node, int version)
3058 {
3059 	const XMLNodeList &nlist = node.children();
3060 	XMLNodeConstIterator niter;
3061 	ProcessorList new_order;
3062 	bool must_configure = false;
3063 
3064 	for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3065 
3066 		XMLProperty* prop = (*niter)->property ("type");
3067 
3068 		if (prop->value() == "amp") {
3069 			_amp->set_state (**niter, version);
3070 			new_order.push_back (_amp);
3071 		} else if (prop->value() == "trim") {
3072 			_trim->set_state (**niter, version);
3073 			new_order.push_back (_trim);
3074 		} else if (prop->value() == "main-volume") {
3075 			assert (is_master ());
3076 			_volume->set_state (**niter, version);
3077 			new_order.push_back (_volume);
3078 		} else if (prop->value() == "meter") {
3079 			_meter->set_state (**niter, version);
3080 			new_order.push_back (_meter);
3081 		} else if (prop->value() == "polarity") {
3082 			_polarity->set_state (**niter, version);
3083 			new_order.push_back (_polarity);
3084 		} else if (prop->value() == "delay") {
3085 			// skip -- internal
3086 		} else if (prop->value() == "main-outs") {
3087 			_main_outs->set_state (**niter, version);
3088 		} else if (prop->value() == "monreturn") {
3089 			if (!_intreturn) {
3090 				_intreturn.reset (new MonitorReturn (_session));
3091 				must_configure = true;
3092 			}
3093 			_intreturn->set_state (**niter, version);
3094 		} else if (prop->value() == "intreturn") {
3095 			if (!_intreturn) {
3096 				if (is_monitor ()) {
3097 					_intreturn.reset (new MonitorReturn (_session));
3098 				} else {
3099 					_intreturn.reset (new InternalReturn (_session));
3100 				}
3101 				must_configure = true;
3102 			}
3103 			_intreturn->set_state (**niter, version);
3104 		} else if (is_monitor() && prop->value() == "monitor") {
3105 			if (!_monitor_control) {
3106 				_monitor_control.reset (new MonitorProcessor (_session));
3107 				must_configure = true;
3108 			}
3109 			_monitor_control->set_state (**niter, version);
3110 		} else if (prop->value() == "capture") {
3111 			/* CapturingProcessor should never be restored, it's always
3112 			   added explicitly when needed */
3113 		} else if (prop->value() == "diskreader" && _disk_reader) {
3114 			_disk_reader->set_state (**niter, version);
3115 			new_order.push_back (_disk_reader);
3116 		} else if (prop->value() == "diskwriter" && _disk_writer) {
3117 			_disk_writer->set_state (**niter, version);
3118 			new_order.push_back (_disk_writer);
3119 		} else {
3120 			set_processor_state (**niter, version, prop, new_order, must_configure);
3121 		}
3122 	}
3123 
3124 	ProcessorList old_list = _processors; // keep a copy
3125 	{
3126 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
3127 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3128 		/* re-assign _processors w/o process-lock.
3129 		 * if there's an IO-processor present in _processors but
3130 		 * not in new_order, it will be deleted and ~IO takes
3131 		 * a process lock.
3132 		 */
3133 		_processors = new_order;
3134 
3135 		/* When a required/existing internal processor is not in the list, it needs to
3136 		 * be added via configure_processors() -> setup_invisible_processors()
3137 		 */
3138 		if (_monitor_control) {
3139 			must_configure |= find (_processors.begin(), _processors.end(), _monitor_control) == _processors.end ();
3140 		}
3141 		if (_main_outs) {
3142 			must_configure |= find (_processors.begin(), _processors.end(), _main_outs) == _processors.end ();
3143 		}
3144 		if (_delayline) {
3145 			must_configure |= find (_processors.begin(), _processors.end(), _delayline) == _processors.end ();
3146 		}
3147 		if (_intreturn) {
3148 			must_configure |= find (_processors.begin(), _processors.end(), _intreturn) == _processors.end ();
3149 		}
3150 
3151 		if (must_configure && !_session.loading()) {
3152 			configure_processors_unlocked (0, &lm);
3153 		}
3154 
3155 		for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3156 
3157 			(*i)->set_owner (this);
3158 			(*i)->ActiveChanged.connect_same_thread (**i, boost::bind (&Session::queue_latency_recompute, &_session));
3159 
3160 			boost::shared_ptr<PluginInsert> pi;
3161 
3162 			if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
3163 				if (pi->has_no_inputs ()) {
3164 					_have_internal_generator = true;
3165 					break;
3166 				}
3167 			}
3168 		}
3169 	}
3170 	/* drop references w/o process-lock (I/O procs may re-take it in ~IO() */
3171 	old_list.clear ();
3172 
3173 	reset_instrument_info ();
3174 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3175 	set_processor_positions ();
3176 }
3177 
3178 bool
set_processor_state(XMLNode const & node,int version,XMLProperty const * prop,ProcessorList & new_order,bool & must_configure)3179 Route::set_processor_state (XMLNode const& node, int version, XMLProperty const* prop, ProcessorList& new_order, bool& must_configure)
3180 {
3181 	ProcessorList::iterator o;
3182 
3183 	for (o = _processors.begin(); o != _processors.end(); ++o) {
3184 		XMLProperty const * id_prop = node.property(X_("id"));
3185 		if (id_prop && (*o)->id() == id_prop->value()) {
3186 			(*o)->set_state (node, version);
3187 			new_order.push_back (*o);
3188 			break;
3189 		}
3190 	}
3191 
3192 	// If the processor (node) is not on the route then create it
3193 
3194 	if (o == _processors.end()) {
3195 
3196 		boost::shared_ptr<Processor> processor;
3197 
3198 		if (prop->value() == "intsend") {
3199 
3200 			processor.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), boost::shared_ptr<Route>(), Delivery::Aux, true));
3201 
3202 		} else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
3203 		           prop->value() == "lv2" ||
3204 		           prop->value() == "windows-vst" ||
3205 		           prop->value() == "mac-vst" ||
3206 		           prop->value() == "lxvst" ||
3207 		           prop->value() == "luaproc" ||
3208 		           prop->value() == "vst3" ||
3209 		           prop->value() == "audiounit") {
3210 
3211 			if (_session.get_disable_all_loaded_plugins ()) {
3212 				processor.reset (new UnknownProcessor (_session, node));
3213 			} else {
3214 				processor.reset (new PluginInsert (_session));
3215 				processor->set_owner (this);
3216 			}
3217 		} else if (prop->value() == "port") {
3218 
3219 			processor.reset (new PortInsert (_session, _pannable, _mute_master));
3220 
3221 		} else if (prop->value() == "send") {
3222 
3223 			processor.reset (new Send (_session, _pannable, _mute_master, Delivery::Send, true));
3224 			boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
3225 			send->SelfDestruct.connect_same_thread (*send, boost::bind (&Route::processor_selfdestruct, this, boost::weak_ptr<Processor> (processor)));
3226 			if (send->output()) {
3227 				send->output()->changed.connect_same_thread (*send, boost::bind (&Route::output_change_handler, this, _1, _2));
3228 			}
3229 
3230 		} else {
3231 			warning << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
3232 			return false;
3233 		}
3234 
3235 		if (processor->set_state (node, version) != 0) {
3236 			/* This processor could not be configured.  Turn it into a UnknownProcessor */
3237 			processor.reset (new UnknownProcessor (_session, node));
3238 		}
3239 
3240 		/* set strict I/O only after loading plugin state, because
3241 		 * individual plugins may override this */
3242 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (processor);
3243 		if (pi && _strict_io) {
3244 			pi->set_strict_io (true);
3245 		}
3246 
3247 		/* subscribe to Sidechain IO changes */
3248 		if (pi && pi->has_sidechain ()) {
3249 			pi->sidechain_input ()->changed.connect_same_thread (*pi, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
3250 		}
3251 
3252 		/* we have to note the monitor send here, otherwise a new one will be created
3253 		   and the state of this one will be lost.
3254 		*/
3255 		boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
3256 		if (isend && isend->role() == Delivery::Listen) {
3257 			_monitor_send = isend;
3258 		}
3259 
3260 		/* it doesn't matter if invisible processors are added here, as they
3261 		   will be sorted out by setup_invisible_processors () shortly.
3262 		*/
3263 
3264 		new_order.push_back (processor);
3265 		must_configure = true;
3266 	}
3267 	return true;
3268 }
3269 
3270 void
silence(samplecnt_t nframes)3271 Route::silence (samplecnt_t nframes)
3272 {
3273 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3274 	if (!lm.locked()) {
3275 		return;
3276 	}
3277 
3278 	silence_unlocked (nframes);
3279 }
3280 
3281 void
silence_unlocked(samplecnt_t nframes)3282 Route::silence_unlocked (samplecnt_t nframes)
3283 {
3284 	/* Must be called with the processor lock held */
3285 
3286 	const samplepos_t now = _session.transport_sample ();
3287 
3288 	_output->silence (nframes);
3289 
3290 	// update owned automated controllables
3291 	automation_run (now, nframes);
3292 	if (_pannable) {
3293 		_pannable->automation_run (now, nframes);
3294 	}
3295 
3296 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3297 		boost::shared_ptr<PluginInsert> pi;
3298 
3299 		if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
3300 			/* evaluate automated automation controls */
3301 			pi->automation_run (now, nframes);
3302 			/* skip plugins, they don't need anything when we're not active */
3303 			continue;
3304 		}
3305 
3306 		(*i)->silence (nframes, now);
3307 	}
3308 }
3309 
3310 void
add_internal_return()3311 Route::add_internal_return ()
3312 {
3313 	if (!_intreturn) {
3314 		_intreturn.reset (new InternalReturn (_session));
3315 		add_processor (_intreturn, PreFader);
3316 	}
3317 }
3318 
3319 void
add_send_to_internal_return(InternalSend * send)3320 Route::add_send_to_internal_return (InternalSend* send)
3321 {
3322 	Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3323 
3324 	for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3325 		boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3326 
3327 		if (d) {
3328 			return d->add_send (send);
3329 		}
3330 	}
3331 }
3332 
3333 void
remove_send_from_internal_return(InternalSend * send)3334 Route::remove_send_from_internal_return (InternalSend* send)
3335 {
3336 	Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3337 
3338 	for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3339 		boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3340 
3341 		if (d) {
3342 			return d->remove_send (send);
3343 		}
3344 	}
3345 }
3346 
3347 void
enable_monitor_send()3348 Route::enable_monitor_send ()
3349 {
3350 	/* Caller must hold process lock */
3351 	assert (!AudioEngine::instance()->process_lock().trylock());
3352 
3353 	/* master never sends to monitor section via the normal mechanism */
3354 	assert (!is_master ());
3355 	assert (!is_monitor ());
3356 
3357 	/* make sure we have one */
3358 	if (!_monitor_send) {
3359 		_monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), _session.monitor_out(), Delivery::Listen));
3360 		_monitor_send->set_display_to_user (false);
3361 	}
3362 
3363 	/* set it up */
3364 	configure_processors (0);
3365 }
3366 
3367 /** Add an aux send to a route.
3368  *  @param route route to send to.
3369  *  @param before Processor to insert before, or 0 to insert at the end.
3370  */
3371 int
add_aux_send(boost::shared_ptr<Route> route,boost::shared_ptr<Processor> before)3372 Route::add_aux_send (boost::shared_ptr<Route> route, boost::shared_ptr<Processor> before)
3373 {
3374 	assert (route != _session.monitor_out ());
3375 
3376 	{
3377 		Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3378 
3379 		for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3380 
3381 			boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3382 
3383 			if (d && d->target_route() == route) {
3384 				/* already listening via the specified IO: do nothing */
3385 				return 0;
3386 			}
3387 		}
3388 	}
3389 
3390 	try {
3391 
3392 		boost::shared_ptr<InternalSend> listener;
3393 
3394 		{
3395 			Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3396 			listener.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Aux));
3397 		}
3398 
3399 		add_processor (listener, before);
3400 
3401 	} catch (failed_constructor& err) {
3402 		return -1;
3403 	}
3404 
3405 	return 0;
3406 }
3407 
3408 int
add_foldback_send(boost::shared_ptr<Route> route,bool post_fader)3409 Route::add_foldback_send (boost::shared_ptr<Route> route, bool post_fader)
3410 {
3411 	assert (route != _session.monitor_out ());
3412 	boost::shared_ptr<Processor> before;
3413 	if (post_fader) {
3414 		before = before_processor_for_placement (PostFader);
3415 	} else {
3416 		before = before_processor_for_placement (PreFader);
3417 	}
3418 
3419 	{
3420 		Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3421 
3422 		for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3423 
3424 			boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3425 
3426 			if (d && d->target_route() == route) {
3427 				/* already listening via the specified IO: do nothing */
3428 				return 0;
3429 			}
3430 		}
3431 	}
3432 
3433 	try {
3434 
3435 		boost::shared_ptr<InternalSend> listener;
3436 
3437 		{
3438 			Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3439 			listener.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Foldback));
3440 		}
3441 
3442 		listener->panner_shell()->set_linked_to_route (false);
3443 		listener->set_pre_fader (!post_fader);
3444 		add_processor (listener, before);
3445 
3446 	} catch (failed_constructor& err) {
3447 		return -1;
3448 	}
3449 	_session.FBSendsChanged ();
3450 
3451 	return 0;
3452 }
3453 
3454 void
remove_monitor_send()3455 Route::remove_monitor_send ()
3456 {
3457 	/* caller needs to hold process lock */
3458 	if (!_monitor_send) {
3459 		return;
3460 	}
3461 	ProcessorStreams err;
3462 	remove_processor (_monitor_send, &err, false);
3463 	_monitor_send.reset ();
3464 }
3465 
3466 void
set_comment(string cmt,void * src)3467 Route::set_comment (string cmt, void *src)
3468 {
3469 	_comment = cmt;
3470 	comment_changed ();
3471 	_session.set_dirty ();
3472 }
3473 
3474 bool
add_fed_by(boost::shared_ptr<Route> other,bool via_sends_only)3475 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
3476 {
3477 	FeedRecord fr (other, via_sends_only);
3478 
3479 	pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
3480 
3481 	if (!result.second) {
3482 
3483 		/* already a record for "other" - make sure sends-only information is correct */
3484 		if (!via_sends_only && result.first->sends_only) {
3485 			FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
3486 			frp->sends_only = false;
3487 		}
3488 	}
3489 
3490 	return result.second;
3491 }
3492 
3493 void
clear_fed_by()3494 Route::clear_fed_by ()
3495 {
3496 	_fed_by.clear ();
3497 }
3498 
3499 bool
feeds(boost::shared_ptr<Route> other,bool * via_sends_only)3500 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
3501 {
3502 	const FedBy& fed_by (other->fed_by());
3503 
3504 	for (FedBy::const_iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
3505 		boost::shared_ptr<Route> sr = f->r.lock();
3506 
3507 		if (sr && (sr.get() == this)) {
3508 
3509 			if (via_sends_only) {
3510 				*via_sends_only = f->sends_only;
3511 			}
3512 
3513 			return true;
3514 		}
3515 	}
3516 
3517 	return false;
3518 }
3519 
3520 IOVector
all_inputs() const3521 Route::all_inputs () const
3522 {
3523 	/* TODO, if this works as expected,
3524 	 * cache the IOVector and maintain it via
3525 	 * input_change_handler(), sidechain_change_handler() etc
3526 	 */
3527 	IOVector ios;
3528 	ios.push_back (_input);
3529 
3530 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3531 	for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3532 
3533 		boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3534 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3535 		if (pi != 0) {
3536 			assert (iop == 0);
3537 			iop = pi->sidechain();
3538 		}
3539 
3540 		if (iop != 0 && iop->input()) {
3541 			ios.push_back (iop->input());
3542 		}
3543 	}
3544 	return ios;
3545 }
3546 
3547 IOVector
all_outputs() const3548 Route::all_outputs () const
3549 {
3550 	IOVector ios;
3551 	// _output is included via Delivery
3552 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3553 	for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3554 		boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3555 		if (iop != 0 && iop->output()) {
3556 			ios.push_back (iop->output());
3557 		}
3558 	}
3559 	return ios;
3560 }
3561 
3562 bool
direct_feeds_according_to_reality(boost::shared_ptr<Route> other,bool * via_send_only)3563 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
3564 {
3565 	DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds from %1 (-> %2)?\n", _name, other->name()));
3566 	if (other->all_inputs().fed_by (_output)) {
3567 		DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS to %1\n", other->name()));
3568 		if (via_send_only) {
3569 			*via_send_only = false;
3570 		}
3571 
3572 		return true;
3573 	}
3574 
3575 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3576 
3577 	for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
3578 
3579 		boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3580 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3581 		if (pi != 0) {
3582 			assert (iop == 0);
3583 			iop = pi->sidechain();
3584 		}
3585 
3586 		if (iop != 0) {
3587 			boost::shared_ptr<const IO> iop_out = iop->output();
3588 			if (other.get() == this && iop_out && iop->input() && iop_out->connected_to (iop->input())) {
3589 				// TODO this needs a delaylines in the Insert to align connections (!)
3590 				DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed its own return (%2)\n", iop->name(), other->name()));
3591 				continue;
3592 			}
3593 			if ((iop_out && other->all_inputs().fed_by (iop_out)) || iop->feeds (other)) {
3594 				DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
3595 				if (via_send_only) {
3596 					*via_send_only = true;
3597 				}
3598 				return true;
3599 			} else {
3600 				DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
3601 			}
3602 		}
3603 	}
3604 
3605 	DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
3606 	return false;
3607 }
3608 
3609 bool
direct_feeds_according_to_graph(boost::shared_ptr<Route> other,bool * via_send_only)3610 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
3611 {
3612 	return _session._current_route_graph.has (boost::dynamic_pointer_cast<Route> (shared_from_this ()), other, via_send_only);
3613 }
3614 
3615 bool
feeds_according_to_graph(boost::shared_ptr<Route> other)3616 Route::feeds_according_to_graph (boost::shared_ptr<Route> other)
3617 {
3618 	return _session._current_route_graph.feeds (boost::dynamic_pointer_cast<Route> (shared_from_this ()), other);
3619 }
3620 
3621 /** Called from the (non-realtime) butler thread when the transport is stopped */
3622 void
non_realtime_transport_stop(samplepos_t now,bool flush)3623 Route::non_realtime_transport_stop (samplepos_t now, bool flush)
3624 {
3625 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3626 
3627 	Automatable::non_realtime_transport_stop (now, flush);
3628 
3629 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3630 
3631 		if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && flush)) {
3632 			(*i)->flush ();
3633 		}
3634 
3635 		(*i)->non_realtime_transport_stop (now, flush);
3636 	}
3637 }
3638 
3639 void
realtime_handle_transport_stopped()3640 Route::realtime_handle_transport_stopped ()
3641 {
3642 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3643 
3644 	/* currently only by Plugin, queue note-off events */
3645 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3646 		(*i)->realtime_handle_transport_stopped ();
3647 	}
3648 }
3649 
3650 
3651 void
input_change_handler(IOChange change,void *)3652 Route::input_change_handler (IOChange change, void * /*src*/)
3653 {
3654 	if (_session.loading ()) {
3655 		return;
3656 	}
3657 
3658 	if ((change.type & IOChange::ConfigurationChanged)) {
3659 		/* This is called with the process lock held if change
3660 		   contains ConfigurationChanged
3661 		*/
3662 		configure_processors (0);
3663 		io_changed (); /* EMIT SIGNAL */
3664 	}
3665 
3666 	if (_initial_io_setup) {
3667 		return;
3668 	}
3669 
3670 	if (_solo_control->soloed_by_others_upstream() || _solo_isolate_control->solo_isolated_by_upstream()) {
3671 		int sbou = 0;
3672 		int ibou = 0;
3673 		boost::shared_ptr<RouteList> routes = _session.get_routes ();
3674 		if (_input->connected()) {
3675 			for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3676 				if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3677 					continue;
3678 				}
3679 				if ((*i)->direct_feeds_according_to_reality (boost::dynamic_pointer_cast<Route> (shared_from_this()))) {
3680 					if ((*i)->soloed()) {
3681 						++sbou;
3682 					}
3683 					if ((*i)->solo_isolate_control()->solo_isolated()) {
3684 						++ibou;
3685 					}
3686 				}
3687 			}
3688 		}
3689 
3690 		int delta  = sbou - _solo_control->soloed_by_others_upstream();
3691 		int idelta = ibou - _solo_isolate_control->solo_isolated_by_upstream();
3692 
3693 		if (idelta < -1) {
3694 			PBD::warning << string_compose (
3695 			                _("Invalid Solo-Isolate propagation: from:%1 new:%2 - old:%3 = delta:%4"),
3696 			                _name, ibou, _solo_isolate_control->solo_isolated_by_upstream(), idelta)
3697 			             << endmsg;
3698 
3699 		}
3700 
3701 		if (_solo_control->soloed_by_others_upstream()) {
3702 			// ignore new connections (they're not propagated)
3703 			if (delta <= 0) {
3704 				_solo_control->mod_solo_by_others_upstream (delta);
3705 			}
3706 		}
3707 
3708 		if (_solo_isolate_control->solo_isolated_by_upstream()) {
3709 			// solo-isolate currently only propagates downstream
3710 			if (idelta < 0) {
3711 				_solo_isolate_control->mod_solo_isolated_by_upstream (1);
3712 			}
3713 			//_solo_isolated_by_upstream = ibou;
3714 		}
3715 
3716 		// Session::route_solo_changed  does not propagate indirect solo-changes
3717 		// propagate downstream to tracks
3718 		for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3719 			if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3720 				continue;
3721 			}
3722 			bool does_feed = feeds (*i);
3723 			if (delta <= 0 && does_feed) {
3724 				(*i)->solo_control()->mod_solo_by_others_upstream (delta);
3725 			}
3726 
3727 			if (idelta < 0 && does_feed) {
3728 				(*i)->solo_isolate_control()->mod_solo_isolated_by_upstream (-1);
3729 			}
3730 		}
3731 	}
3732 }
3733 
3734 void
output_change_handler(IOChange change,void *)3735 Route::output_change_handler (IOChange change, void * /*src*/)
3736 {
3737 	if (_initial_io_setup) {
3738 		return;
3739 	}
3740 
3741 	if ((change.type & IOChange::ConfigurationChanged)) {
3742 		/* This is called with the process lock held if change
3743 		   contains ConfigurationChanged
3744 		*/
3745 		configure_processors (0);
3746 
3747 		if (is_master()) {
3748 			_session.reset_monitor_section();
3749 		}
3750 
3751 		io_changed (); /* EMIT SIGNAL */
3752 	}
3753 
3754 	if (_session.loading ()) {
3755 		return;
3756 	}
3757 
3758 	if ((change.type & IOChange::ConnectionsChanged)) {
3759 
3760 		/* do this ONLY if connections have changed. Configuration
3761 		 * changes do not, by themselves alter solo upstream or
3762 		 * downstream status.
3763 		 */
3764 
3765 		if (_solo_control->soloed_by_others_downstream()) {
3766 			int sbod = 0;
3767 			/* checking all all downstream routes for
3768 			 * explicit of implict solo is a rather drastic measure,
3769 			 * ideally the input_change_handler() of the other route
3770 			 * would propagate the change to us.
3771 			 */
3772 			boost::shared_ptr<RouteList> routes = _session.get_routes ();
3773 			if (_output->connected()) {
3774 				for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3775 					if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3776 						continue;
3777 					}
3778 					if (direct_feeds_according_to_reality (*i)) {
3779 						if ((*i)->soloed()) {
3780 							++sbod;
3781 							break;
3782 						}
3783 					}
3784 				}
3785 			}
3786 
3787 			int delta = sbod - _solo_control->soloed_by_others_downstream();
3788 			if (delta <= 0) {
3789 				// do not allow new connections to change implicit solo (no propagation)
3790 				_solo_control->mod_solo_by_others_downstream (delta);
3791 				// Session::route_solo_changed() does not propagate indirect solo-changes
3792 				// propagate upstream to tracks
3793 				boost::shared_ptr<Route> shared_this = boost::dynamic_pointer_cast<Route> (shared_from_this());
3794 				for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3795 					if ((*i).get() == this || !can_solo()) {
3796 						continue;
3797 					}
3798 					if (delta != 0 && (*i)->feeds (shared_this)) {
3799 						(*i)->solo_control()->mod_solo_by_others_downstream (delta);
3800 					}
3801 				}
3802 
3803 			}
3804 		}
3805 	}
3806 }
3807 
3808 void
sidechain_change_handler(IOChange change,void * src)3809 Route::sidechain_change_handler (IOChange change, void* src)
3810 {
3811 	if (_initial_io_setup || _in_sidechain_setup) {
3812 		return;
3813 	}
3814 
3815 	input_change_handler (change, src);
3816 }
3817 
3818 uint32_t
pans_required() const3819 Route::pans_required () const
3820 {
3821 	if (n_outputs().n_audio() < 2) {
3822 		return 0;
3823 	}
3824 
3825 	return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
3826 }
3827 
3828 void
flush_processor_buffers_locked(samplecnt_t nframes)3829 Route::flush_processor_buffers_locked (samplecnt_t nframes)
3830 {
3831 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3832 		boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
3833 		if (d) {
3834 			d->flush_buffers (nframes);
3835 		} else {
3836 			boost::shared_ptr<PortInsert> p = boost::dynamic_pointer_cast<PortInsert> (*i);
3837 			if (p) {
3838 				p->flush_buffers (nframes);
3839 			}
3840 		}
3841 	}
3842 }
3843 
3844 void
flush_processors()3845 Route::flush_processors ()
3846 {
3847 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3848 
3849 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3850 		(*i)->flush ();
3851 	}
3852 }
3853 
3854 samplecnt_t
playback_latency(bool incl_downstream) const3855 Route::playback_latency (bool incl_downstream) const
3856 {
3857 	samplecnt_t rv;
3858 	if (_disk_reader) {
3859 		rv = _disk_reader->output_latency ();
3860 	} else {
3861 		rv = _signal_latency;
3862 	}
3863 	if (incl_downstream) {
3864 		rv += _output->connected_latency (true);
3865 	} else {
3866 		rv += _output_latency;
3867 	}
3868 	return rv;
3869 }
3870 
3871 pframes_t
latency_preroll(pframes_t nframes,samplepos_t & start_sample,samplepos_t & end_sample)3872 Route::latency_preroll (pframes_t nframes, samplepos_t& start_sample, samplepos_t& end_sample)
3873 {
3874 	samplecnt_t latency_preroll = _session.remaining_latency_preroll ();
3875 	if (latency_preroll == 0) {
3876 		return nframes;
3877 	}
3878 	if (!_disk_reader) {
3879 		if (_session.transport_speed() < 0) {
3880 			start_sample += latency_preroll;
3881 			end_sample   += latency_preroll;
3882 		} else {
3883 			start_sample -= latency_preroll;
3884 			end_sample   -= latency_preroll;
3885 		}
3886 		return nframes;
3887 	}
3888 
3889 	if (latency_preroll > playback_latency ()) {
3890 		no_roll_unlocked (nframes, start_sample - latency_preroll, end_sample - latency_preroll, false);
3891 		return 0;
3892 	}
3893 
3894 	if (_session.transport_speed() < 0) {
3895 		start_sample += latency_preroll;
3896 		end_sample   += latency_preroll;
3897 	} else {
3898 		start_sample -= latency_preroll;
3899 		end_sample -= latency_preroll;
3900 	}
3901 	return nframes;
3902 }
3903 
3904 int
roll(pframes_t nframes,samplepos_t start_sample,samplepos_t end_sample,bool & need_butler)3905 Route::roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool& need_butler)
3906 {
3907 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3908 
3909 	if (!lm.locked()) {
3910 		return 0;
3911 	}
3912 
3913 	if (!_active) {
3914 		silence_unlocked (nframes);
3915 		_meter->reset();
3916 		return 0;
3917 	}
3918 
3919 	if ((nframes = latency_preroll (nframes, start_sample, end_sample)) == 0) {
3920 		return 0;
3921 	}
3922 
3923 	run_route (start_sample, end_sample, nframes, (!_disk_writer || !_disk_writer->record_enabled()) && _session.transport_rolling(), true);
3924 
3925 	if ((_disk_reader && _disk_reader->need_butler()) || (_disk_writer && _disk_writer->need_butler())) {
3926 		need_butler = true;
3927 	}
3928 	return 0;
3929 }
3930 
3931 int
no_roll(pframes_t nframes,samplepos_t start_sample,samplepos_t end_sample,bool session_state_changing)3932 Route::no_roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool session_state_changing)
3933 {
3934 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3935 
3936 	if (!lm.locked()) {
3937 		return 0;
3938 	}
3939 
3940 	return no_roll_unlocked (nframes, start_sample, end_sample, session_state_changing);
3941 }
3942 
3943 int
no_roll_unlocked(pframes_t nframes,samplepos_t start_sample,samplepos_t end_sample,bool session_state_changing)3944 Route::no_roll_unlocked (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool session_state_changing)
3945 {
3946 	/* Must be called with the processor lock held */
3947 
3948 	if (!_active) {
3949 		silence_unlocked (nframes);
3950 		_meter->reset();
3951 		return 0;
3952 	}
3953 
3954 	if (session_state_changing) {
3955 		if (_session.transport_speed() != 0.0f) {
3956 			/* we're rolling but some state is changing (e.g. our diskstream contents)
3957 			   so we cannot use them. Be silent till this is over.
3958 
3959 			   XXX note the absurdity of ::no_roll() being called when we ARE rolling!
3960 			*/
3961 			silence_unlocked (nframes);
3962 			_meter->reset();
3963 			return 0;
3964 		}
3965 		/* we're really not rolling, so we're either delivery silence or actually
3966 		   monitoring, both of which are safe to do while session_state_changing is true.
3967 		*/
3968 	}
3969 
3970 	run_route (start_sample, end_sample, nframes, false, false);
3971 	return 0;
3972 }
3973 
3974 int
silent_roll(pframes_t nframes,samplepos_t,samplepos_t,bool &)3975 Route::silent_roll (pframes_t nframes, samplepos_t /*start_sample*/, samplepos_t /*end_sample*/, bool& /* need_butler */)
3976 {
3977 	silence (nframes);
3978 	flush_processor_buffers_locked (nframes);
3979 	return 0;
3980 }
3981 
3982 #ifdef __clang__
3983 __attribute__((annotate("realtime")))
3984 #endif
3985 bool
apply_processor_changes_rt()3986 Route::apply_processor_changes_rt ()
3987 {
3988 	int emissions = EmitNone;
3989 
3990 	if (_pending_meter_point != _meter_point) {
3991 		Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
3992 		if (pwl.locked()) {
3993 			/* meters always have buffers for 'processor_max_streams'
3994 			 * they can be re-positioned without re-allocation */
3995 			if (set_meter_point_unlocked()) {
3996 				emissions |= EmitMeterChanged | EmitMeterVisibilityChange;;
3997 			} else {
3998 				emissions |= EmitMeterChanged;
3999 			}
4000 		}
4001 	}
4002 
4003 	bool changed = false;
4004 
4005 	if (g_atomic_int_get (&_pending_process_reorder)) {
4006 		Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4007 		if (pwl.locked()) {
4008 			g_atomic_int_set (&_pending_process_reorder, 0);
4009 			g_atomic_int_set (&_pending_listen_change, 0);
4010 			apply_processor_order (_pending_processor_order);
4011 			_pending_processor_order.clear ();
4012 			setup_invisible_processors ();
4013 			changed = true;
4014 			emissions |= EmitRtProcessorChange;
4015 		}
4016 	}
4017 
4018 	if (g_atomic_int_get (&_pending_listen_change)) {
4019 		Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4020 		if (pwl.locked()) {
4021 			g_atomic_int_set (&_pending_listen_change, 0);
4022 			setup_invisible_processors ();
4023 			changed = true;
4024 			emissions |= EmitRtProcessorChange;
4025 		}
4026 	}
4027 
4028 	if (changed) {
4029 		set_processor_positions ();
4030 		/* update processor input/output latency
4031 		 * (total signal_latency does not change)
4032 		 */
4033 		update_signal_latency (true);
4034 	}
4035 	if (emissions != 0) {
4036 		g_atomic_int_set (&_pending_signals, emissions);
4037 		return true;
4038 	}
4039 	return (!selfdestruct_sequence.empty ());
4040 }
4041 
4042 void
emit_pending_signals()4043 Route::emit_pending_signals ()
4044 {
4045 	int sig = g_atomic_int_and (&_pending_signals, 0);
4046 	if (sig & EmitMeterChanged) {
4047 		_meter->emit_configuration_changed();
4048 		meter_change (); /* EMIT SIGNAL */
4049 		if (sig & EmitMeterVisibilityChange) {
4050 		processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
4051 		} else {
4052 		processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
4053 		}
4054 	}
4055 	if (sig & EmitRtProcessorChange) {
4056 		processors_changed (RouteProcessorChange (RouteProcessorChange::RealTimeChange)); /* EMIT SIGNAL */
4057 	}
4058 
4059 	/* this would be a job for the butler.
4060 	 * Conceptually we should not take processe/processor locks here.
4061 	 * OTOH its more efficient (less overhead for summoning the butler and
4062 	 * telling her what do do) and signal emission is called
4063 	 * directly after the process callback, which decreases the chance
4064 	 * of xruns when taking the locks.
4065 	 */
4066 	while (!selfdestruct_sequence.empty ()) {
4067 		Glib::Threads::Mutex::Lock lx (selfdestruct_lock);
4068 		if (selfdestruct_sequence.empty ()) { break; } // re-check with lock
4069 		boost::shared_ptr<Processor> proc = selfdestruct_sequence.back ().lock ();
4070 		selfdestruct_sequence.pop_back ();
4071 		lx.release ();
4072 		if (proc) {
4073 			remove_processor (proc);
4074 		}
4075 	}
4076 }
4077 
4078 void
set_meter_point(MeterPoint p)4079 Route::set_meter_point (MeterPoint p)
4080 {
4081 	if (_pending_meter_point == p) {
4082 		return;
4083 	}
4084 
4085 	if (!AudioEngine::instance()->running()) {
4086 		bool meter_visibly_changed = false;
4087 		{
4088 			Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4089 			Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4090 			_pending_meter_point = p;
4091 			if (set_meter_point_unlocked ()) {
4092 				meter_visibly_changed = true;
4093 			}
4094 		}
4095 		_meter->emit_configuration_changed();
4096 		meter_change (); /* EMIT SIGNAL */
4097 		processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
4098 	} else {
4099 		_pending_meter_point = p;
4100 	}
4101 }
4102 
4103 
4104 #ifdef __clang__
4105 __attribute__((annotate("realtime")))
4106 #endif
4107 bool
set_meter_point_unlocked()4108 Route::set_meter_point_unlocked ()
4109 {
4110 #ifndef NDEBUG
4111 	/* Caller must hold process and processor write lock */
4112 	assert (!AudioEngine::instance()->process_lock().trylock());
4113 	Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4114 	assert (!lm.locked ());
4115 #endif
4116 
4117 	_meter_point = _pending_meter_point;
4118 
4119 	bool meter_was_visible_to_user = _meter->display_to_user ();
4120 
4121 	if (!_custom_meter_position_noted) {
4122 		maybe_note_meter_position ();
4123 	}
4124 
4125 	if (_meter_point != MeterCustom) {
4126 
4127 		_meter->set_display_to_user (false);
4128 
4129 		setup_invisible_processors ();
4130 
4131 	} else {
4132 		_meter->set_display_to_user (true);
4133 
4134 		/* If we have a previous position for the custom meter, try to put it there */
4135 		boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
4136 		if (after) {
4137 			ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
4138 			if (i != _processors.end ()) {
4139 				_processors.remove (_meter);
4140 				_processors.insert (i, _meter);
4141 			}
4142 		} else {// at end, right before the mains_out/panner
4143 			_processors.remove (_meter);
4144 			ProcessorList::iterator main = _processors.end();
4145 			_processors.insert (--main, _meter);
4146 		}
4147 	}
4148 
4149 	/* Set up the meter for its new position */
4150 
4151 	ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
4152 
4153 	ChanCount m_in;
4154 
4155 	if (loc == _processors.begin()) {
4156 		m_in = _input->n_ports();
4157 	} else {
4158 		ProcessorList::iterator before = loc;
4159 		--before;
4160 		m_in = (*before)->output_streams ();
4161 	}
4162 
4163 	_meter->reflect_inputs (m_in);
4164 
4165 	/* we do not need to reconfigure the processors, because the meter
4166 	   (a) is always ready to handle processor_max_streams
4167 	   (b) is always an N-in/N-out processor, and thus moving
4168 	   it doesn't require any changes to the other processors.
4169 	*/
4170 
4171 	/* these should really be done after releasing the lock
4172 	 * but all those signals are subscribed to with gui_thread()
4173 	 * so we're safe.
4174 	 */
4175 	 return (_meter->display_to_user() != meter_was_visible_to_user);
4176 }
4177 
4178 void
listen_position_changed()4179 Route::listen_position_changed ()
4180 {
4181 	if (!_monitor_send) {
4182 		return;
4183 	}
4184 	/* check if re-order can be done in realtime */
4185 	ChanCount c;
4186 
4187 	switch (Config->get_listen_position ()) {
4188 		case PreFaderListen:
4189 			switch (Config->get_pfl_position ()) {
4190 				case PFLFromBeforeProcessors:
4191 					c = input_streams ();
4192 					break;
4193 				case PFLFromAfterProcessors:
4194 					c = _amp->input_streams ();
4195 					break;
4196 			}
4197 			break;
4198 		case AfterFaderListen:
4199 			switch (Config->get_afl_position ()) {
4200 				case AFLFromBeforeProcessors:
4201 					c = _amp->output_streams ();
4202 					break;
4203 				case AFLFromAfterProcessors:
4204 					c = _main_outs->input_streams ();
4205 					break;
4206 			}
4207 			break;
4208 	}
4209 
4210 	if (c == _monitor_send->input_streams () && AudioEngine::instance()->running()) {
4211 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock); // XXX is this needed?
4212 		g_atomic_int_set (&_pending_listen_change, 1);
4213 		return;
4214 	}
4215 
4216 	{
4217 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4218 		Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4219 		ProcessorState pstate (this);
4220 
4221 		if (configure_processors_unlocked (0, &lm)) {
4222 			DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
4223 			pstate.restore ();
4224 			configure_processors_unlocked (0, &lm); // it worked before we tried to add it ...
4225 			return;
4226 		}
4227 	}
4228 
4229 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
4230 	_session.set_dirty ();
4231 }
4232 
4233 boost::shared_ptr<CapturingProcessor>
add_export_point()4234 Route::add_export_point()
4235 {
4236 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4237 	if (!_capturing_processor) {
4238 		lm.release();
4239 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4240 		Glib::Threads::RWLock::WriterLock lw (_processor_lock);
4241 
4242 		/* Align all tracks for stem-export w/o processing.
4243 		 * Compensate for all plugins between the this route's disk-reader
4244 		 * and the common final downstream output (ie alignment point for playback).
4245 		 */
4246 		_capturing_processor.reset (new CapturingProcessor (_session, playback_latency (true)));
4247 		configure_processors_unlocked (0, &lw);
4248 		_capturing_processor->activate ();
4249 	}
4250 
4251 	return _capturing_processor;
4252 }
4253 
4254 samplecnt_t
update_signal_latency(bool apply_to_delayline,bool * delayline_update_needed)4255 Route::update_signal_latency (bool apply_to_delayline, bool* delayline_update_needed)
4256 {
4257 	if (!active()) {
4258 		_signal_latency = 0;
4259 		/* mark all send are inactive, set internal-return "delay-out" to zero. */
4260 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4261 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4262 			if (boost::shared_ptr<LatentSend> snd = boost::dynamic_pointer_cast<LatentSend> (*i)) {
4263 				snd->set_delay_in (0);
4264 			}
4265 			if (boost::shared_ptr<InternalReturn> rtn = boost::dynamic_pointer_cast<InternalReturn> (*i)) {
4266 				rtn->set_playback_offset (0);
4267 			}
4268 			// TODO sidechain inputs?!
4269 		}
4270 		return 0;
4271 	}
4272 
4273 	samplecnt_t capt_lat_in  = _input->connected_latency (false);
4274 	samplecnt_t play_lat_out = _output->connected_latency (true);
4275 	samplecnt_t in_latency   = _input->latency ();
4276 	_output_latency          = _output->latency ();
4277 
4278 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4279 
4280 	samplecnt_t l_in  = 0;
4281 	samplecnt_t l_out = 0;
4282 	for (ProcessorList::reverse_iterator i = _processors.rbegin(); i != _processors.rend(); ++i) {
4283 		if (boost::shared_ptr<LatentSend> snd = boost::dynamic_pointer_cast<LatentSend> (*i)) {
4284 			snd->set_delay_in (l_out + _output_latency);
4285 		}
4286 
4287 		if (boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4288 			if (boost::shared_ptr<IO> pio = pi->sidechain_input ()) {
4289 				samplecnt_t lat = l_out + _output_latency;
4290 				pio->set_private_port_latencies (lat, true);
4291 				pio->set_public_port_latencies (lat, true);
4292 			}
4293 		}
4294 		(*i)->set_output_latency (l_out);
4295 		if ((*i)->active ()) { // XXX
4296 			l_out += (*i)->effective_latency ();
4297 		}
4298 	}
4299 
4300 	DEBUG_TRACE (DEBUG::LatencyRoute, string_compose ("%1: internal signal latency = %2\n", _name, l_out));
4301 
4302 	_signal_latency = l_out;
4303 
4304 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4305 
4306 		/* set sidechain, send and insert port latencies */
4307 		if (boost::shared_ptr<PortInsert> pi = boost::dynamic_pointer_cast<PortInsert> (*i)) {
4308 			if (pi->input ()) {
4309 				/* propagate playback latency from output to input */
4310 				pi->input ()->set_private_port_latencies (play_lat_out + l_in, true);
4311 			}
4312 			if (pi->output ()) {
4313 				/* propagate capture latency from input to output */
4314 				pi->output ()->set_private_port_latencies (capt_lat_in + l_in, false);
4315 			}
4316 
4317 		} else if (boost::shared_ptr<Send> snd = boost::dynamic_pointer_cast<Send> (*i)) {
4318 			if (snd->output ()) {
4319 				/* set capture latency */
4320 				snd->output ()->set_private_port_latencies (capt_lat_in + l_in, false);
4321 				/* take send-target's playback latency into account */
4322 				snd->set_delay_out (snd->output ()->connected_latency (true));
4323 				/* InternalReturn::set_playback_offset() below, also calls set_delay_out() */
4324 			}
4325 		}
4326 
4327 		(*i)->set_input_latency (l_in);
4328 		(*i)->set_playback_offset (_signal_latency + _output_latency);
4329 		(*i)->set_capture_offset (in_latency);
4330 		if ((*i)->active ()) {
4331 			l_in += (*i)->effective_latency ();
4332 		}
4333 	}
4334 
4335 	lm.release ();
4336 
4337 	if (apply_to_delayline) {
4338 		/* see also Session::post_playback_latency() */
4339 		apply_latency_compensation ();
4340 	} else if (delayline_update_needed && _delayline) {
4341 		samplecnt_t play_lat_in = _input->connected_latency (true);
4342 		samplecnt_t latcomp = play_lat_in - play_lat_out - _signal_latency;
4343 		if (latcomp < 0) {
4344 			latcomp = 0;
4345 		}
4346 		if (_delayline->delay () != latcomp) {
4347 			*delayline_update_needed = true;
4348 		}
4349 	}
4350 
4351 	return _signal_latency;
4352 }
4353 
4354 void
apply_latency_compensation()4355 Route::apply_latency_compensation ()
4356 {
4357 	if (!_delayline) {
4358 		return;
4359 	}
4360 
4361 	samplecnt_t play_lat_in = _input->connected_latency (true);
4362 	samplecnt_t play_lat_out = _output->connected_latency (true);
4363 	samplecnt_t latcomp = play_lat_in - play_lat_out - _signal_latency;
4364 
4365 #if 0 // DEBUG
4366 	samplecnt_t capt_lat_in = _input->connected_latency (false);
4367 	samplecnt_t capt_lat_out = _output->connected_latency (false);
4368 	samplecnt_t latcomp_capt = capt_lat_out - capt_lat_in - _signal_latency;
4369 
4370 	cout << "ROUTE " << name() << " delay for " << latcomp << " (c: " << latcomp_capt << ")" << endl;
4371 #endif
4372 
4373 	_delayline->set_delay (latcomp > 0 ? latcomp : 0);
4374 }
4375 
4376 void
set_block_size(pframes_t nframes)4377 Route::set_block_size (pframes_t nframes)
4378 {
4379 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4380 		(*i)->set_block_size (nframes);
4381 	}
4382 
4383 	_session.ensure_buffers (n_process_buffers ());
4384 }
4385 
4386 void
protect_automation()4387 Route::protect_automation ()
4388 {
4389 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
4390 		(*i)->protect_automation();
4391 }
4392 
4393 /** Shift automation forwards from a particular place, thereby inserting time.
4394  *  Adds undo commands for any shifts that are performed.
4395  *
4396  * @param pos Position to start shifting from.
4397  * @param samples Amount to shift forwards by.
4398  */
4399 
4400 void
shift(samplepos_t pos,samplecnt_t samples)4401 Route::shift (samplepos_t pos, samplecnt_t samples)
4402 {
4403 	/* pan automation */
4404 	if (_pannable) {
4405 		ControlSet::Controls& c (_pannable->controls());
4406 
4407 		for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
4408 			boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
4409 			if (pc) {
4410 				boost::shared_ptr<AutomationList> al = pc->alist();
4411 				XMLNode& before = al->get_state ();
4412 				al->shift (pos, samples);
4413 				XMLNode& after = al->get_state ();
4414 				_session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4415 			}
4416 		}
4417 	}
4418 
4419 	/* TODO mute automation, MuteControl */
4420 
4421 	/* processor automation (incl. gain, trim,..) */
4422 	{
4423 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4424 		for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
4425 
4426 			set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
4427 
4428 			for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
4429 				boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
4430 				if (ac) {
4431 					boost::shared_ptr<AutomationList> al = ac->alist();
4432 					if (al->empty ()) {
4433 						continue;
4434 					}
4435 					XMLNode &before = al->get_state ();
4436 					al->shift (pos, samples);
4437 					XMLNode &after = al->get_state ();
4438 					_session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4439 				}
4440 			}
4441 		}
4442 	}
4443 }
4444 
4445 void
set_plugin_state_dir(boost::weak_ptr<Processor> p,const std::string & d)4446 Route::set_plugin_state_dir (boost::weak_ptr<Processor> p, const std::string& d)
4447 {
4448 	boost::shared_ptr<Processor> processor (p.lock ());
4449 	boost::shared_ptr<PluginInsert> pi  = boost::dynamic_pointer_cast<PluginInsert> (processor);
4450 	if (!pi) {
4451 		return;
4452 	}
4453 	pi->set_state_dir (d);
4454 }
4455 
4456 int
save_as_template(const string & path,const string & name,const string & description)4457 Route::save_as_template (const string& path, const string& name, const string& description)
4458 {
4459 	std::string state_dir = path.substr (0, path.find_last_of ('.')); // strip template_suffix
4460 	PBD::Unwinder<std::string> uw (_session._template_state_dir, state_dir);
4461 
4462 	XMLNode& node (state (true));
4463 	node.set_property (X_("name"), name);
4464 
4465 	node.remove_nodes (X_("description"));
4466 	if (!description.empty()) {
4467 		XMLNode* desc = new XMLNode(X_("description"));
4468 		XMLNode* desc_cont = new XMLNode(X_("content"), description);
4469 		desc->add_child_nocopy (*desc_cont);
4470 
4471 		node.add_child_nocopy (*desc);
4472 	}
4473 
4474 	XMLTree tree;
4475 
4476 	IO::set_name_in_state (*node.children().front(), name);
4477 
4478 	tree.set_root (&node);
4479 
4480 	/* return zero on success, non-zero otherwise */
4481 	return !tree.write (path.c_str());
4482 }
4483 
4484 
4485 bool
set_name(const string & str)4486 Route::set_name (const string& str)
4487 {
4488 	if (str.empty ()) {
4489 		return false;
4490 	}
4491 
4492 	if (str == name()) {
4493 		return true;
4494 	}
4495 
4496 	string newname = Route::ensure_track_or_route_name (str);
4497 
4498 	if (newname == name()) {
4499 		return true;
4500 	}
4501 
4502 	SessionObject::set_name (newname);
4503 
4504 	for (uint32_t n = 0 ; ; ++n) {
4505 		boost::shared_ptr<PluginInsert> pi = boost::static_pointer_cast<PluginInsert> (nth_plugin (n));
4506 		if (!pi) {
4507 			break;
4508 		}
4509 		pi->update_sidechain_name ();
4510 	}
4511 
4512 	bool ret = (_input->set_name(newname) && _output->set_name(newname));
4513 
4514 	if (ret) {
4515 		/* rename the main outs. Leave other IO processors
4516 		 * with whatever name they already have, because its
4517 		 * just fine as it is (it will not contain the route
4518 		 * name if its a port insert, port send or port return).
4519 		 */
4520 
4521 		if (_main_outs) {
4522 			if (_main_outs->set_name (newname)) {
4523 				/* XXX returning false here is stupid because
4524 				   we already changed the route name.
4525 				*/
4526 				return false;
4527 			}
4528 		}
4529 	}
4530 
4531 	return ret;
4532 }
4533 
4534 /** Set the name of a route in an XML description.
4535  *  @param node XML <Route> node to set the name in.
4536  *  @param name New name.
4537  */
4538 void
set_name_in_state(XMLNode & node,string const & name)4539 Route::set_name_in_state (XMLNode& node, string const & name)
4540 {
4541 	node.set_property (X_("name"), name);
4542 
4543 	XMLNodeList children = node.children();
4544 	for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
4545 
4546 		if ((*i)->name() == X_("IO")) {
4547 
4548 			IO::set_name_in_state (**i, name);
4549 
4550 		} else if ((*i)->name() == X_("Processor")) {
4551 
4552 			std::string str;
4553 			if ((*i)->get_property (X_("role"), str) && str == X_("Main")) {
4554 				(*i)->set_property (X_("name"), name);
4555 			}
4556 		}
4557 	}
4558 }
4559 
4560 boost::shared_ptr<Send>
internal_send_for(boost::shared_ptr<const Route> target) const4561 Route::internal_send_for (boost::shared_ptr<const Route> target) const
4562 {
4563 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4564 
4565 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4566 		boost::shared_ptr<InternalSend> send;
4567 
4568 		if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
4569 			if (send->target_route() == target) {
4570 				return send;
4571 			}
4572 		}
4573 	}
4574 
4575 	return boost::shared_ptr<Send>();
4576 }
4577 
4578 void
set_denormal_protection(bool yn)4579 Route::set_denormal_protection (bool yn)
4580 {
4581 	if (_denormal_protection != yn) {
4582 		_denormal_protection = yn;
4583 		denormal_protection_changed (); /* EMIT SIGNAL */
4584 	}
4585 }
4586 
4587 bool
denormal_protection() const4588 Route::denormal_protection () const
4589 {
4590 	return _denormal_protection;
4591 }
4592 
4593 void
set_active(bool yn,void * src)4594 Route::set_active (bool yn, void* src)
4595 {
4596 	if (_session.transport_rolling()) {
4597 		return;
4598 	}
4599 
4600 	if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
4601 		_route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
4602 		return;
4603 	}
4604 
4605 	if (_active != yn) {
4606 		_active = yn;
4607 		_input->set_active (yn);
4608 		_output->set_active (yn);
4609 		flush_processors ();
4610 		if (_active || _signal_latency > 0) {
4611 			processor_latency_changed (); /* EMIT SIGNAL */
4612 		}
4613 		active_changed (); // EMIT SIGNAL
4614 		_session.set_dirty ();
4615 	}
4616 }
4617 
4618 boost::shared_ptr<Pannable>
pannable() const4619 Route::pannable() const
4620 {
4621 	return _pannable;
4622 }
4623 
4624 boost::shared_ptr<Panner>
panner() const4625 Route::panner() const
4626 {
4627 	/* may be null ! */
4628 	return _main_outs->panner_shell()->panner();
4629 }
4630 
4631 boost::shared_ptr<PannerShell>
panner_shell() const4632 Route::panner_shell() const
4633 {
4634 	return _main_outs->panner_shell();
4635 }
4636 
4637 boost::shared_ptr<GainControl>
gain_control() const4638 Route::gain_control() const
4639 {
4640 	return _gain_control;
4641 }
4642 
4643 boost::shared_ptr<GainControl>
trim_control() const4644 Route::trim_control() const
4645 {
4646 	return _trim_control;
4647 }
4648 
4649 boost::shared_ptr<GainControl>
volume_control() const4650 Route::volume_control() const
4651 {
4652 	return _volume_control;
4653 }
4654 
4655 boost::shared_ptr<PhaseControl>
phase_control() const4656 Route::phase_control() const
4657 {
4658 	return _phase_control;
4659 }
4660 
4661 void
set_volume_applies_to_output(bool en)4662 Route::set_volume_applies_to_output (bool en)
4663 {
4664 	if (!is_master () || _volume_applies_to_output == en) {
4665 		return;
4666 	}
4667 	if (en) {
4668 		_volume->deactivate ();
4669 		_volume->set_display_to_user (false);
4670 		main_outs()->add_gain (_volume_control);
4671 		{
4672 			/* remove hidden processor */
4673 			Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4674 			configure_processors (NULL);
4675 		}
4676 		processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
4677 	} else {
4678 		_volume->set_display_to_user (true);
4679 		add_processor (_volume, PostFader, NULL, true);
4680 		_volume->activate ();
4681 		main_outs()->add_gain (boost::shared_ptr<GainControl> ());
4682 	}
4683 	_volume_applies_to_output = en;
4684 	_session.set_dirty ();
4685 }
4686 
4687 boost::shared_ptr<AutomationControl>
get_control(const Evoral::Parameter & param)4688 Route::get_control (const Evoral::Parameter& param)
4689 {
4690 	/* either we own the control or .... */
4691 
4692 	boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
4693 
4694 	if (!c) {
4695 
4696 		/* maybe one of our processors does or ... */
4697 
4698 		Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
4699 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4700 			if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
4701 				break;
4702 			}
4703 		}
4704 	}
4705 
4706 	if (!c) {
4707 
4708 		/* nobody does so we'll make a new one */
4709 
4710 		c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
4711 		add_control(c);
4712 	}
4713 
4714 	return c;
4715 }
4716 
4717 boost::shared_ptr<Processor>
nth_plugin(uint32_t n) const4718 Route::nth_plugin (uint32_t n) const
4719 {
4720 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4721 	ProcessorList::const_iterator i;
4722 
4723 	for (i = _processors.begin(); i != _processors.end(); ++i) {
4724 		if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4725 			if (n-- == 0) {
4726 				return *i;
4727 			}
4728 		}
4729 	}
4730 
4731 	return boost::shared_ptr<Processor> ();
4732 }
4733 
4734 boost::shared_ptr<Processor>
nth_send(uint32_t n) const4735 Route::nth_send (uint32_t n) const
4736 {
4737 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4738 	ProcessorList::const_iterator i;
4739 
4740 	for (i = _processors.begin(); i != _processors.end(); ++i) {
4741 		if (boost::dynamic_pointer_cast<Send> (*i)) {
4742 
4743 			if ((*i) == _monitor_send) {
4744 				/* send to monitor section is not considered
4745 				 * to be an accessible send.
4746 				 */
4747 				continue;
4748 			}
4749 
4750 			if (n-- == 0) {
4751 				return *i;
4752 			}
4753 		}
4754 	}
4755 
4756 	return boost::shared_ptr<Processor> ();
4757 }
4758 
4759 bool
has_io_processor_named(const string & name)4760 Route::has_io_processor_named (const string& name)
4761 {
4762 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4763 	ProcessorList::iterator i;
4764 
4765 	for (i = _processors.begin(); i != _processors.end(); ++i) {
4766 		if (boost::dynamic_pointer_cast<Send> (*i) ||
4767 		    boost::dynamic_pointer_cast<PortInsert> (*i)) {
4768 			if ((*i)->name() == name) {
4769 				return true;
4770 			}
4771 		}
4772 	}
4773 
4774 	return false;
4775 }
4776 
4777 void
set_processor_positions()4778 Route::set_processor_positions ()
4779 {
4780 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4781 
4782 	bool had_amp = false;
4783 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4784 		(*i)->set_pre_fader (!had_amp);
4785 		if (*i == _amp) {
4786 			had_amp = true;
4787 		}
4788 	}
4789 }
4790 
4791 /** Called when there is a proposed change to the input port count */
4792 bool
input_port_count_changing(ChanCount to)4793 Route::input_port_count_changing (ChanCount to)
4794 {
4795 	list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
4796 	if (c.empty()) {
4797 		/* The processors cannot be configured with the new input arrangement, so
4798 		   block the change.
4799 		*/
4800 		return true;
4801 	}
4802 
4803 	/* The change is ok */
4804 	return false;
4805 }
4806 
4807 /** Called when there is a proposed change to the output port count */
4808 bool
output_port_count_changing(ChanCount to)4809 Route::output_port_count_changing (ChanCount to)
4810 {
4811 	if (_strict_io && !_in_configure_processors) {
4812 		return true;
4813 	}
4814 	for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4815 		if (processor_out_streams.get(*t) > to.get(*t)) {
4816 			return true;
4817 		}
4818 	}
4819 	/* The change is ok */
4820 	return false;
4821 }
4822 
4823 list<string>
unknown_processors() const4824 Route::unknown_processors () const
4825 {
4826 	list<string> p;
4827 
4828 	if (_session.get_disable_all_loaded_plugins ()) {
4829 		// Do not list "missing plugins" if they are explicitly disabled
4830 		return p;
4831 	}
4832 
4833 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4834 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4835 		if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
4836 			p.push_back ((*i)->name ());
4837 		}
4838 	}
4839 
4840 	return p;
4841 }
4842 
4843 
4844 samplecnt_t
update_port_latencies(PortSet & from,PortSet & to,bool playback,samplecnt_t our_latency) const4845 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, samplecnt_t our_latency) const
4846 {
4847 	/* we assume that all our input ports feed all our output ports. its not
4848 	   universally true, but the alternative is way too corner-case to worry about.
4849 	*/
4850 
4851 	LatencyRange all_connections;
4852 
4853 	if (from.empty()) {
4854 		all_connections.min = 0;
4855 		all_connections.max = 0;
4856 	} else {
4857 		all_connections.min = ~((pframes_t) 0);
4858 		all_connections.max = 0;
4859 
4860 		/* iterate over all "from" ports and determine the latency range for all of their
4861 		 * connections to the "outside" (outside of this Route).
4862 		 */
4863 
4864 		for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4865 
4866 			if (!p->connected ()) {
4867 				/* ignore latency of unconnected ports, not not assume "0", they can float freely */
4868 				continue;
4869 			}
4870 
4871 			LatencyRange range;
4872 			p->get_connected_latency_range (range, playback);
4873 
4874 			all_connections.min = min (all_connections.min, range.min);
4875 			all_connections.max = max (all_connections.max, range.max);
4876 		}
4877 
4878 		if (all_connections.min == ~((pframes_t) 0)) {
4879 			all_connections.min = 0;
4880 		}
4881 	}
4882 
4883 	/* set the "from" port latencies to the max/min range of all their connections */
4884 
4885 	for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4886 		p->set_private_latency_range (all_connections, playback);
4887 	}
4888 
4889 	DEBUG_TRACE (DEBUG::LatencyRoute, string_compose ("%1: priv. port L(%2) = (%3, %4) + %5\n", _name, playback ? "playback" : "capture", all_connections.min, all_connections.max, our_latency));
4890 
4891 	/* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
4892 
4893 	all_connections.min += our_latency;
4894 	all_connections.max += our_latency;
4895 
4896 	for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
4897 		p->set_private_latency_range (all_connections, playback);
4898 	}
4899 
4900 	return all_connections.max;
4901 }
4902 
4903 samplecnt_t
set_private_port_latencies(bool playback) const4904 Route::set_private_port_latencies (bool playback) const
4905 {
4906 	samplecnt_t own_latency = 0;
4907 
4908 	/* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
4909 	   OR LATENCY CALLBACK.
4910 
4911 	   This is called (early) from the latency callback. It computes the REAL
4912 	   latency associated with each port and stores the result as the "private"
4913 	   latency of the port. A later call to Route::set_public_port_latencies()
4914 	   sets all ports to the same value to reflect the fact that we do latency
4915 	   compensation and so all signals are delayed by the same amount as they
4916 	   flow through ardour.
4917 	*/
4918 
4919 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4920 
4921 		if ((*i)->active ()) {
4922 			own_latency += (*i)->effective_latency ();
4923 		}
4924 	}
4925 
4926 	if (playback) {
4927 		/* playback: propagate latency from "outside the route" to outputs to inputs */
4928 		return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
4929 	} else {
4930 		/* capture: propagate latency from "outside the route" to inputs to outputs */
4931 		return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
4932 	}
4933 }
4934 
4935 void
set_public_port_latencies(samplecnt_t value,bool playback) const4936 Route::set_public_port_latencies (samplecnt_t value, bool playback) const
4937 {
4938 	/* publish private latencies */
4939 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4940 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4941 		boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*i);
4942 		if (!iop) {
4943 			continue;
4944 		}
4945 		if (iop->input ()) {
4946 			iop->input ()->set_public_port_latencies (iop->input()->latency(), true);
4947 		}
4948 		if (iop->output ()) {
4949 			iop->output ()->set_public_port_latencies (iop->output()->latency(), false);
4950 		}
4951 	}
4952 
4953 	/* this is called to set the JACK-visible port latencies, which take
4954 	 * latency compensation into account.
4955 	 */
4956 	_input->set_public_port_latencies (value, playback);
4957 	_output->set_public_port_latencies (value, playback);
4958 }
4959 
4960 /** Put the invisible processors in the right place in _processors.
4961  *  Must be called with a writer lock on _processor_lock held.
4962  */
4963 #ifdef __clang__
4964 __attribute__((annotate("realtime")))
4965 #endif
4966 void
setup_invisible_processors()4967 Route::setup_invisible_processors ()
4968 {
4969 #ifndef NDEBUG
4970 	Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4971 	assert (!lm.locked ());
4972 #endif
4973 
4974 	if (!_main_outs) {
4975 		/* too early to be doing this stuff */
4976 		return;
4977 	}
4978 
4979 	/* we'll build this new list here and then use it
4980 	 *
4981 	 * TODO put the ProcessorList is on the stack for RT-safety.
4982 	 */
4983 
4984 	ProcessorList new_processors;
4985 	ProcessorList foldback_sends;
4986 	ProcessorList::iterator dr;
4987 	ProcessorList::iterator dw;
4988 
4989 	/* find visible processors */
4990 
4991 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4992 		boost::shared_ptr<Send> auxsnd = boost::dynamic_pointer_cast<Send> ((*i));
4993 		if ((*i)->display_to_user ()) {
4994 			new_processors.push_back (*i);
4995 		}
4996 		else if (auxsnd && auxsnd->is_foldback ()) {
4997 			foldback_sends.push_back (*i);
4998 		}
4999 	}
5000 
5001 	/* find the amp */
5002 
5003 	ProcessorList::iterator amp = find (new_processors.begin(), new_processors.end(), _amp);
5004 
5005 	if (amp == new_processors.end ()) {
5006 		error << string_compose (_("Amp/Fader on track/bus '%1' was missing."), name()) << endmsg;
5007 		new_processors.push_front (_amp);
5008 		amp = find (new_processors.begin(), new_processors.end(), _amp);
5009 	}
5010 
5011 
5012 	/* Pre-fader METER */
5013 
5014 	if (_meter && _meter_point == MeterPreFader) {
5015 		/* add meter just before the fader */
5016 		assert (!_meter->display_to_user ());
5017 		new_processors.insert (amp, _meter);
5018 	}
5019 
5020 	/* MAIN OUTS */
5021 
5022 	assert (_main_outs);
5023 	assert (!_main_outs->display_to_user ());
5024 	new_processors.push_back (_main_outs);
5025 
5026 	/* iterator for the main outs */
5027 	ProcessorList::iterator main = new_processors.end();
5028 	--main;
5029 
5030 	/* OUTPUT METERING */
5031 
5032 	if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
5033 		assert (!_meter->display_to_user ());
5034 		/* add the processor just before or just after the main outs */
5035 		ProcessorList::iterator meter_point = main;
5036 		if (_meter_point == MeterOutput) {
5037 			++meter_point;
5038 		}
5039 		new_processors.insert (meter_point, _meter);
5040 	}
5041 
5042 	/* Foldback Sends */
5043 
5044 	for (ProcessorList::iterator i = foldback_sends.begin(); i != foldback_sends.end(); ++i) {
5045 		if ((*i)->get_pre_fader ()) {
5046 			new_processors.insert (amp, (*i));
5047 		} else {
5048 			new_processors.insert (main, (*i));
5049 		}
5050 	}
5051 
5052 	/* MONITOR SEND */
5053 
5054 	if (_monitor_send && !is_monitor ()) {
5055 		ProcessorList::iterator after_amp = amp;
5056 		++after_amp;
5057 
5058 		assert (!_monitor_send->display_to_user ());
5059 		switch (Config->get_listen_position ()) {
5060 		case PreFaderListen:
5061 			switch (Config->get_pfl_position ()) {
5062 			case PFLFromBeforeProcessors:
5063 				new_processors.push_front (_monitor_send);
5064 				break;
5065 			case PFLFromAfterProcessors:
5066 				new_processors.insert (amp, _monitor_send);
5067 				break;
5068 			}
5069 			_monitor_send->set_can_pan (false);
5070 			break;
5071 		case AfterFaderListen:
5072 			switch (Config->get_afl_position ()) {
5073 			case AFLFromBeforeProcessors:
5074 				new_processors.insert (after_amp, _monitor_send);
5075 				break;
5076 			case AFLFromAfterProcessors:
5077 				new_processors.insert (main, _monitor_send);
5078 				break;
5079 			}
5080 			_monitor_send->set_can_pan (true);
5081 			break;
5082 		}
5083 	}
5084 
5085 	/* MONITOR CONTROL */
5086 
5087 	if (_monitor_control && is_monitor ()) {
5088 		assert (!_monitor_control->display_to_user ());
5089 		new_processors.insert (amp, _monitor_control);
5090 	}
5091 
5092 	/* TRIM CONTROL */
5093 
5094 	ProcessorList::iterator trim = new_processors.end();
5095 
5096 	if (_trim->active()) {
5097 		assert (!_trim->display_to_user ());
5098 		new_processors.push_front (_trim);
5099 		trim = new_processors.begin();
5100 	}
5101 
5102 	/* INTERNAL RETURN */
5103 
5104 	/* doing this here means that any monitor control will come after
5105 	   the return and trim.
5106 	*/
5107 
5108 	if (_intreturn) {
5109 		assert (!_intreturn->display_to_user ());
5110 		new_processors.push_front (_intreturn);
5111 	}
5112 
5113 	/* DISK READER & WRITER (for Track objects) */
5114 
5115 	if (_disk_reader || _disk_writer) {
5116 		switch (_disk_io_point) {
5117 		case DiskIOPreFader:
5118 			if (trim != new_processors.end()) {
5119 				/* insert BEFORE TRIM */
5120 				if (_disk_writer) {
5121 					new_processors.insert (trim, _disk_writer);
5122 				}
5123 				if (_disk_reader) {
5124 					new_processors.insert (trim, _disk_reader);
5125 				}
5126 			} else {
5127 				if (_disk_writer) {
5128 					new_processors.push_front (_disk_writer);
5129 				}
5130 				if (_disk_reader) {
5131 					new_processors.push_front (_disk_reader);
5132 				}
5133 			}
5134 			break;
5135 		case DiskIOPostFader:
5136 			/* insert BEFORE main outs */
5137 			if (_disk_writer) {
5138 				new_processors.insert (main, _disk_writer);
5139 			}
5140 			if (_disk_reader) {
5141 				new_processors.insert (main, _disk_reader);
5142 			}
5143 			break;
5144 		case DiskIOCustom:
5145 			/* reader and writer are visible under this condition, so they
5146 			 * are not invisible and thus not handled here.
5147 			 */
5148 			break;
5149 		}
5150 	}
5151 
5152 	/* ensure dist-writer is before disk-reader */
5153 	if (_disk_reader && _disk_writer) {
5154 		ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
5155 		ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
5156 		assert (reader_pos != new_processors.end ());
5157 		assert (writer_pos != new_processors.end ());
5158 		if (std::distance (new_processors.begin(), reader_pos) < std::distance (new_processors.begin(), writer_pos)) {
5159 			new_processors.erase (reader_pos);
5160 			assert (writer_pos == find (new_processors.begin(), new_processors.end(), _disk_writer));
5161 			new_processors.insert (++writer_pos, _disk_reader);
5162 		}
5163 	}
5164 
5165 	/* EXPORT PROCESSOR */
5166 	if (_capturing_processor) {
5167 		assert (!_capturing_processor->display_to_user ());
5168 		ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
5169 		if (reader_pos != new_processors.end()) {
5170 			/* insert after disk-reader */
5171 			new_processors.insert (++reader_pos, _capturing_processor);
5172 		} else {
5173 			ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
5174 			/* insert after return */
5175 			if (return_pos != new_processors.end()) {
5176 				new_processors.insert (++return_pos, _capturing_processor);
5177 			} else {
5178 				new_processors.push_front (_capturing_processor);
5179 			}
5180 		}
5181 	}
5182 
5183 	/* Polarity Invert */
5184 	if (_polarity) {
5185 		ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
5186 		if (reader_pos != new_processors.end()) {
5187 			/* insert after disk-reader */
5188 			new_processors.insert (++reader_pos, _polarity);
5189 		} else {
5190 			ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
5191 			/* insert after return */
5192 			if (return_pos != new_processors.end()) {
5193 				new_processors.insert (++return_pos, _polarity);
5194 			} else {
5195 				new_processors.push_front (_polarity);
5196 			}
5197 		}
5198 	}
5199 
5200 	/* Input meter */
5201 	if (_meter && _meter_point == MeterInput) {
5202 		/* add meter just before the disk-writer (if any)
5203 		 * otherwise at the top, but after the latency delayline
5204 		 * (perhaps it should also be after intreturn on busses ??)
5205 		 */
5206 		assert (!_meter->display_to_user ());
5207 		ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
5208 		if (writer_pos != new_processors.end()) {
5209 			/* insert before disk-writer */
5210 			new_processors.insert (writer_pos, _meter);
5211 		} else {
5212 			ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
5213 			/* insert after return */
5214 			if (return_pos != new_processors.end()) {
5215 				new_processors.insert (++return_pos, _meter);
5216 			} else {
5217 				new_processors.push_front (_meter);
5218 			}
5219 		}
5220 	}
5221 
5222 	if (!is_master() && !is_monitor() && !is_auditioner()) {
5223 		ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
5224 		if (reader_pos != new_processors.end()) {
5225 			/* insert before disk-reader */
5226 			new_processors.insert (reader_pos, _delayline);
5227 		} else {
5228 			new_processors.push_front (_delayline);
5229 		}
5230 	}
5231 
5232 	_processors = new_processors;
5233 
5234 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5235 		if (!(*i)->display_to_user () && !(*i)->enabled () && (*i) != _monitor_send) {
5236 			(*i)->enable (true);
5237 		}
5238 	}
5239 
5240 	DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
5241 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5242 		DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
5243 	}
5244 }
5245 
5246 void
unpan()5247 Route::unpan ()
5248 {
5249 	Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
5250 	Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
5251 
5252 	_pannable.reset ();
5253 
5254 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5255 		boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
5256 		if (d) {
5257 			d->unpan ();
5258 		}
5259 	}
5260 }
5261 
5262 /** If the meter point is `Custom', make a note of where the meter is.
5263  *  This is so that if the meter point is subsequently set to something else,
5264  *  and then back to custom, we can put the meter back where it was last time
5265  *  custom was enabled.
5266  *
5267  *  Must be called with the _processor_lock held.
5268  */
5269 void
maybe_note_meter_position()5270 Route::maybe_note_meter_position ()
5271 {
5272 	if (_meter_point != MeterCustom) {
5273 		return;
5274 	}
5275 
5276 	_custom_meter_position_noted = true;
5277 	/* custom meter points range from after trim to before panner/main_outs
5278 	 * this is a limitation by the current processor UI
5279 	 */
5280 	bool seen_trim = false;
5281 	_processor_after_last_custom_meter.reset();
5282 	for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5283 		if ((*i) == _trim) {
5284 			seen_trim = true;
5285 		}
5286 		if ((*i) == _main_outs) {
5287 			_processor_after_last_custom_meter = *i;
5288 			break;
5289 		}
5290 		if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
5291 			if (!seen_trim) {
5292 				_processor_after_last_custom_meter = _trim;
5293 			} else {
5294 				ProcessorList::iterator j = i;
5295 				++j;
5296 				assert(j != _processors.end ()); // main_outs should be before
5297 				_processor_after_last_custom_meter = *j;
5298 			}
5299 			break;
5300 		}
5301 	}
5302 	assert(_processor_after_last_custom_meter.lock());
5303 }
5304 
5305 boost::shared_ptr<Processor>
processor_by_id(PBD::ID id) const5306 Route::processor_by_id (PBD::ID id) const
5307 {
5308 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5309 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5310 		if ((*i)->id() == id) {
5311 			return *i;
5312 		}
5313 	}
5314 
5315 	return boost::shared_ptr<Processor> ();
5316 }
5317 
5318 bool
can_freeze_processor(boost::shared_ptr<Processor> p,bool allow_routing) const5319 Route::can_freeze_processor (boost::shared_ptr<Processor> p, bool allow_routing) const
5320 {
5321 	/* ignore inactive processors and obviously ignore the main
5322 	 * outs since everything has them and we don't care.
5323 	 */
5324 	if (!p->active()) {
5325 		return true;
5326 	}
5327 
5328 	if (p != _main_outs && p->does_routing()) {
5329 		return allow_routing;
5330 	}
5331 
5332 	if (boost::dynamic_pointer_cast<PortInsert>(p)) {
5333 		return false;
5334 	}
5335 
5336 	boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(p);
5337 	if (pi && pi->has_sidechain () && pi->sidechain_input () && pi->sidechain_input ()->connected()) {
5338 		return false;
5339 	}
5340 
5341 	return true;
5342 }
5343 
5344 bool
has_external_redirects() const5345 Route::has_external_redirects () const
5346 {
5347 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5348 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5349 		if (!can_freeze_processor (*i)) {
5350 			return true;
5351 		}
5352 	}
5353 	return false;
5354 }
5355 
5356 boost::shared_ptr<Processor>
the_instrument() const5357 Route::the_instrument () const
5358 {
5359 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5360 	return the_instrument_unlocked ();
5361 }
5362 
5363 boost::shared_ptr<Processor>
the_instrument_unlocked() const5364 Route::the_instrument_unlocked () const
5365 {
5366 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5367 		boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
5368 		if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
5369 			return (*i);
5370 		}
5371 	}
5372 	return boost::shared_ptr<Processor>();
5373 }
5374 
5375 bool
is_track()5376 Route::is_track()
5377 {
5378 	return dynamic_cast<Track*>(this) != 0;
5379 }
5380 
5381 void
non_realtime_locate(samplepos_t pos)5382 Route::non_realtime_locate (samplepos_t pos)
5383 {
5384 	Automatable::non_realtime_locate (pos);
5385 
5386 	if (_pannable) {
5387 		_pannable->non_realtime_locate (pos);
5388 	}
5389 
5390 #if 0 // XXX mayhaps clear delayline here (and at stop?)
5391 	if (_delayline) {
5392 		_delayline->flush ();
5393 	}
5394 #endif
5395 
5396 	{
5397 		//Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5398 		Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5399 
5400 		for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5401 			(*i)->non_realtime_locate (pos);
5402 		}
5403 	}
5404 }
5405 
5406 void
fill_buffers_with_input(BufferSet & bufs,boost::shared_ptr<IO> io,pframes_t nframes)5407 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
5408 {
5409 	size_t n_buffers;
5410 	size_t i;
5411 
5412 	/* MIDI
5413 	 *
5414 	 * We don't currently mix MIDI input together, so we don't need the
5415 	 * complex logic of the audio case.
5416 	 */
5417 
5418 	n_buffers = bufs.count().n_midi ();
5419 
5420 	for (i = 0; i < n_buffers; ++i) {
5421 
5422 		boost::shared_ptr<MidiPort> source_port = io->midi (i);
5423 		MidiBuffer& buf (bufs.get_midi (i));
5424 
5425 		if (source_port) {
5426 			buf.copy (source_port->get_midi_buffer(nframes));
5427 		} else {
5428 			buf.silence (nframes);
5429 		}
5430 	}
5431 
5432 	/* AUDIO */
5433 
5434 	n_buffers = bufs.count().n_audio();
5435 
5436 	size_t n_ports = io->n_ports().n_audio();
5437 	float scaling = 1.0f;
5438 
5439 	if (n_ports > n_buffers) {
5440 		scaling = ((float) n_buffers) / n_ports;
5441 	}
5442 
5443 	for (i = 0; i < n_ports; ++i) {
5444 
5445 		/* if there are more ports than buffers, map them onto buffers
5446 		 * in a round-robin fashion
5447 		 */
5448 
5449 		boost::shared_ptr<AudioPort> source_port = io->audio (i);
5450 		AudioBuffer& buf (bufs.get_audio (i%n_buffers));
5451 
5452 		if (i < n_buffers) {
5453 
5454 			/* first time through just copy a channel into
5455 			   the output buffer.
5456 			*/
5457 
5458 			buf.read_from (source_port->get_audio_buffer (nframes), nframes);
5459 
5460 			if (scaling != 1.0f) {
5461 				buf.apply_gain (scaling, nframes);
5462 			}
5463 
5464 		} else {
5465 
5466 			/* on subsequent times around, merge data from
5467 			 * the port with what is already there
5468 			 */
5469 
5470 			if (scaling != 1.0f) {
5471 				buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
5472 			} else {
5473 				buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
5474 			}
5475 		}
5476 	}
5477 
5478 	/* silence any remaining buffers */
5479 
5480 	for (; i < n_buffers; ++i) {
5481 		AudioBuffer& buf (bufs.get_audio (i));
5482 		buf.silence (nframes);
5483 	}
5484 
5485 	/* establish the initial setup of the buffer set, reflecting what was
5486 	   copied into it. unless, of course, we are the auditioner, in which
5487 	   case nothing was fed into it from the inputs at all.
5488 	*/
5489 
5490 	if (!is_auditioner()) {
5491 		bufs.set_count (io->n_ports());
5492 	}
5493 }
5494 
5495 boost::shared_ptr<AutomationControl>
pan_azimuth_control() const5496 Route::pan_azimuth_control() const
5497 {
5498 #ifdef MIXBUS
5499 	if (_mixbus_send) {
5500 		return _mixbus_send->master_pan_ctrl ();
5501 	}
5502 	return boost::shared_ptr<AutomationControl>();
5503 #else
5504 	if (!_pannable || !panner()) {
5505 		return boost::shared_ptr<AutomationControl>();
5506 	}
5507 	return _pannable->pan_azimuth_control;
5508 #endif
5509 }
5510 
5511 boost::shared_ptr<AutomationControl>
pan_elevation_control() const5512 Route::pan_elevation_control() const
5513 {
5514 	if (Profile->get_mixbus() || !_pannable || !panner()) {
5515 		return boost::shared_ptr<AutomationControl>();
5516 	}
5517 
5518 	set<Evoral::Parameter> c = pannable()->what_can_be_automated ();
5519 
5520 	if (c.find (PanElevationAutomation) != c.end()) {
5521 		return _pannable->pan_elevation_control;
5522 	} else {
5523 		return boost::shared_ptr<AutomationControl>();
5524 	}
5525 }
5526 boost::shared_ptr<AutomationControl>
pan_width_control() const5527 Route::pan_width_control() const
5528 {
5529 #ifdef MIXBUS
5530 	if (mixbus() && _ch_pre) {
5531 		//mono blend
5532 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(_ch_pre->control(Evoral::Parameter(PluginAutomation, 0, 1)));
5533 	}
5534 #endif
5535 	if (Profile->get_mixbus() || !_pannable || !panner()) {
5536 		return boost::shared_ptr<AutomationControl>();
5537 	}
5538 
5539 	set<Evoral::Parameter> c = pannable()->what_can_be_automated ();
5540 
5541 	if (c.find (PanWidthAutomation) != c.end()) {
5542 		return _pannable->pan_width_control;
5543 	} else {
5544 		return boost::shared_ptr<AutomationControl>();
5545 	}
5546 }
5547 boost::shared_ptr<AutomationControl>
pan_frontback_control() const5548 Route::pan_frontback_control() const
5549 {
5550 	if (Profile->get_mixbus() || !_pannable || !panner()) {
5551 		return boost::shared_ptr<AutomationControl>();
5552 	}
5553 
5554 	set<Evoral::Parameter> c = pannable()->what_can_be_automated ();
5555 
5556 	if (c.find (PanFrontBackAutomation) != c.end()) {
5557 		return _pannable->pan_frontback_control;
5558 	} else {
5559 		return boost::shared_ptr<AutomationControl>();
5560 	}
5561 }
5562 boost::shared_ptr<AutomationControl>
pan_lfe_control() const5563 Route::pan_lfe_control() const
5564 {
5565 	if (Profile->get_mixbus() || !_pannable || !panner()) {
5566 		return boost::shared_ptr<AutomationControl>();
5567 	}
5568 
5569 	set<Evoral::Parameter> c = pannable()->what_can_be_automated ();
5570 
5571 	if (c.find (PanLFEAutomation) != c.end()) {
5572 		return _pannable->pan_lfe_control;
5573 	} else {
5574 		return boost::shared_ptr<AutomationControl>();
5575 	}
5576 }
5577 
5578 uint32_t
eq_band_cnt() const5579 Route::eq_band_cnt () const
5580 {
5581 	if (Profile->get_mixbus()) {
5582 #ifdef MIXBUS32C
5583 		if (is_master() || mixbus()) {
5584 			return 3;
5585 		} else {
5586 			return 4;
5587 		}
5588 #else
5589 		return 3;
5590 #endif
5591 	} else {
5592 		/* Ardour has no well-known EQ object */
5593 		return 0;
5594 	}
5595 }
5596 
5597 boost::shared_ptr<AutomationControl>
eq_gain_controllable(uint32_t band) const5598 Route::eq_gain_controllable (uint32_t band) const
5599 {
5600 #ifdef MIXBUS
5601 	boost::shared_ptr<PluginInsert> eq = _ch_eq;
5602 
5603 	if (!eq) {
5604 		return boost::shared_ptr<AutomationControl>();
5605 	}
5606 
5607 	uint32_t port_number;
5608 	if (is_master() || mixbus()) {
5609 		switch (band) {
5610 			case 0: port_number = 4; break;
5611 			case 1: port_number = 3; break;
5612 			case 2: port_number = 2; break;
5613 			default:
5614 				return boost::shared_ptr<AutomationControl>();
5615 		}
5616 	} else {
5617 #ifdef MIXBUS32C
5618 		switch (band) {
5619 			case 0: port_number = 14; break;
5620 			case 1: port_number = 12; break;
5621 			case 2: port_number = 10; break;
5622 			case 3: port_number =  8; break;
5623 			default:
5624 				return boost::shared_ptr<AutomationControl>();
5625 		}
5626 #else
5627 		switch (band) {
5628 			case 0: port_number = 8; break;
5629 			case 1: port_number = 6; break;
5630 			case 2: port_number = 4; break;
5631 			default:
5632 				return boost::shared_ptr<AutomationControl>();
5633 		}
5634 #endif
5635 	}
5636 
5637 	return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5638 #else
5639 	return boost::shared_ptr<AutomationControl>();
5640 #endif
5641 }
5642 boost::shared_ptr<AutomationControl>
eq_freq_controllable(uint32_t band) const5643 Route::eq_freq_controllable (uint32_t band) const
5644 {
5645 #ifdef MIXBUS
5646 	if (mixbus() || is_master()) {
5647 		/* no frequency controls for mixbusses or master */
5648 		return boost::shared_ptr<AutomationControl>();
5649 	}
5650 
5651 	boost::shared_ptr<PluginInsert> eq = _ch_eq;
5652 
5653 	if (!eq) {
5654 		return boost::shared_ptr<AutomationControl>();
5655 	}
5656 
5657 	uint32_t port_number;
5658 #ifdef MIXBUS32C
5659 	switch (band) {
5660 		case 0: port_number = 13; break; // lo
5661 		case 1: port_number = 11; break; // lo mid
5662 		case 2: port_number = 9; break; // hi mid
5663 		case 3: port_number = 7; break; // hi
5664 		default:
5665 			return boost::shared_ptr<AutomationControl>();
5666 	}
5667 #else
5668 	switch (band) {
5669 		case 0: port_number = 7; break;
5670 		case 1: port_number = 5; break;
5671 		case 2: port_number = 3; break;
5672 		default:
5673 			return boost::shared_ptr<AutomationControl>();
5674 	}
5675 #endif
5676 
5677 	return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5678 #else
5679 	return boost::shared_ptr<AutomationControl>();
5680 #endif
5681 }
5682 
5683 boost::shared_ptr<AutomationControl>
eq_q_controllable(uint32_t band) const5684 Route::eq_q_controllable (uint32_t band) const
5685 {
5686 	return boost::shared_ptr<AutomationControl>();
5687 }
5688 
5689 boost::shared_ptr<AutomationControl>
eq_shape_controllable(uint32_t band) const5690 Route::eq_shape_controllable (uint32_t band) const
5691 {
5692 #ifdef MIXBUS32C
5693 	if (is_master() || mixbus() || !eq) {
5694 		return boost::shared_ptr<AutomationControl>();
5695 	}
5696 	switch (band) {
5697 		case 0:
5698 			return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4))); // lo bell
5699 			break;
5700 		case 3:
5701 			return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3))); // hi bell
5702 			break;
5703 		default:
5704 			break;
5705 	}
5706 #endif
5707 	return boost::shared_ptr<AutomationControl>();
5708 }
5709 
5710 boost::shared_ptr<AutomationControl>
eq_enable_controllable() const5711 Route::eq_enable_controllable () const
5712 {
5713 #ifdef MIXBUS
5714 	boost::shared_ptr<PluginInsert> eq = _ch_eq;
5715 
5716 	if (!eq) {
5717 		return boost::shared_ptr<AutomationControl>();
5718 	}
5719 
5720 	return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5721 #else
5722 	return boost::shared_ptr<AutomationControl>();
5723 #endif
5724 }
5725 
5726 boost::shared_ptr<AutomationControl>
filter_freq_controllable(bool hpf) const5727 Route::filter_freq_controllable (bool hpf) const
5728 {
5729 #ifdef MIXBUS
5730 	boost::shared_ptr<PluginInsert> eq = _ch_eq;
5731 
5732 	if (is_master() || mixbus() || !eq) {
5733 		return boost::shared_ptr<AutomationControl>();
5734 	}
5735 	if (hpf) {
5736 #ifdef MIXBUS32C
5737 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5))); // HPF freq
5738 #else
5739 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5740 #endif
5741 	} else {
5742 #ifdef MIXBUS32C
5743 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 6))); // LPF freq
5744 #else
5745 		return boost::shared_ptr<AutomationControl>();
5746 #endif
5747 	}
5748 
5749 #else
5750 	return boost::shared_ptr<AutomationControl>();
5751 #endif
5752 }
5753 
5754 boost::shared_ptr<AutomationControl>
filter_slope_controllable(bool) const5755 Route::filter_slope_controllable (bool) const
5756 {
5757 	return boost::shared_ptr<AutomationControl>();
5758 }
5759 
5760 boost::shared_ptr<AutomationControl>
filter_enable_controllable(bool) const5761 Route::filter_enable_controllable (bool) const
5762 {
5763 #ifdef MIXBUS32C
5764 	boost::shared_ptr<PluginInsert> eq = _ch_eq;
5765 
5766 	if (is_master() || mixbus() || !eq) {
5767 		return boost::shared_ptr<AutomationControl>();
5768 	}
5769 
5770 	return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5771 #else
5772 	return boost::shared_ptr<AutomationControl>();
5773 #endif
5774 }
5775 
5776 boost::shared_ptr<AutomationControl>
tape_drive_controllable() const5777 Route::tape_drive_controllable () const
5778 {
5779 #ifdef MIXBUS
5780 	if (_ch_pre) {
5781 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_pre->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 0)));
5782 	}
5783 #endif
5784 	return boost::shared_ptr<AutomationControl>();
5785 }
5786 
5787 boost::shared_ptr<ReadOnlyControl>
tape_drive_mtr_controllable() const5788 Route::tape_drive_mtr_controllable () const
5789 {
5790 #ifdef MIXBUS
5791 	if (_ch_pre) {
5792 		return _ch_pre->control_output (is_master() ? 1 : 2);
5793 	}
5794 #endif
5795 	return boost::shared_ptr<ReadOnlyControl>();
5796 }
5797 
5798 boost::shared_ptr<ReadOnlyControl>
master_correlation_mtr_controllable(bool mm) const5799 Route::master_correlation_mtr_controllable (bool mm) const
5800 {
5801 #ifdef MIXBUS
5802 	if (is_master() && _ch_post) {
5803 		return _ch_post->control_output (mm ? 4 : 3);
5804 	}
5805 #endif
5806 	return boost::shared_ptr<ReadOnlyControl>();
5807 }
5808 
5809 boost::shared_ptr<AutomationControl>
master_limiter_enable_controllable() const5810 Route::master_limiter_enable_controllable () const
5811 {
5812 #ifdef MIXBUS
5813 	if (is_master() && _ch_post) {
5814 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_post->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5815 	}
5816 #endif
5817 	return boost::shared_ptr<AutomationControl>();
5818 }
5819 
5820 boost::shared_ptr<ReadOnlyControl>
master_limiter_mtr_controllable() const5821 Route::master_limiter_mtr_controllable () const
5822 {
5823 #ifdef MIXBUS
5824 	if (is_master() && _ch_post) {
5825 		return _ch_post->control_output (2);
5826 	}
5827 #endif
5828 	return boost::shared_ptr<ReadOnlyControl>();
5829 }
5830 
5831 boost::shared_ptr<ReadOnlyControl>
master_k_mtr_controllable() const5832 Route::master_k_mtr_controllable () const
5833 {
5834 #ifdef MIXBUS
5835 	if (is_master() && _ch_post) {
5836 		return _ch_post->control_output (5);
5837 	}
5838 #endif
5839 	return boost::shared_ptr<ReadOnlyControl>();
5840 }
5841 
5842 string
eq_band_name(uint32_t band) const5843 Route::eq_band_name (uint32_t band) const
5844 {
5845 #ifdef MIXBUS32C
5846 	if (is_master() || mixbus()) {
5847 #endif
5848 	if (Profile->get_mixbus()) {
5849 		switch (band) {
5850 			case 0: return _("lo");
5851 			case 1: return _("mid");
5852 			case 2: return _("hi");
5853 			default: return string();
5854 		}
5855 	} else {
5856 		return string ();
5857 	}
5858 #ifdef MIXBUS32C
5859 	} else {
5860 		switch (band) {
5861 			case 0: return _("lo");
5862 			case 1: return _("lm");
5863 			case 2: return _("hm");
5864 			case 3: return _("hi");
5865 			default: return string();
5866 		}
5867 	}
5868 #endif
5869 }
5870 
5871 boost::shared_ptr<AutomationControl>
comp_enable_controllable() const5872 Route::comp_enable_controllable () const
5873 {
5874 #ifdef MIXBUS
5875 	if (_ch_comp) {
5876 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5877 	}
5878 #endif
5879 	return boost::shared_ptr<AutomationControl>();
5880 }
5881 boost::shared_ptr<AutomationControl>
comp_threshold_controllable() const5882 Route::comp_threshold_controllable () const
5883 {
5884 #ifdef MIXBUS
5885 	if (_ch_comp) {
5886 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5887 	}
5888 #endif
5889 	return boost::shared_ptr<AutomationControl>();
5890 }
5891 boost::shared_ptr<AutomationControl>
comp_speed_controllable() const5892 Route::comp_speed_controllable () const
5893 {
5894 #ifdef MIXBUS
5895 	if (_ch_comp) {
5896 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3)));
5897 	}
5898 #endif
5899 	return boost::shared_ptr<AutomationControl>();
5900 }
5901 boost::shared_ptr<AutomationControl>
comp_mode_controllable() const5902 Route::comp_mode_controllable () const
5903 {
5904 #ifdef MIXBUS
5905 	if (_ch_comp) {
5906 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5907 	}
5908 #endif
5909 	return boost::shared_ptr<AutomationControl>();
5910 }
5911 boost::shared_ptr<AutomationControl>
comp_makeup_controllable() const5912 Route::comp_makeup_controllable () const
5913 {
5914 #ifdef MIXBUS
5915 	if (_ch_comp) {
5916 		return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5)));
5917 	}
5918 #endif
5919 	return boost::shared_ptr<AutomationControl>();
5920 }
5921 boost::shared_ptr<ReadOnlyControl>
comp_redux_controllable() const5922 Route::comp_redux_controllable () const
5923 {
5924 #ifdef MIXBUS
5925 	if (_ch_comp) {
5926 		return _ch_comp->control_output (6);
5927 	}
5928 #endif
5929 	return boost::shared_ptr<ReadOnlyControl>();
5930 }
5931 
5932 string
comp_mode_name(uint32_t mode) const5933 Route::comp_mode_name (uint32_t mode) const
5934 {
5935 #ifdef MIXBUS
5936 	switch (mode) {
5937 	case 0:
5938 		return _("Leveler");
5939 	case 1:
5940 		return _("Compressor");
5941 	case 2:
5942 		return _("Limiter");
5943 	case 3:
5944 		return mixbus() ? _("Sidechain") : _("Limiter");
5945 	}
5946 
5947 	return _("???");
5948 #else
5949 	return _("???");
5950 #endif
5951 }
5952 
5953 string
comp_speed_name(uint32_t mode) const5954 Route::comp_speed_name (uint32_t mode) const
5955 {
5956 #ifdef MIXBUS
5957 	switch (mode) {
5958 	case 0:
5959 		return _("Attk");
5960 	case 1:
5961 		return _("Ratio");
5962 	case 2:
5963 	case 3:
5964 		return _("Rels");
5965 	}
5966 	return _("???");
5967 #else
5968 	return _("???");
5969 #endif
5970 }
5971 
5972 boost::shared_ptr<AutomationControl>
send_pan_azimuth_controllable(uint32_t n) const5973 Route::send_pan_azimuth_controllable (uint32_t n) const
5974 {
5975 #ifdef  MIXBUS
5976 	if (_mixbus_send) {
5977 		if (n < _mixbus_send->n_busses ()) {
5978 			return _mixbus_send->send_pan_ctrl (n + 1);
5979 		}
5980 	}
5981 #endif
5982 	return boost::shared_ptr<AutomationControl>();
5983 }
5984 
5985 boost::shared_ptr<AutomationControl>
send_level_controllable(uint32_t n) const5986 Route::send_level_controllable (uint32_t n) const
5987 {
5988 #ifdef  MIXBUS
5989 	if (_mixbus_send) {
5990 		if (n < _mixbus_send->n_busses ()) {
5991 			return _mixbus_send->send_gain_ctrl (n + 1);
5992 		}
5993 		n -= _mixbus_send->n_busses ();
5994 	}
5995 #endif
5996 	boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(nth_send (n));
5997 	if (s) {
5998 		return s->gain_control ();
5999 	}
6000 	return boost::shared_ptr<AutomationControl>();
6001 }
6002 
6003 boost::shared_ptr<AutomationControl>
send_enable_controllable(uint32_t n) const6004 Route::send_enable_controllable (uint32_t n) const
6005 {
6006 #ifdef  MIXBUS
6007 	if (_mixbus_send) {
6008 		if (n < _mixbus_send->n_busses ()) {
6009 			return _mixbus_send->send_enable_ctrl (n + 1);
6010 		}
6011 	}
6012 #endif
6013 	/* although Ardour sends have enable/disable as part of the Processor
6014 	 * API, it is not exposed as a controllable.
6015 	 *
6016 	 * XXX: we should fix this (make it click-free, automatable enable-control)
6017 	 */
6018 	return boost::shared_ptr<AutomationControl>();
6019 }
6020 
6021 boost::shared_ptr<AutomationControl>
send_pan_azimuth_enable_controllable(uint32_t n) const6022 Route::send_pan_azimuth_enable_controllable (uint32_t n) const
6023 {
6024 #ifdef  MIXBUS
6025 	if (_mixbus_send) {
6026 		if (n < _mixbus_send->n_busses ()) {
6027 			return _mixbus_send->send_pan_enable_ctrl (n + 1);
6028 		}
6029 	}
6030 #endif
6031 	return boost::shared_ptr<AutomationControl>();
6032 }
6033 
6034 string
send_name(uint32_t n) const6035 Route::send_name (uint32_t n) const
6036 {
6037 #ifdef  MIXBUS
6038 	if (_mixbus_send) {
6039 		if (n < _mixbus_send->n_busses ()) {
6040 			return _session.get_mixbus (n)->name();
6041 		}
6042 		n -= _mixbus_send->n_busses ();
6043 	}
6044 #endif
6045 	boost::shared_ptr<Processor> p = nth_send (n);
6046 	if (p) {
6047 		return p->name();
6048 	}
6049 	return string();
6050 }
6051 
6052 boost::shared_ptr<AutomationControl>
master_send_enable_controllable() const6053 Route::master_send_enable_controllable () const
6054 {
6055 #ifdef  MIXBUS
6056 	if (is_master() || is_monitor() || is_auditioner()) {
6057 		return boost::shared_ptr<AutomationControl>();
6058 	}
6059 
6060 	if (_mixbus_send) {
6061 		return _mixbus_send->master_send_enable_ctrl ();
6062 	}
6063 
6064 #endif
6065 	return boost::shared_ptr<AutomationControl>();
6066 }
6067 
6068 bool
slaved() const6069 Route::slaved () const
6070 {
6071 	if (!_gain_control) {
6072 		return false;
6073 	}
6074 	/* just test one particular control, not all of them */
6075 	return _gain_control->slaved ();
6076 }
6077 
6078 bool
slaved_to(boost::shared_ptr<VCA> vca) const6079 Route::slaved_to (boost::shared_ptr<VCA> vca) const
6080 {
6081 	if (!vca || !_gain_control) {
6082 		return false;
6083 	}
6084 
6085 	/* just test one particular control, not all of them */
6086 
6087 	return _gain_control->slaved_to (vca->gain_control());
6088 }
6089 
6090 bool
muted_by_others_soloing() const6091 Route::muted_by_others_soloing () const
6092 {
6093 	if (!can_be_muted_by_others ()) {
6094 		return false;
6095 	}
6096 
6097 	return  _session.soloing() && !_solo_control->soloed() && !_solo_isolate_control->solo_isolated();
6098 }
6099 
6100 void
clear_all_solo_state()6101 Route::clear_all_solo_state ()
6102 {
6103 	_solo_control->clear_all_solo_state ();
6104 }
6105 
6106 boost::shared_ptr<AutomationControl>
automation_control_recurse(PBD::ID const & id) const6107 Route::automation_control_recurse (PBD::ID const & id) const
6108 {
6109 	boost::shared_ptr<AutomationControl> ac = Automatable::automation_control (id);
6110 
6111 	if (ac) {
6112 		return ac;
6113 	}
6114 
6115 	if  (_pannable) {
6116 		if ((ac = _pannable->automation_control (id))) {
6117 			return ac;
6118 		}
6119 	}
6120 
6121 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
6122 
6123 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
6124 		if ((ac = (*i)->automation_control (id))) {
6125 			return ac;
6126 		}
6127 	}
6128 
6129 	return boost::shared_ptr<AutomationControl> ();
6130 }
6131 
6132 SlavableControlList
slavables() const6133 Route::slavables () const
6134 {
6135 	SlavableControlList rv;
6136 	rv.push_back (_gain_control);
6137 	rv.push_back (_mute_control);
6138 	rv.push_back (_solo_control);
6139 	return rv;
6140 }
6141 
6142 void
set_meter_type(MeterType t)6143 Route::set_meter_type (MeterType t)
6144 {
6145 	_meter->set_meter_type (t);
6146 	_session.set_dirty ();
6147 }
6148 
6149 MeterType
meter_type() const6150 Route::meter_type () const
6151 {
6152 	return _meter->meter_type ();
6153 }
6154 
6155 void
set_disk_io_point(DiskIOPoint diop)6156 Route::set_disk_io_point (DiskIOPoint diop)
6157 {
6158 	bool display = false;
6159 
6160 	switch (diop) {
6161 	case DiskIOCustom:
6162 		display = true;
6163 		break;
6164 	default:
6165 		display = false;
6166 	}
6167 
6168 	if (_disk_writer) {
6169 		_disk_writer->set_display_to_user (display);
6170 	}
6171 
6172 	if (_disk_reader) {
6173 		_disk_reader->set_display_to_user (display);
6174 	}
6175 
6176 	const bool changed = (diop != _disk_io_point);
6177 
6178 	_disk_io_point = diop;
6179 
6180 	if (_initial_io_setup) {
6181 		return;
6182 	}
6183 
6184 	if (changed) {
6185 		Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
6186 		configure_processors (0);
6187 	}
6188 
6189 	processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
6190 }
6191 
6192 void
set_loop(Location * l)6193 Route::set_loop (Location* l)
6194 {
6195 	_loop_location = l;
6196 	Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
6197 	for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
6198 		(*i)->set_loop (l);
6199 	}
6200 }
6201 
6202 static inline MonitorState
operator |(const MonitorState & a,const MonitorState & b)6203 operator| (const MonitorState& a, const MonitorState& b) {
6204   return static_cast<MonitorState> (static_cast <int>(a) | static_cast<int> (b));
6205 }
6206 
6207 MonitorState
monitoring_state() const6208 Route::monitoring_state () const
6209 {
6210 	if (!_disk_reader || !_monitoring_control) {
6211 		return MonitoringInput;
6212 	}
6213 
6214 	/* Explicit requests */
6215 	MonitorChoice m (_monitoring_control->monitoring_choice());
6216 
6217 	if (m != MonitorAuto) {
6218 
6219 		MonitorState ms = MonitoringSilence;
6220 
6221 		if (m & MonitorInput) {
6222 			ms = MonitorState (ms | MonitoringInput);
6223 		}
6224 
6225 		if (m & MonitorDisk) {
6226 			ms = MonitorState (ms | MonitoringDisk);
6227 		}
6228 
6229 		return ms;
6230 	}
6231 
6232 	switch (_session.config.get_session_monitoring ()) {
6233 		case MonitorDisk:
6234 			return MonitoringDisk;
6235 			break;
6236 		case MonitorInput:
6237 			return MonitoringInput;
6238 			break;
6239 		case MonitorCue:
6240 			return MonitoringCue;
6241 		default:
6242 			/* MonitorAuto */
6243 			break;
6244 	}
6245 
6246 	/* This is an implementation of the truth table in doc/monitor_modes.pdf;
6247 	 * I don't think it's ever going to be too pretty too look at.
6248 	 */
6249 
6250 	bool const roll        = _session.transport_rolling ();
6251 	bool const auto_input  = _session.config.get_auto_input ();
6252 	bool const track_rec   = _disk_writer->record_enabled ();
6253 	bool session_rec;
6254 
6255 	bool const auto_input_does_talkback = Config->get_auto_input_does_talkback ();
6256 
6257 	/* I suspect that just use actively_recording() is good enough all the
6258 	 * time, but just to keep the semantics the same as they were before
6259 	 * sept 26th 2012, we differentiate between the cases where punch is
6260 	 * enabled and those where it is not.
6261 	 *
6262 	 * rg: sept 30 2017: Above is not the case: punch-in/out location is
6263 	 * global session playhead position.
6264 	 * When this method is called from process_output_buffers() we need
6265 	 * to use delay-compensated route's process-position.
6266 	 *
6267 	 * NB. Disk reader/writer may also be offset by a same amount of time.
6268 	 *
6269 	 * Also keep in mind that _session.transport_rolling() is false during
6270 	 * pre-roll but the disk already produces output.
6271 	 *
6272 	 * TODO: FIXME
6273 	 */
6274 
6275 	if (_session.config.get_punch_in() || _session.config.get_punch_out()) {
6276 		session_rec = _session.actively_recording ();
6277 	} else {
6278 		session_rec = _session.get_record_enabled();
6279 	}
6280 
6281 	if (track_rec) {
6282 
6283 		if (!session_rec && roll && auto_input) {
6284 			return MonitoringDisk | get_input_monitoring_state (false, false);
6285 		} else {
6286 			/* recording */
6287 			return get_input_monitoring_state (true, false);
6288 		}
6289 
6290 	} else {
6291 
6292 		if (auto_input_does_talkback) {
6293 
6294 			if (!roll && auto_input) {
6295 				return get_input_monitoring_state (false, true);
6296 			} else {
6297 				return MonitoringDisk | get_input_monitoring_state (false, false);
6298 			}
6299 
6300 		} else {
6301 			/* tape-machine-mode */
6302 			return MonitoringDisk | get_input_monitoring_state (false, false);
6303 		}
6304 	}
6305 
6306 	abort(); /* NOTREACHED */
6307 	return MonitoringSilence;
6308 }
6309 
6310