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