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