Merge branch 'master' into cairocanvas
[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 <fstream>
26 #include <cassert>
27 #include <algorithm>
28
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
38 #include "ardour/amp.h"
39 #include "ardour/audio_buffer.h"
40 #include "ardour/audio_port.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/buffer.h"
43 #include "ardour/buffer_set.h"
44 #include "ardour/capturing_processor.h"
45 #include "ardour/debug.h"
46 #include "ardour/delivery.h"
47 #include "ardour/internal_return.h"
48 #include "ardour/internal_send.h"
49 #include "ardour/meter.h"
50 #include "ardour/midi_buffer.h"
51 #include "ardour/midi_port.h"
52 #include "ardour/monitor_processor.h"
53 #include "ardour/pannable.h"
54 #include "ardour/panner_shell.h"
55 #include "ardour/plugin_insert.h"
56 #include "ardour/port.h"
57 #include "ardour/port_insert.h"
58 #include "ardour/processor.h"
59 #include "ardour/route.h"
60 #include "ardour/route_group.h"
61 #include "ardour/send.h"
62 #include "ardour/session.h"
63 #include "ardour/unknown_processor.h"
64 #include "ardour/utils.h"
65
66 #include "i18n.h"
67
68 using namespace std;
69 using namespace ARDOUR;
70 using namespace PBD;
71
72 PBD::Signal0<void> Route::SyncOrderKeys;
73 PBD::Signal0<void> Route::RemoteControlIDChange;
74
75 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
76         : SessionObject (sess, name)
77         , Automatable (sess)
78         , GraphNode (sess._process_graph)
79         , _active (true)
80         , _signal_latency (0)
81         , _initial_delay (0)
82         , _roll_delay (0)
83         , _flags (flg)
84         , _pending_declick (true)
85         , _meter_point (MeterPostFader)
86         , _meter_type (MeterPeak)
87         , _self_solo (false)
88         , _soloed_by_others_upstream (0)
89         , _soloed_by_others_downstream (0)
90         , _solo_isolated (0)
91         , _denormal_protection (false)
92         , _recordable (true)
93         , _silent (false)
94         , _declickable (false)
95         , _mute_master (new MuteMaster (sess, name))
96         , _have_internal_generator (false)
97         , _solo_safe (false)
98         , _default_type (default_type)
99         , _order_key (0)
100         , _has_order_key (false)
101         , _remote_control_id (0)
102         , _in_configure_processors (false)
103         , _initial_io_setup (false)
104         , _custom_meter_position_noted (false)
105         , _last_custom_meter_was_at_end (false)
106 {
107         if (is_master()) {
108                 _meter_type = MeterK20;
109         }
110         processor_max_streams.reset();
111 }
112
113 int
114 Route::init ()
115 {
116         /* add standard controls */
117
118         _solo_control.reset (new SoloControllable (X_("solo"), shared_from_this ()));
119         _mute_control.reset (new MuteControllable (X_("mute"), shared_from_this ()));
120
121         _solo_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
122         _mute_control->set_flags (Controllable::Flag (_mute_control->flags() | Controllable::Toggle));
123
124         add_control (_solo_control);
125         add_control (_mute_control);
126
127         /* panning */
128
129         if (!(_flags & Route::MonitorOut)) {
130                 _pannable.reset (new Pannable (_session));
131         }
132
133         /* input and output objects */
134
135         _input.reset (new IO (_session, _name, IO::Input, _default_type));
136         _output.reset (new IO (_session, _name, IO::Output, _default_type));
137
138         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
139         _input->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::input_port_count_changing, this, _1));
140
141         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
142         _output->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::output_port_count_changing, this, _1));
143
144         /* add amp processor  */
145
146         _amp.reset (new Amp (_session));
147         add_processor (_amp, PostFader);
148
149         /* create standard processors: meter, main outs, monitor out;
150            they will be added to _processors by setup_invisible_processors ()
151         */
152
153         _meter.reset (new PeakMeter (_session, _name));
154         _meter->set_owner (this);
155         _meter->set_display_to_user (false);
156         _meter->activate ();
157
158         _main_outs.reset (new Delivery (_session, _output, _pannable, _mute_master, _name, Delivery::Main));
159         _main_outs->activate ();
160
161         if (is_monitor()) {
162                 /* where we listen to tracks */
163                 _intreturn.reset (new InternalReturn (_session));
164                 _intreturn->activate ();
165
166                 /* the thing that provides proper control over a control/monitor/listen bus
167                    (such as per-channel cut, dim, solo, invert, etc).
168                 */
169                 _monitor_control.reset (new MonitorProcessor (_session));
170                 _monitor_control->activate ();
171         }
172
173         if (is_master() || is_monitor() || is_auditioner()) {
174                 _mute_master->set_solo_ignore (true);
175         }
176
177         /* now that we have _meter, its safe to connect to this */
178
179         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
180
181         {
182                 /* run a configure so that the invisible processors get set up */
183                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
184                 configure_processors (0);
185         }
186
187         return 0;
188 }
189
190 Route::~Route ()
191 {
192         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
193
194         /* do this early so that we don't get incoming signals as we are going through destruction
195          */
196
197         drop_connections ();
198
199         /* don't use clear_processors here, as it depends on the session which may
200            be half-destroyed by now
201         */
202
203         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
204         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
205                 (*i)->drop_references ();
206         }
207
208         _processors.clear ();
209 }
210
211 void
212 Route::set_remote_control_id (uint32_t id, bool notify_class_listeners)
213 {
214         if (Config->get_remote_model() != UserOrdered) {
215                 return;
216         }
217
218         set_remote_control_id_internal (id, notify_class_listeners);
219 }
220
221 void
222 Route::set_remote_control_id_internal (uint32_t id, bool notify_class_listeners)
223 {
224         /* force IDs for master/monitor busses and prevent 
225            any other route from accidentally getting these IDs
226            (i.e. legacy sessions)
227         */
228
229         if (is_master() && id != MasterBusRemoteControlID) {
230                 id = MasterBusRemoteControlID;
231         }
232
233         if (is_monitor() && id != MonitorBusRemoteControlID) {
234                 id = MonitorBusRemoteControlID;
235         }
236
237         if (id < 1) {
238                 return;
239         }
240
241         /* don't allow it to collide */
242
243         if (!is_master () && !is_monitor() && 
244             (id == MasterBusRemoteControlID || id == MonitorBusRemoteControlID)) {
245                 id += MonitorBusRemoteControlID;
246         }
247
248         if (id != remote_control_id()) {
249                 _remote_control_id = id;
250                 RemoteControlIDChanged ();
251
252                 if (notify_class_listeners) {
253                         RemoteControlIDChange ();
254                 }
255         }
256 }
257
258 uint32_t
259 Route::remote_control_id() const
260 {
261         if (is_master()) {
262                 return MasterBusRemoteControlID;
263         } 
264
265         if (is_monitor()) {
266                 return MonitorBusRemoteControlID;
267         }
268
269         return _remote_control_id;
270 }
271
272 bool
273 Route::has_order_key () const
274 {
275         return _has_order_key;
276 }
277
278 uint32_t
279 Route::order_key () const
280 {
281         return _order_key;
282 }
283
284 void
285 Route::set_remote_control_id_explicit (uint32_t rid)
286 {
287         if (is_master() || is_monitor() || is_auditioner()) {
288                 /* hard-coded remote IDs, or no remote ID */
289                 return;
290         }
291
292         if (_remote_control_id != rid) {
293                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1: set edit-based RID to %2\n", name(), rid));
294                 _remote_control_id = rid;
295                 RemoteControlIDChanged (); /* EMIT SIGNAL (per-route) */
296         }
297
298         /* don't emit the class-level RID signal RemoteControlIDChange here,
299            leave that to the entity that changed the order key, so that we
300            don't get lots of emissions for no good reasons (e.g. when changing
301            all route order keys).
302
303            See Session::sync_remote_id_from_order_keys() for the (primary|only)
304            spot where that is emitted.
305         */
306 }
307
308 void
309 Route::set_order_key (uint32_t n)
310 {
311         _has_order_key = true;
312
313         if (_order_key == n) {
314                 return;
315         }
316
317         _order_key = n;
318
319         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 order key set to %2\n",
320                                                        name(), order_key ()));
321
322         _session.set_dirty ();
323 }
324
325 string
326 Route::ensure_track_or_route_name(string name, Session &session)
327 {
328         string newname = name;
329
330         while (!session.io_name_is_legal (newname)) {
331                 newname = bump_name_once (newname, '.');
332         }
333
334         return newname;
335 }
336
337
338 void
339 Route::inc_gain (gain_t fraction, void *src)
340 {
341         _amp->inc_gain (fraction, src);
342 }
343
344 void
345 Route::set_gain (gain_t val, void *src)
346 {
347         if (src != 0 && _route_group && src != _route_group && _route_group->is_active() && _route_group->is_gain()) {
348
349                 if (_route_group->is_relative()) {
350
351                         gain_t usable_gain = _amp->gain();
352                         if (usable_gain < 0.000001f) {
353                                 usable_gain = 0.000001f;
354                         }
355
356                         gain_t delta = val;
357                         if (delta < 0.000001f) {
358                                 delta = 0.000001f;
359                         }
360
361                         delta -= usable_gain;
362
363                         if (delta == 0.0f)
364                                 return;
365
366                         gain_t factor = delta / usable_gain;
367
368                         if (factor > 0.0f) {
369                                 factor = _route_group->get_max_factor(factor);
370                                 if (factor == 0.0f) {
371                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
372                                         return;
373                                 }
374                         } else {
375                                 factor = _route_group->get_min_factor(factor);
376                                 if (factor == 0.0f) {
377                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
378                                         return;
379                                 }
380                         }
381
382                         _route_group->foreach_route (boost::bind (&Route::inc_gain, _1, factor, _route_group));
383
384                 } else {
385
386                         _route_group->foreach_route (boost::bind (&Route::set_gain, _1, val, _route_group));
387                 }
388
389                 return;
390         }
391
392         if (val == _amp->gain()) {
393                 return;
394         }
395
396         _amp->set_gain (val, src);
397 }
398
399 void
400 Route::maybe_declick (BufferSet&, framecnt_t, int)
401 {
402         /* this is the "bus" implementation and they never declick.
403          */
404         return;
405 }
406
407 /** Process this route for one (sub) cycle (process thread)
408  *
409  * @param bufs Scratch buffers to use for the signal path
410  * @param start_frame Initial transport frame
411  * @param end_frame Final transport frame
412  * @param nframes Number of frames to output (to ports)
413  *
414  * Note that (end_frame - start_frame) may not be equal to nframes when the
415  * transport speed isn't 1.0 (eg varispeed).
416  */
417 void
418 Route::process_output_buffers (BufferSet& bufs,
419                                framepos_t start_frame, framepos_t end_frame, pframes_t nframes,
420                                int declick, bool gain_automation_ok)
421 {
422         /* figure out if we're going to use gain automation */
423         if (gain_automation_ok) {
424                 _amp->set_gain_automation_buffer (_session.gain_automation_buffer ());
425                 _amp->setup_gain_automation (start_frame, end_frame, nframes);
426         } else {
427                 _amp->apply_gain_automation (false);
428         }
429
430         /* Tell main outs what to do about monitoring.  We do this so that
431            on a transition between monitoring states we get a de-clicking gain
432            change in the _main_outs delivery.
433         */
434
435         _main_outs->no_outs_cuz_we_no_monitor (monitoring_state () == MonitoringSilence);
436
437         /* -------------------------------------------------------------------------------------------
438            GLOBAL DECLICK (for transport changes etc.)
439            ----------------------------------------------------------------------------------------- */
440
441         maybe_declick (bufs, nframes, declick);
442         _pending_declick = 0;
443
444         /* -------------------------------------------------------------------------------------------
445            DENORMAL CONTROL/PHASE INVERT
446            ----------------------------------------------------------------------------------------- */
447
448         if (_phase_invert.any ()) {
449
450                 int chn = 0;
451
452                 if (_denormal_protection || Config->get_denormal_protection()) {
453
454                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
455                                 Sample* const sp = i->data();
456
457                                 if (_phase_invert[chn]) {
458                                         for (pframes_t nx = 0; nx < nframes; ++nx) {
459                                                 sp[nx]  = -sp[nx];
460                                                 sp[nx] += 1.0e-27f;
461                                         }
462                                 } else {
463                                         for (pframes_t nx = 0; nx < nframes; ++nx) {
464                                                 sp[nx] += 1.0e-27f;
465                                         }
466                                 }
467                         }
468
469                 } else {
470
471                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
472                                 Sample* const sp = i->data();
473
474                                 if (_phase_invert[chn]) {
475                                         for (pframes_t nx = 0; nx < nframes; ++nx) {
476                                                 sp[nx] = -sp[nx];
477                                         }
478                                 }
479                         }
480                 }
481
482         } else {
483
484                 if (_denormal_protection || Config->get_denormal_protection()) {
485
486                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
487                                 Sample* const sp = i->data();
488                                 for (pframes_t nx = 0; nx < nframes; ++nx) {
489                                         sp[nx] += 1.0e-27f;
490                                 }
491                         }
492
493                 }
494         }
495
496         /* -------------------------------------------------------------------------------------------
497            and go ....
498            ----------------------------------------------------------------------------------------- */
499
500         /* set this to be true if the meter will already have been ::run() earlier */
501         bool const meter_already_run = metering_state() == MeteringInput;
502
503         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
504
505                 if (meter_already_run && boost::dynamic_pointer_cast<PeakMeter> (*i)) {
506                         /* don't ::run() the meter, otherwise it will have its previous peak corrupted */
507                         continue;
508                 }
509
510 #ifndef NDEBUG
511                 /* if it has any inputs, make sure they match */
512                 if (boost::dynamic_pointer_cast<UnknownProcessor> (*i) == 0 && (*i)->input_streams() != ChanCount::ZERO) {
513                         if (bufs.count() != (*i)->input_streams()) {
514                                 DEBUG_TRACE (
515                                         DEBUG::Processors, string_compose (
516                                                 "input port mismatch %1 bufs = %2 input for %3 = %4\n",
517                                                 _name, bufs.count(), (*i)->name(), (*i)->input_streams()
518                                                 )
519                                         );
520                         }
521                 }
522 #endif
523
524                 /* should we NOT run plugins here if the route is inactive?
525                    do we catch route != active somewhere higher?
526                 */
527
528                 (*i)->run (bufs, start_frame, end_frame, nframes, *i != _processors.back());
529                 bufs.set_count ((*i)->output_streams());
530         }
531 }
532
533 ChanCount
534 Route::n_process_buffers ()
535 {
536         return max (_input->n_ports(), processor_max_streams);
537 }
538
539 void
540 Route::monitor_run (framepos_t start_frame, framepos_t end_frame, pframes_t nframes, int declick)
541 {
542         assert (is_monitor());
543         BufferSet& bufs (_session.get_route_buffers (n_process_buffers()));
544         passthru (bufs, start_frame, end_frame, nframes, declick);
545 }
546
547 void
548 Route::passthru (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame, pframes_t nframes, int declick)
549 {
550         _silent = false;
551
552         if (is_monitor() && _session.listening() && !_session.is_auditioning()) {
553
554                 /* control/monitor bus ignores input ports when something is
555                    feeding the listen "stream". data will "arrive" into the
556                    route from the intreturn processor element.
557                 */
558
559                 bufs.silence (nframes, 0);
560         }
561
562         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
563         process_output_buffers (bufs, start_frame, end_frame, nframes, declick, true);
564 }
565
566 void
567 Route::passthru_silence (framepos_t start_frame, framepos_t end_frame, pframes_t nframes, int declick)
568 {
569         BufferSet& bufs (_session.get_route_buffers (n_process_buffers(), true));
570
571         bufs.set_count (_input->n_ports());
572         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
573         process_output_buffers (bufs, start_frame, end_frame, nframes, declick, false);
574 }
575
576 void
577 Route::set_listen (bool yn, void* src)
578 {
579         if (_solo_safe) {
580                 return;
581         }
582
583         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
584                 _route_group->foreach_route (boost::bind (&Route::set_listen, _1, yn, _route_group));
585                 return;
586         }
587
588         if (_monitor_send) {
589                 if (yn != _monitor_send->active()) {
590                         if (yn) {
591                                 _monitor_send->activate ();
592                                 _mute_master->set_soloed (true);
593                         } else {
594                                 _monitor_send->deactivate ();
595                                 _mute_master->set_soloed (false);
596                         }
597
598                         listen_changed (src); /* EMIT SIGNAL */
599                 }
600         }
601 }
602
603 bool
604 Route::listening_via_monitor () const
605 {
606         if (_monitor_send) {
607                 return _monitor_send->active ();
608         } else {
609                 return false;
610         }
611 }
612
613 void
614 Route::set_solo_safe (bool yn, void *src)
615 {
616         if (_solo_safe != yn) {
617                 _solo_safe = yn;
618                 solo_safe_changed (src);
619         }
620 }
621
622 bool
623 Route::solo_safe() const
624 {
625         return _solo_safe;
626 }
627
628 void
629 Route::set_solo (bool yn, void *src)
630 {
631         if (_solo_safe) {
632                 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 ignore solo change due to solo-safe\n", name()));
633                 return;
634         }
635
636         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
637                 _route_group->foreach_route (boost::bind (&Route::set_solo, _1, yn, _route_group));
638                 return;
639         }
640
641         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: set solo => %2, src: %3 grp ? %4 currently self-soloed ? %5\n", 
642                                                   name(), yn, src, (src == _route_group), self_soloed()));
643
644         if (self_soloed() != yn) {
645                 set_self_solo (yn);
646                 set_mute_master_solo ();
647                 solo_changed (true, src); /* EMIT SIGNAL */
648                 _solo_control->Changed (); /* EMIT SIGNAL */
649         }
650 }
651
652 void
653 Route::set_self_solo (bool yn)
654 {
655         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: set SELF solo => %2\n", name(), yn));
656         _self_solo = yn;
657 }
658
659 void
660 Route::mod_solo_by_others_upstream (int32_t delta)
661 {
662         if (_solo_safe) {
663                 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 ignore solo-by-upstream due to solo-safe\n", name()));
664                 return;
665         }
666
667         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 mod solo-by-upstream by %2, current up = %3 down = %4\n", 
668                                                   name(), delta, _soloed_by_others_upstream, _soloed_by_others_downstream));
669
670         uint32_t old_sbu = _soloed_by_others_upstream;
671
672         if (delta < 0) {
673                 if (_soloed_by_others_upstream >= (uint32_t) abs (delta)) {
674                         _soloed_by_others_upstream += delta;
675                 } else {
676                         _soloed_by_others_upstream = 0;
677                 }
678         } else {
679                 _soloed_by_others_upstream += delta;
680         }
681
682         DEBUG_TRACE (DEBUG::Solo, string_compose (
683                              "%1 SbU delta %2 = %3 old = %4 sbd %5 ss %6 exclusive %7\n",
684                              name(), delta, _soloed_by_others_upstream, old_sbu,
685                              _soloed_by_others_downstream, _self_solo, Config->get_exclusive_solo()));
686
687         /* push the inverse solo change to everything that feeds us.
688
689            This is important for solo-within-group. When we solo 1 track out of N that
690            feed a bus, that track will cause mod_solo_by_upstream (+1) to be called
691            on the bus. The bus then needs to call mod_solo_by_downstream (-1) on all
692            tracks that feed it. This will silence them if they were audible because
693            of a bus solo, but the newly soloed track will still be audible (because
694            it is self-soloed).
695
696            but .. do this only when we are being told to solo-by-upstream (i.e delta = +1),
697            not in reverse.
698         */
699
700         if ((_self_solo || _soloed_by_others_downstream) &&
701             ((old_sbu == 0 && _soloed_by_others_upstream > 0) ||
702              (old_sbu > 0 && _soloed_by_others_upstream == 0))) {
703
704                 if (delta > 0 || !Config->get_exclusive_solo()) {
705                         DEBUG_TRACE (DEBUG::Solo, "\t ... INVERT push\n");
706                         for (FedBy::iterator i = _fed_by.begin(); i != _fed_by.end(); ++i) {
707                                 boost::shared_ptr<Route> sr = i->r.lock();
708                                 if (sr) {
709                                         sr->mod_solo_by_others_downstream (-delta);
710                                 }
711                         }
712                 }
713         }
714
715         set_mute_master_solo ();
716         solo_changed (false, this);
717 }
718
719 void
720 Route::mod_solo_by_others_downstream (int32_t delta)
721 {
722         if (_solo_safe) {
723                 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 ignore solo-by-downstream due to solo safe\n", name()));
724                 return;
725         }
726
727         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 mod solo-by-downstream by %2, current up = %3 down = %4\n", 
728                                                   name(), delta, _soloed_by_others_upstream, _soloed_by_others_downstream));
729
730         if (delta < 0) {
731                 if (_soloed_by_others_downstream >= (uint32_t) abs (delta)) {
732                         _soloed_by_others_downstream += delta;
733                 } else {
734                         _soloed_by_others_downstream = 0;
735                 }
736         } else {
737                 _soloed_by_others_downstream += delta;
738         }
739
740         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 SbD delta %2 = %3\n", name(), delta, _soloed_by_others_downstream));
741
742         set_mute_master_solo ();
743         solo_changed (false, this);
744 }
745
746 void
747 Route::set_mute_master_solo ()
748 {
749         _mute_master->set_soloed (self_soloed() || soloed_by_others_downstream() || soloed_by_others_upstream());
750 }
751
752 void
753 Route::set_solo_isolated (bool yn, void *src)
754 {
755         if (is_master() || is_monitor() || is_auditioner()) {
756                 return;
757         }
758
759         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
760                 _route_group->foreach_route (boost::bind (&Route::set_solo_isolated, _1, yn, _route_group));
761                 return;
762         }
763
764         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
765
766         boost::shared_ptr<RouteList> routes = _session.get_routes ();
767         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
768
769                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
770                         continue;
771                 }
772
773                 bool sends_only;
774                 bool does_feed = direct_feeds_according_to_graph (*i, &sends_only); // we will recurse anyway, so don't use ::feeds()
775
776                 if (does_feed && !sends_only) {
777                         (*i)->set_solo_isolated (yn, (*i)->route_group());
778                 }
779         }
780
781         /* XXX should we back-propagate as well? (April 2010: myself and chris goddard think not) */
782
783         bool changed = false;
784
785         if (yn) {
786                 if (_solo_isolated == 0) {
787                         _mute_master->set_solo_ignore (true);
788                         changed = true;
789                 }
790                 _solo_isolated++;
791         } else {
792                 if (_solo_isolated > 0) {
793                         _solo_isolated--;
794                         if (_solo_isolated == 0) {
795                                 _mute_master->set_solo_ignore (false);
796                                 changed = true;
797                         }
798                 }
799         }
800
801         if (changed) {
802                 solo_isolated_changed (src);
803         }
804 }
805
806 bool
807 Route::solo_isolated () const
808 {
809         return _solo_isolated > 0;
810 }
811
812 void
813 Route::set_mute_points (MuteMaster::MutePoint mp)
814 {
815         _mute_master->set_mute_points (mp);
816         mute_points_changed (); /* EMIT SIGNAL */
817
818         if (_mute_master->muted_by_self()) {
819                 mute_changed (this); /* EMIT SIGNAL */
820                 _mute_control->Changed (); /* EMIT SIGNAL */
821         }
822 }
823
824 void
825 Route::set_mute (bool yn, void *src)
826 {
827         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_mute()) {
828                 _route_group->foreach_route (boost::bind (&Route::set_mute, _1, yn, _route_group));
829                 return;
830         }
831
832         if (muted() != yn) {
833                 _mute_master->set_muted_by_self (yn);
834                 /* allow any derived classes to respond to the mute change
835                    before anybody else knows about it.
836                 */
837                 act_on_mute ();
838                 /* tell everyone else */
839                 mute_changed (src); /* EMIT SIGNAL */
840                 _mute_control->Changed (); /* EMIT SIGNAL */
841         }
842 }
843
844 bool
845 Route::muted () const
846 {
847         return _mute_master->muted_by_self();
848 }
849
850 #if 0
851 static void
852 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
853 {
854         cerr << name << " {" << endl;
855         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
856                         p != procs.end(); ++p) {
857                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << " @ " << (*p) << endl;
858         }
859         cerr << "}" << endl;
860 }
861 #endif
862
863 /** Supposing that we want to insert a Processor at a given Placement, return
864  *  the processor to add the new one before (or 0 to add at the end).
865  */
866 boost::shared_ptr<Processor>
867 Route::before_processor_for_placement (Placement p)
868 {
869         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
870
871         ProcessorList::iterator loc;
872         
873         if (p == PreFader) {
874                 /* generic pre-fader: insert immediately before the amp */
875                 loc = find (_processors.begin(), _processors.end(), _amp);
876         } else {
877                 /* generic post-fader: insert right before the main outs */
878                 loc = find (_processors.begin(), _processors.end(), _main_outs);
879         }
880
881         return loc != _processors.end() ? *loc : boost::shared_ptr<Processor> ();
882 }
883
884 /** Supposing that we want to insert a Processor at a given index, return
885  *  the processor to add the new one before (or 0 to add at the end).
886  */
887 boost::shared_ptr<Processor>
888 Route::before_processor_for_index (int index)
889 {
890         if (index == -1) {
891                 return boost::shared_ptr<Processor> ();
892         }
893
894         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
895         
896         ProcessorList::iterator i = _processors.begin ();
897         int j = 0;
898         while (i != _processors.end() && j < index) {
899                 if ((*i)->display_to_user()) {
900                         ++j;
901                 }
902                 
903                 ++i;
904         }
905
906         return (i != _processors.end() ? *i : boost::shared_ptr<Processor> ());
907 }
908
909 /** Add a processor either pre- or post-fader
910  *  @return 0 on success, non-0 on failure.
911  */
912 int
913 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err, bool activation_allowed)
914 {
915         return add_processor (processor, before_processor_for_placement (placement), err, activation_allowed);
916 }
917
918
919 /** Add a processor to a route such that it ends up with a given index into the visible processors.
920  *  @param index Index to add the processor at, or -1 to add at the end of the list.
921  *  @return 0 on success, non-0 on failure.
922  */
923 int
924 Route::add_processor_by_index (boost::shared_ptr<Processor> processor, int index, ProcessorStreams* err, bool activation_allowed)
925 {
926         return add_processor (processor, before_processor_for_index (index), err, activation_allowed);
927 }
928
929 /** Add a processor to the route.
930  *  @param before An existing processor in the list, or 0; the new processor will be inserted immediately before it (or at the end).
931  *  @return 0 on success, non-0 on failure.
932  */
933 int
934 Route::add_processor (boost::shared_ptr<Processor> processor, boost::shared_ptr<Processor> before, ProcessorStreams* err, bool activation_allowed)
935 {
936         assert (processor != _meter);
937         assert (processor != _main_outs);
938
939         DEBUG_TRACE (DEBUG::Processors, string_compose (
940                              "%1 adding processor %2\n", name(), processor->name()));
941
942         if (!AudioEngine::instance()->connected() || !processor) {
943                 return 1;
944         }
945
946         {
947                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
948                 ProcessorState pstate (this);
949
950                 boost::shared_ptr<PluginInsert> pi;
951                 boost::shared_ptr<PortInsert> porti;
952
953                 if (processor == _amp) {
954                         /* Ensure that only one amp is in the list at any time */
955                         ProcessorList::iterator check = find (_processors.begin(), _processors.end(), processor);
956                         if (check != _processors.end()) {
957                                 if (before == _amp) {
958                                         /* Already in position; all is well */
959                                         return 0;
960                                 } else {
961                                         _processors.erase (check);
962                                 }
963                         }
964                 }
965
966                 assert (find (_processors.begin(), _processors.end(), processor) == _processors.end ());
967
968                 ProcessorList::iterator loc;
969                 if (before) {
970                         /* inserting before a processor; find it */
971                         loc = find (_processors.begin(), _processors.end(), before);
972                         if (loc == _processors.end ()) {
973                                 /* Not found */
974                                 return 1;
975                         }
976                 } else {
977                         /* inserting at end */
978                         loc = _processors.end ();
979                 }
980
981                 _processors.insert (loc, processor);
982                 processor->set_owner (this);
983
984                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
985                 // configure redirect ports properly, etc.
986
987                 {
988                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
989
990                         if (configure_processors_unlocked (err)) {
991                                 pstate.restore ();
992                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
993                                 return -1;
994                         }
995                 }
996
997                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
998
999                         if (pi->has_no_inputs ()) {
1000                                 /* generator plugin */
1001                                 _have_internal_generator = true;
1002                         }
1003
1004                 }
1005
1006                 if (activation_allowed && !_session.get_disable_all_loaded_plugins()) {
1007                         processor->activate ();
1008                 }
1009
1010                 processor->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1011
1012                 _output->set_user_latency (0);
1013         }
1014
1015         reset_instrument_info ();
1016         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1017         set_processor_positions ();
1018
1019         return 0;
1020 }
1021
1022 bool
1023 Route::add_processor_from_xml_2X (const XMLNode& node, int version)
1024 {
1025         const XMLProperty *prop;
1026
1027         try {
1028                 boost::shared_ptr<Processor> processor;
1029
1030                 /* bit of a hack: get the `placement' property from the <Redirect> tag here
1031                    so that we can add the processor in the right place (pre/post-fader)
1032                 */
1033
1034                 XMLNodeList const & children = node.children ();
1035                 XMLNodeList::const_iterator i = children.begin ();
1036
1037                 while (i != children.end() && (*i)->name() != X_("Redirect")) {
1038                         ++i;
1039                 }
1040
1041                 Placement placement = PreFader;
1042
1043                 if (i != children.end()) {
1044                         if ((prop = (*i)->property (X_("placement"))) != 0) {
1045                                 placement = Placement (string_2_enum (prop->value(), placement));
1046                         }
1047                 }
1048
1049                 if (node.name() == "Insert") {
1050
1051                         if ((prop = node.property ("type")) != 0) {
1052
1053                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
1054                                                 prop->value() == "lv2" ||
1055                                                 prop->value() == "windows-vst" ||
1056                                                 prop->value() == "lxvst" ||
1057                                                 prop->value() == "audiounit") {
1058
1059                                         processor.reset (new PluginInsert (_session));
1060
1061                                 } else {
1062
1063                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
1064                                 }
1065
1066                         }
1067
1068                 } else if (node.name() == "Send") {
1069
1070                         processor.reset (new Send (_session, _pannable, _mute_master));
1071
1072                 } else {
1073
1074                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
1075                         return false;
1076                 }
1077
1078                 if (processor->set_state (node, version)) {
1079                         return false;
1080                 }
1081
1082                 return (add_processor (processor, placement) == 0);
1083         }
1084
1085         catch (failed_constructor &err) {
1086                 warning << _("processor could not be created. Ignored.") << endmsg;
1087                 return false;
1088         }
1089 }
1090
1091 int
1092 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
1093 {
1094         /* NOTE: this is intended to be used ONLY when copying
1095            processors from another Route. Hence the subtle
1096            differences between this and ::add_processor()
1097         */
1098
1099         ProcessorList::iterator loc;
1100
1101         if (before) {
1102                 loc = find(_processors.begin(), _processors.end(), before);
1103         } else {
1104                 /* nothing specified - at end */
1105                 loc = _processors.end ();
1106         }
1107
1108         if (!_session.engine().connected()) {
1109                 return 1;
1110         }
1111
1112         if (others.empty()) {
1113                 return 0;
1114         }
1115
1116         {
1117                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1118                 ProcessorState pstate (this);
1119
1120                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1121
1122                         if (*i == _meter) {
1123                                 continue;
1124                         }
1125
1126                         boost::shared_ptr<PluginInsert> pi;
1127
1128                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1129                                 pi->set_count (1);
1130                         }
1131
1132                         _processors.insert (loc, *i);
1133                         (*i)->set_owner (this);
1134
1135                         if ((*i)->active()) {
1136                                 (*i)->activate ();
1137                         }
1138
1139                         {
1140                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1141                                 if (configure_processors_unlocked (err)) {
1142                                         pstate.restore ();
1143                                         configure_processors_unlocked (0); // it worked before we tried to add it ...
1144                                         return -1;
1145                                 }
1146                         }
1147
1148                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1149                 }
1150
1151                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1152                         boost::shared_ptr<PluginInsert> pi;
1153
1154                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1155                                 if (pi->has_no_inputs ()) {
1156                                         _have_internal_generator = true;
1157                                         break;
1158                                 }
1159                         }
1160                 }
1161
1162                 _output->set_user_latency (0);
1163         }
1164
1165         reset_instrument_info ();
1166         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1167         set_processor_positions ();
1168
1169         return 0;
1170 }
1171
1172 void
1173 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1174 {
1175         if (p == PreFader) {
1176                 start = _processors.begin();
1177                 end = find(_processors.begin(), _processors.end(), _amp);
1178         } else {
1179                 start = find(_processors.begin(), _processors.end(), _amp);
1180                 ++start;
1181                 end = _processors.end();
1182         }
1183 }
1184
1185 /** Turn off all processors with a given placement
1186  * @param p Placement of processors to disable
1187  */
1188 void
1189 Route::disable_processors (Placement p)
1190 {
1191         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1192
1193         ProcessorList::iterator start, end;
1194         placement_range(p, start, end);
1195
1196         for (ProcessorList::iterator i = start; i != end; ++i) {
1197                 (*i)->deactivate ();
1198         }
1199
1200         _session.set_dirty ();
1201 }
1202
1203 /** Turn off all redirects
1204  */
1205 void
1206 Route::disable_processors ()
1207 {
1208         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1209
1210         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1211                 (*i)->deactivate ();
1212         }
1213
1214         _session.set_dirty ();
1215 }
1216
1217 /** Turn off all redirects with a given placement
1218  * @param p Placement of redirects to disable
1219  */
1220 void
1221 Route::disable_plugins (Placement p)
1222 {
1223         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1224
1225         ProcessorList::iterator start, end;
1226         placement_range(p, start, end);
1227
1228         for (ProcessorList::iterator i = start; i != end; ++i) {
1229                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1230                         (*i)->deactivate ();
1231                 }
1232         }
1233
1234         _session.set_dirty ();
1235 }
1236
1237 /** Turn off all plugins
1238  */
1239 void
1240 Route::disable_plugins ()
1241 {
1242         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1243
1244         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1245                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1246                         (*i)->deactivate ();
1247                 }
1248         }
1249
1250         _session.set_dirty ();
1251 }
1252
1253
1254 void
1255 Route::ab_plugins (bool forward)
1256 {
1257         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1258
1259         if (forward) {
1260
1261                 /* forward = turn off all active redirects, and mark them so that the next time
1262                    we go the other way, we will revert them
1263                 */
1264
1265                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1266                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1267                                 continue;
1268                         }
1269
1270                         if ((*i)->active()) {
1271                                 (*i)->deactivate ();
1272                                 (*i)->set_next_ab_is_active (true);
1273                         } else {
1274                                 (*i)->set_next_ab_is_active (false);
1275                         }
1276                 }
1277
1278         } else {
1279
1280                 /* backward = if the redirect was marked to go active on the next ab, do so */
1281
1282                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1283
1284                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1285                                 continue;
1286                         }
1287
1288                         if ((*i)->get_next_ab_is_active()) {
1289                                 (*i)->activate ();
1290                         } else {
1291                                 (*i)->deactivate ();
1292                         }
1293                 }
1294         }
1295
1296         _session.set_dirty ();
1297 }
1298
1299
1300 /** Remove processors with a given placement.
1301  * @param p Placement of processors to remove.
1302  */
1303 void
1304 Route::clear_processors (Placement p)
1305 {
1306         if (!_session.engine().connected()) {
1307                 return;
1308         }
1309
1310         bool already_deleting = _session.deletion_in_progress();
1311         if (!already_deleting) {
1312                 _session.set_deletion_in_progress();
1313         }
1314
1315         {
1316                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1317                 ProcessorList new_list;
1318                 ProcessorStreams err;
1319                 bool seen_amp = false;
1320
1321                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1322
1323                         if (*i == _amp) {
1324                                 seen_amp = true;
1325                         }
1326
1327                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1328
1329                                 /* you can't remove these */
1330
1331                                 new_list.push_back (*i);
1332
1333                         } else {
1334                                 if (seen_amp) {
1335
1336                                         switch (p) {
1337                                         case PreFader:
1338                                                 new_list.push_back (*i);
1339                                                 break;
1340                                         case PostFader:
1341                                                 (*i)->drop_references ();
1342                                                 break;
1343                                         }
1344
1345                                 } else {
1346
1347                                         switch (p) {
1348                                         case PreFader:
1349                                                 (*i)->drop_references ();
1350                                                 break;
1351                                         case PostFader:
1352                                                 new_list.push_back (*i);
1353                                                 break;
1354                                         }
1355                                 }
1356                         }
1357                 }
1358
1359                 _processors = new_list;
1360
1361                 {
1362                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1363                         configure_processors_unlocked (&err); // this can't fail
1364                 }
1365         }
1366
1367         processor_max_streams.reset();
1368         _have_internal_generator = false;
1369         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1370         set_processor_positions ();
1371
1372         reset_instrument_info ();
1373
1374         if (!already_deleting) {
1375                 _session.clear_deletion_in_progress();
1376         }
1377 }
1378
1379 int
1380 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err, bool need_process_lock)
1381 {
1382         // TODO once the export point can be configured properly, do something smarter here
1383         if (processor == _capturing_processor) {
1384                 _capturing_processor.reset();
1385         }
1386
1387         /* these can never be removed */
1388
1389         if (processor == _amp || processor == _meter || processor == _main_outs) {
1390                 return 0;
1391         }
1392
1393         if (!_session.engine().connected()) {
1394                 return 1;
1395         }
1396
1397         processor_max_streams.reset();
1398
1399         {
1400                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1401                 ProcessorState pstate (this);
1402
1403                 ProcessorList::iterator i;
1404                 bool removed = false;
1405
1406                 for (i = _processors.begin(); i != _processors.end(); ) {
1407                         if (*i == processor) {
1408
1409                                 /* move along, see failure case for configure_processors()
1410                                    where we may need to reconfigure the processor.
1411                                 */
1412
1413                                 /* stop redirects that send signals to JACK ports
1414                                    from causing noise as a result of no longer being
1415                                    run.
1416                                 */
1417
1418                                 boost::shared_ptr<IOProcessor> iop;
1419
1420                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1421                                         iop->disconnect ();
1422                                 }
1423
1424                                 i = _processors.erase (i);
1425                                 removed = true;
1426                                 break;
1427
1428                         } else {
1429                                 ++i;
1430                         }
1431
1432                         _output->set_user_latency (0);
1433                 }
1434
1435                 if (!removed) {
1436                         /* what? */
1437                         return 1;
1438                 } 
1439
1440                 if (need_process_lock) {
1441                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1442
1443                         if (configure_processors_unlocked (err)) {
1444                                 pstate.restore ();
1445                                 /* we know this will work, because it worked before :) */
1446                                 configure_processors_unlocked (0);
1447                                 return -1;
1448                         }
1449                 } else {
1450                         if (configure_processors_unlocked (err)) {
1451                                 pstate.restore ();
1452                                 /* we know this will work, because it worked before :) */
1453                                 configure_processors_unlocked (0);
1454                                 return -1;
1455                         }
1456                 }
1457
1458                 _have_internal_generator = false;
1459
1460                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1461                         boost::shared_ptr<PluginInsert> pi;
1462
1463                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1464                                 if (pi->has_no_inputs ()) {
1465                                         _have_internal_generator = true;
1466                                         break;
1467                                 }
1468                         }
1469                 }
1470         }
1471
1472         reset_instrument_info ();
1473         processor->drop_references ();
1474         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1475         set_processor_positions ();
1476
1477         return 0;
1478 }
1479
1480 int
1481 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1482 {
1483         ProcessorList deleted;
1484
1485         if (!_session.engine().connected()) {
1486                 return 1;
1487         }
1488
1489         processor_max_streams.reset();
1490
1491         {
1492                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1493                 ProcessorState pstate (this);
1494
1495                 ProcessorList::iterator i;
1496                 boost::shared_ptr<Processor> processor;
1497
1498                 for (i = _processors.begin(); i != _processors.end(); ) {
1499
1500                         processor = *i;
1501
1502                         /* these can never be removed */
1503
1504                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1505                                 ++i;
1506                                 continue;
1507                         }
1508
1509                         /* see if its in the list of processors to delete */
1510
1511                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1512                                 ++i;
1513                                 continue;
1514                         }
1515
1516                         /* stop IOProcessors that send to JACK ports
1517                            from causing noise as a result of no longer being
1518                            run.
1519                         */
1520
1521                         boost::shared_ptr<IOProcessor> iop;
1522
1523                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1524                                 iop->disconnect ();
1525                         }
1526
1527                         deleted.push_back (processor);
1528                         i = _processors.erase (i);
1529                 }
1530
1531                 if (deleted.empty()) {
1532                         /* none of those in the requested list were found */
1533                         return 0;
1534                 }
1535
1536                 _output->set_user_latency (0);
1537
1538                 {
1539                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1540
1541                         if (configure_processors_unlocked (err)) {
1542                                 pstate.restore ();
1543                                 /* we know this will work, because it worked before :) */
1544                                 configure_processors_unlocked (0);
1545                                 return -1;
1546                         }
1547                 }
1548
1549                 _have_internal_generator = false;
1550
1551                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1552                         boost::shared_ptr<PluginInsert> pi;
1553
1554                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1555                                 if (pi->has_no_inputs ()) {
1556                                         _have_internal_generator = true;
1557                                         break;
1558                                 }
1559                         }
1560                 }
1561         }
1562
1563         /* now try to do what we need to so that those that were removed will be deleted */
1564
1565         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1566                 (*i)->drop_references ();
1567         }
1568
1569         reset_instrument_info ();
1570         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1571         set_processor_positions ();
1572
1573         return 0;
1574 }
1575
1576 void
1577 Route::reset_instrument_info ()
1578 {
1579         boost::shared_ptr<Processor> instr = the_instrument();
1580         if (instr) {
1581                 _instrument_info.set_internal_instrument (instr);
1582         }
1583 }
1584
1585 /** Caller must hold process lock */
1586 int
1587 Route::configure_processors (ProcessorStreams* err)
1588 {
1589         assert (!AudioEngine::instance()->process_lock().trylock());
1590
1591         if (!_in_configure_processors) {
1592                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1593                 return configure_processors_unlocked (err);
1594         }
1595
1596         return 0;
1597 }
1598
1599 ChanCount
1600 Route::input_streams () const
1601 {
1602         return _input->n_ports ();
1603 }
1604
1605 list<pair<ChanCount, ChanCount> >
1606 Route::try_configure_processors (ChanCount in, ProcessorStreams* err)
1607 {
1608         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1609
1610         return try_configure_processors_unlocked (in, err);
1611 }
1612
1613 list<pair<ChanCount, ChanCount> >
1614 Route::try_configure_processors_unlocked (ChanCount in, ProcessorStreams* err)
1615 {
1616         // Check each processor in order to see if we can configure as requested
1617         ChanCount out;
1618         list<pair<ChanCount, ChanCount> > configuration;
1619         uint32_t index = 0;
1620
1621         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1622         DEBUG_TRACE (DEBUG::Processors, "{\n");
1623
1624         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1625
1626                 if (boost::dynamic_pointer_cast<UnknownProcessor> (*p)) {
1627                         DEBUG_TRACE (DEBUG::Processors, "--- CONFIGURE ABORTED due to unknown processor.\n");
1628                         DEBUG_TRACE (DEBUG::Processors, "}\n");
1629                         return list<pair<ChanCount, ChanCount> > ();
1630                 }
1631
1632                 if ((*p)->can_support_io_configuration(in, out)) {
1633                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID=%2 in=%3 out=%4\n",(*p)->name(), (*p)->id(), in, out));
1634                         configuration.push_back(make_pair(in, out));
1635                         in = out;
1636                 } else {
1637                         if (err) {
1638                                 err->index = index;
1639                                 err->count = in;
1640                         }
1641                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
1642                         DEBUG_TRACE (DEBUG::Processors, string_compose ("---- %1 cannot support in=%2 out=%3\n", (*p)->name(), in, out));
1643                         DEBUG_TRACE (DEBUG::Processors, "}\n");
1644                         return list<pair<ChanCount, ChanCount> > ();
1645                 }
1646         }
1647
1648         DEBUG_TRACE (DEBUG::Processors, "}\n");
1649
1650         return configuration;
1651 }
1652
1653 /** Set the input/output configuration of each processor in the processors list.
1654  *  Caller must hold process lock.
1655  *  Return 0 on success, otherwise configuration is impossible.
1656  */
1657 int
1658 Route::configure_processors_unlocked (ProcessorStreams* err)
1659 {
1660         assert (!AudioEngine::instance()->process_lock().trylock());
1661
1662         if (_in_configure_processors) {
1663                 return 0;
1664         }
1665
1666         /* put invisible processors where they should be */
1667         setup_invisible_processors ();
1668
1669         _in_configure_processors = true;
1670
1671         list<pair<ChanCount, ChanCount> > configuration = try_configure_processors_unlocked (input_streams (), err);
1672
1673         if (configuration.empty ()) {
1674                 _in_configure_processors = false;
1675                 return -1;
1676         }
1677
1678         ChanCount out;
1679         bool seen_mains_out = false;
1680         processor_out_streams = _input->n_ports();
1681         processor_max_streams.reset();
1682
1683         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1684         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1685
1686                 if (boost::dynamic_pointer_cast<UnknownProcessor> (*p)) {
1687                         break;
1688                 }
1689
1690                 (*p)->configure_io(c->first, c->second);
1691                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1692                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1693                 out = c->second;
1694
1695                 if (boost::dynamic_pointer_cast<Delivery> (*p)
1696                                 && boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main) {
1697                         /* main delivery will increase port count to match input.
1698                          * the Delivery::Main is usually the last processor - followed only by
1699                          * 'MeterOutput'.
1700                          */
1701                         seen_mains_out = true;
1702                 }
1703                 if (!seen_mains_out) {
1704                         processor_out_streams = out;
1705                 }
1706         }
1707
1708
1709         if (_meter) {
1710                 _meter->reset_max_channels (processor_max_streams);
1711         }
1712
1713         /* make sure we have sufficient scratch buffers to cope with the new processor
1714            configuration 
1715         */
1716         _session.ensure_buffers (n_process_buffers ());
1717
1718         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration complete\n", _name));
1719
1720         _in_configure_processors = false;
1721         return 0;
1722 }
1723
1724 /** Set all visible processors to a given active state (except Fader, whose state is not changed)
1725  *  @param state New active state for those processors.
1726  */
1727 void
1728 Route::all_visible_processors_active (bool state)
1729 {
1730         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1731
1732         if (_processors.empty()) {
1733                 return;
1734         }
1735         
1736         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1737                 if (!(*i)->display_to_user() || boost::dynamic_pointer_cast<Amp> (*i)) {
1738                         continue;
1739                 }
1740                 
1741                 if (state) {
1742                         (*i)->activate ();
1743                 } else {
1744                         (*i)->deactivate ();
1745                 }
1746         }
1747
1748         _session.set_dirty ();
1749 }
1750
1751 int
1752 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1753 {
1754         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1755            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1756            processors in the current actual processor list that are hidden. Any visible processors
1757            in the current list but not in "new_order" will be assumed to be deleted.
1758         */
1759
1760         {
1761                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1762                 ProcessorState pstate (this);
1763
1764                 ProcessorList::iterator oiter;
1765                 ProcessorList::const_iterator niter;
1766                 ProcessorList as_it_will_be;
1767
1768                 oiter = _processors.begin();
1769                 niter = new_order.begin();
1770
1771                 while (niter !=  new_order.end()) {
1772
1773                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1774                            then append it to the temp list.
1775
1776                            Otherwise, see if the next processor in the old list is in the new list. if not,
1777                            its been deleted. If its there, append it to the temp list.
1778                         */
1779
1780                         if (oiter == _processors.end()) {
1781
1782                                 /* no more elements in the old list, so just stick the rest of
1783                                    the new order onto the temp list.
1784                                 */
1785
1786                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1787                                 while (niter != new_order.end()) {
1788                                         ++niter;
1789                                 }
1790                                 break;
1791
1792                         } else {
1793
1794                                 if (!(*oiter)->display_to_user()) {
1795
1796                                         as_it_will_be.push_back (*oiter);
1797
1798                                 } else {
1799
1800                                         /* visible processor: check that its in the new order */
1801
1802                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1803                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1804                                         } else {
1805                                                 /* ignore this one, and add the next item from the new order instead */
1806                                                 as_it_will_be.push_back (*niter);
1807                                                 ++niter;
1808                                         }
1809                                 }
1810
1811                                 /* now remove from old order - its taken care of no matter what */
1812                                 oiter = _processors.erase (oiter);
1813                         }
1814
1815                 }
1816
1817                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1818
1819                 /* If the meter is in a custom position, find it and make a rough note of its position */
1820                 maybe_note_meter_position ();
1821
1822                 {
1823                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1824
1825                         if (configure_processors_unlocked (err)) {
1826                                 pstate.restore ();
1827                                 return -1;
1828                         }
1829                 }
1830         }
1831
1832         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1833         set_processor_positions ();
1834
1835         return 0;
1836 }
1837
1838 XMLNode&
1839 Route::get_state()
1840 {
1841         return state(true);
1842 }
1843
1844 XMLNode&
1845 Route::get_template()
1846 {
1847         return state(false);
1848 }
1849
1850 XMLNode&
1851 Route::state(bool full_state)
1852 {
1853         XMLNode *node = new XMLNode("Route");
1854         ProcessorList::iterator i;
1855         char buf[32];
1856
1857         id().print (buf, sizeof (buf));
1858         node->add_property("id", buf);
1859         node->add_property ("name", _name);
1860         node->add_property("default-type", _default_type.to_string());
1861
1862         if (_flags) {
1863                 node->add_property("flags", enum_2_string (_flags));
1864         }
1865
1866         node->add_property("active", _active?"yes":"no");
1867         string p;
1868         boost::to_string (_phase_invert, p);
1869         node->add_property("phase-invert", p);
1870         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1871         node->add_property("meter-point", enum_2_string (_meter_point));
1872
1873         node->add_property("meter-type", enum_2_string (_meter_type));
1874
1875         if (_route_group) {
1876                 node->add_property("route-group", _route_group->name());
1877         }
1878
1879         snprintf (buf, sizeof (buf), "%d", _order_key);
1880         node->add_property ("order-key", buf);
1881         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1882         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_upstream);
1883         node->add_property ("soloed-by-upstream", buf);
1884         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_downstream);
1885         node->add_property ("soloed-by-downstream", buf);
1886         node->add_property ("solo-isolated", solo_isolated() ? "yes" : "no");
1887         node->add_property ("solo-safe", _solo_safe ? "yes" : "no");
1888
1889         node->add_child_nocopy (_input->state (full_state));
1890         node->add_child_nocopy (_output->state (full_state));
1891         node->add_child_nocopy (_solo_control->get_state ());
1892         node->add_child_nocopy (_mute_control->get_state ());
1893         node->add_child_nocopy (_mute_master->get_state ());
1894
1895         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1896         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1897         remote_control_node->add_property (X_("id"), buf);
1898         node->add_child_nocopy (*remote_control_node);
1899
1900         if (_comment.length()) {
1901                 XMLNode *cmt = node->add_child ("Comment");
1902                 cmt->add_content (_comment);
1903         }
1904
1905         if (_pannable) {
1906                 node->add_child_nocopy (_pannable->state (full_state));
1907         }
1908
1909         for (i = _processors.begin(); i != _processors.end(); ++i) {
1910                 if (!full_state) {
1911                         /* template save: do not include internal sends functioning as 
1912                            aux sends because the chance of the target ID
1913                            in the session where this template is used
1914                            is not very likely.
1915
1916                            similarly, do not save listen sends which connect to
1917                            the monitor section, because these will always be
1918                            added if necessary.
1919                         */
1920                         boost::shared_ptr<InternalSend> is;
1921
1922                         if ((is = boost::dynamic_pointer_cast<InternalSend> (*i)) != 0) {
1923                                 if (is->role() == Delivery::Listen) {
1924                                         continue;
1925                                 }
1926                         }
1927                 }
1928                 node->add_child_nocopy((*i)->state (full_state));
1929         }
1930
1931         if (_extra_xml) {
1932                 node->add_child_copy (*_extra_xml);
1933         }
1934
1935         if (_custom_meter_position_noted) {
1936                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
1937                 if (after) {
1938                         after->id().print (buf, sizeof (buf));
1939                         node->add_property (X_("processor-after-last-custom-meter"), buf);
1940                 }
1941
1942                 node->add_property (X_("last-custom-meter-was-at-end"), _last_custom_meter_was_at_end ? "yes" : "no");
1943         }
1944
1945         return *node;
1946 }
1947
1948 int
1949 Route::set_state (const XMLNode& node, int version)
1950 {
1951         if (version < 3000) {
1952                 return set_state_2X (node, version);
1953         }
1954
1955         XMLNodeList nlist;
1956         XMLNodeConstIterator niter;
1957         XMLNode *child;
1958         const XMLProperty *prop;
1959
1960         if (node.name() != "Route"){
1961                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1962                 return -1;
1963         }
1964
1965         if ((prop = node.property (X_("name"))) != 0) {
1966                 Route::set_name (prop->value());
1967         }
1968
1969         set_id (node);
1970         _initial_io_setup = true;
1971
1972         if ((prop = node.property (X_("flags"))) != 0) {
1973                 _flags = Flag (string_2_enum (prop->value(), _flags));
1974         } else {
1975                 _flags = Flag (0);
1976         }
1977
1978         if (is_master() || is_monitor() || is_auditioner()) {
1979                 _mute_master->set_solo_ignore (true);
1980         }
1981
1982         if (is_monitor()) {
1983                 /* monitor bus does not get a panner, but if (re)created
1984                    via XML, it will already have one by the time we
1985                    call ::set_state(). so ... remove it.
1986                 */
1987                 unpan ();
1988         }
1989
1990         /* add all processors (except amp, which is always present) */
1991
1992         nlist = node.children();
1993         XMLNode processor_state (X_("processor_state"));
1994
1995         Stateful::save_extra_xml (node);
1996
1997         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1998
1999                 child = *niter;
2000
2001                 if (child->name() == IO::state_node_name) {
2002                         if ((prop = child->property (X_("direction"))) == 0) {
2003                                 continue;
2004                         }
2005
2006                         if (prop->value() == "Input") {
2007                                 _input->set_state (*child, version);
2008                         } else if (prop->value() == "Output") {
2009                                 _output->set_state (*child, version);
2010                         }
2011                 }
2012
2013                 if (child->name() == X_("Processor")) {
2014                         processor_state.add_child_copy (*child);
2015                 }
2016
2017                 if (child->name() == X_("Pannable")) {
2018                         if (_pannable) {
2019                                 _pannable->set_state (*child, version);
2020                         } else {
2021                                 warning << string_compose (_("Pannable state found for route (%1) without a panner!"), name()) << endmsg;
2022                         }
2023                 }
2024         }
2025
2026         if ((prop = node.property (X_("meter-point"))) != 0) {
2027                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
2028                 set_meter_point (mp, true);
2029                 if (_meter) {
2030                         _meter->set_display_to_user (_meter_point == MeterCustom);
2031                 }
2032         }
2033
2034         if ((prop = node.property (X_("meter-type"))) != 0) {
2035                 _meter_type = MeterType (string_2_enum (prop->value (), _meter_type));
2036         }
2037
2038         _initial_io_setup = false;
2039
2040         set_processor_state (processor_state);
2041
2042         // this looks up the internal instrument in processors
2043         reset_instrument_info();
2044
2045         if ((prop = node.property ("self-solo")) != 0) {
2046                 set_self_solo (string_is_affirmative (prop->value()));
2047         }
2048
2049         if ((prop = node.property ("soloed-by-upstream")) != 0) {
2050                 _soloed_by_others_upstream = 0; // needed for mod_.... () to work
2051                 mod_solo_by_others_upstream (atoi (prop->value()));
2052         }
2053
2054         if ((prop = node.property ("soloed-by-downstream")) != 0) {
2055                 _soloed_by_others_downstream = 0; // needed for mod_.... () to work
2056                 mod_solo_by_others_downstream (atoi (prop->value()));
2057         }
2058
2059         if ((prop = node.property ("solo-isolated")) != 0) {
2060                 set_solo_isolated (string_is_affirmative (prop->value()), this);
2061         }
2062
2063         if ((prop = node.property ("solo-safe")) != 0) {
2064                 set_solo_safe (string_is_affirmative (prop->value()), this);
2065         }
2066
2067         if ((prop = node.property (X_("phase-invert"))) != 0) {
2068                 set_phase_invert (boost::dynamic_bitset<> (prop->value ()));
2069         }
2070
2071         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2072                 set_denormal_protection (string_is_affirmative (prop->value()));
2073         }
2074
2075         if ((prop = node.property (X_("active"))) != 0) {
2076                 bool yn = string_is_affirmative (prop->value());
2077                 _active = !yn; // force switch
2078                 set_active (yn, this);
2079         }
2080
2081         if ((prop = node.property (X_("order-key"))) != 0) { // New order key (no separate mixer/editor ordering)
2082                 set_order_key (atoi(prop->value()));
2083         }
2084
2085         if ((prop = node.property (X_("order-keys"))) != 0) { // Deprecated order keys
2086
2087                 int32_t n;
2088
2089                 string::size_type colon, equal;
2090                 string remaining = prop->value();
2091
2092                 while (remaining.length()) {
2093
2094                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2095                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2096                                       << endmsg;
2097                         } else {
2098                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
2099                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2100                                               << endmsg;
2101                                 } else {
2102                                         string keyname = remaining.substr (0, equal);
2103
2104                                         if ((keyname == "EditorSort") || (keyname == "editor")) {
2105                                                 cerr << "Setting " << name() << " order key to " << n << " using saved Editor order." << endl;
2106                                                 set_order_key (n);
2107                                         }
2108                                 }
2109                         }
2110
2111                         colon = remaining.find_first_of (':');
2112
2113                         if (colon != string::npos) {
2114                                 remaining = remaining.substr (colon+1);
2115                         } else {
2116                                 break;
2117                         }
2118                 }
2119         }
2120
2121         if ((prop = node.property (X_("processor-after-last-custom-meter"))) != 0) {
2122                 PBD::ID id (prop->value ());
2123                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2124                 ProcessorList::const_iterator i = _processors.begin ();
2125                 while (i != _processors.end() && (*i)->id() != id) {
2126                         ++i;
2127                 }
2128
2129                 if (i != _processors.end ()) {
2130                         _processor_after_last_custom_meter = *i;
2131                         _custom_meter_position_noted = true;
2132                 }
2133         }
2134
2135         if ((prop = node.property (X_("last-custom-meter-was-at-end"))) != 0) {
2136                 _last_custom_meter_was_at_end = string_is_affirmative (prop->value ());
2137         }
2138
2139         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2140                 child = *niter;
2141
2142                 if (child->name() == X_("Comment")) {
2143
2144                         /* XXX this is a terrible API design in libxml++ */
2145
2146                         XMLNode *cmt = *(child->children().begin());
2147                         _comment = cmt->content();
2148
2149                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
2150                         if (prop->value() == "solo") {
2151                                 _solo_control->set_state (*child, version);
2152                         } else if (prop->value() == "mute") {
2153                                 _mute_control->set_state (*child, version);
2154                         }
2155
2156                 } else if (child->name() == X_("RemoteControl")) {
2157                         if ((prop = child->property (X_("id"))) != 0) {
2158                                 int32_t x;
2159                                 sscanf (prop->value().c_str(), "%d", &x);
2160                                 set_remote_control_id_internal (x);
2161                         }
2162
2163                 } else if (child->name() == X_("MuteMaster")) {
2164                         _mute_master->set_state (*child, version);
2165                 }
2166         }
2167
2168         return 0;
2169 }
2170
2171 int
2172 Route::set_state_2X (const XMLNode& node, int version)
2173 {
2174         XMLNodeList nlist;
2175         XMLNodeConstIterator niter;
2176         XMLNode *child;
2177         const XMLProperty *prop;
2178
2179         /* 2X things which still remain to be handled:
2180          * default-type
2181          * automation
2182          * controlouts
2183          */
2184
2185         if (node.name() != "Route") {
2186                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2187                 return -1;
2188         }
2189
2190         if ((prop = node.property (X_("flags"))) != 0) {
2191                 string f = prop->value ();
2192                 boost::replace_all (f, "ControlOut", "MonitorOut");
2193                 _flags = Flag (string_2_enum (f, _flags));
2194         } else {
2195                 _flags = Flag (0);
2196         }
2197
2198         if (is_master() || is_monitor() || is_auditioner()) {
2199                 _mute_master->set_solo_ignore (true);
2200         }
2201
2202         if ((prop = node.property (X_("phase-invert"))) != 0) {
2203                 boost::dynamic_bitset<> p (_input->n_ports().n_audio ());
2204                 if (string_is_affirmative (prop->value ())) {
2205                         p.set ();
2206                 }
2207                 set_phase_invert (p);
2208         }
2209
2210         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2211                 set_denormal_protection (string_is_affirmative (prop->value()));
2212         }
2213
2214         if ((prop = node.property (X_("soloed"))) != 0) {
2215                 bool yn = string_is_affirmative (prop->value());
2216
2217                 /* XXX force reset of solo status */
2218
2219                 set_solo (yn, this);
2220         }
2221
2222         if ((prop = node.property (X_("muted"))) != 0) {
2223
2224                 bool first = true;
2225                 bool muted = string_is_affirmative (prop->value());
2226
2227                 if (muted) {
2228
2229                         string mute_point;
2230
2231                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2232
2233                                 if (string_is_affirmative (prop->value())){
2234                                         mute_point = mute_point + "PreFader";
2235                                         first = false;
2236                                 }
2237                         }
2238
2239                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2240
2241                                 if (string_is_affirmative (prop->value())){
2242
2243                                         if (!first) {
2244                                                 mute_point = mute_point + ",";
2245                                         }
2246
2247                                         mute_point = mute_point + "PostFader";
2248                                         first = false;
2249                                 }
2250                         }
2251
2252                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2253
2254                                 if (string_is_affirmative (prop->value())){
2255
2256                                         if (!first) {
2257                                                 mute_point = mute_point + ",";
2258                                         }
2259
2260                                         mute_point = mute_point + "Listen";
2261                                         first = false;
2262                                 }
2263                         }
2264
2265                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2266
2267                                 if (string_is_affirmative (prop->value())){
2268
2269                                         if (!first) {
2270                                                 mute_point = mute_point + ",";
2271                                         }
2272
2273                                         mute_point = mute_point + "Main";
2274                                 }
2275                         }
2276
2277                         _mute_master->set_mute_points (mute_point);
2278                         _mute_master->set_muted_by_self (true);
2279                 }
2280         }
2281
2282         if ((prop = node.property (X_("meter-point"))) != 0) {
2283                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2284         }
2285
2286         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2287            don't mean the same thing.
2288         */
2289
2290         if ((prop = node.property (X_("order-keys"))) != 0) {
2291
2292                 int32_t n;
2293
2294                 string::size_type colon, equal;
2295                 string remaining = prop->value();
2296
2297                 while (remaining.length()) {
2298
2299                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2300                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2301                                         << endmsg;
2302                         } else {
2303                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
2304                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2305                                                 << endmsg;
2306                                 } else {
2307                                         string keyname = remaining.substr (0, equal);
2308
2309                                         if (keyname == "EditorSort" || keyname == "editor") {
2310                                                 info << string_compose(_("Converting deprecated order key for %1 using Editor order %2"), name (), n) << endmsg;
2311                                                 set_order_key (n);
2312                                         }
2313                                 }
2314                         }
2315
2316                         colon = remaining.find_first_of (':');
2317
2318                         if (colon != string::npos) {
2319                                 remaining = remaining.substr (colon+1);
2320                         } else {
2321                                 break;
2322                         }
2323                 }
2324         }
2325
2326         /* IOs */
2327
2328         nlist = node.children ();
2329         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2330
2331                 child = *niter;
2332
2333                 if (child->name() == IO::state_node_name) {
2334
2335                         /* there is a note in IO::set_state_2X() about why we have to call
2336                            this directly.
2337                            */
2338
2339                         _input->set_state_2X (*child, version, true);
2340                         _output->set_state_2X (*child, version, false);
2341
2342                         if ((prop = child->property (X_("name"))) != 0) {
2343                                 Route::set_name (prop->value ());
2344                         }
2345
2346                         set_id (*child);
2347
2348                         if ((prop = child->property (X_("active"))) != 0) {
2349                                 bool yn = string_is_affirmative (prop->value());
2350                                 _active = !yn; // force switch
2351                                 set_active (yn, this);
2352                         }
2353
2354                         if ((prop = child->property (X_("gain"))) != 0) {
2355                                 gain_t val;
2356
2357                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2358                                         _amp->gain_control()->set_value (val);
2359                                 }
2360                         }
2361
2362                         /* Set up Panners in the IO */
2363                         XMLNodeList io_nlist = child->children ();
2364
2365                         XMLNodeConstIterator io_niter;
2366                         XMLNode *io_child;
2367
2368                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2369
2370                                 io_child = *io_niter;
2371
2372                                 if (io_child->name() == X_("Panner")) {
2373                                         _main_outs->panner_shell()->set_state(*io_child, version);
2374                                 } else if (io_child->name() == X_("Automation")) {
2375                                         /* IO's automation is for the fader */
2376                                         _amp->set_automation_xml_state (*io_child, Evoral::Parameter (GainAutomation));
2377                                 }
2378                         }
2379                 }
2380         }
2381
2382         XMLNodeList redirect_nodes;
2383
2384         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2385
2386                 child = *niter;
2387
2388                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2389                         redirect_nodes.push_back(child);
2390                 }
2391
2392         }
2393
2394         set_processor_state_2X (redirect_nodes, version);
2395
2396         Stateful::save_extra_xml (node);
2397
2398         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2399                 child = *niter;
2400
2401                 if (child->name() == X_("Comment")) {
2402
2403                         /* XXX this is a terrible API design in libxml++ */
2404
2405                         XMLNode *cmt = *(child->children().begin());
2406                         _comment = cmt->content();
2407
2408                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
2409                         if (prop->value() == X_("solo")) {
2410                                 _solo_control->set_state (*child, version);
2411                         } else if (prop->value() == X_("mute")) {
2412                                 _mute_control->set_state (*child, version);
2413                         }
2414
2415                 } else if (child->name() == X_("RemoteControl")) {
2416                         if ((prop = child->property (X_("id"))) != 0) {
2417                                 int32_t x;
2418                                 sscanf (prop->value().c_str(), "%d", &x);
2419                                 set_remote_control_id_internal (x);
2420                         }
2421
2422                 }
2423         }
2424
2425         return 0;
2426 }
2427
2428 XMLNode&
2429 Route::get_processor_state ()
2430 {
2431         XMLNode* root = new XMLNode (X_("redirects"));
2432         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2433                 root->add_child_nocopy ((*i)->state (true));
2434         }
2435
2436         return *root;
2437 }
2438
2439 void
2440 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2441 {
2442         /* We don't bother removing existing processors not in nList, as this
2443            method will only be called when creating a Route from scratch, not
2444            for undo purposes.  Just put processors in at the appropriate place
2445            in the list.
2446         */
2447
2448         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2449                 add_processor_from_xml_2X (**i, version);
2450         }
2451 }
2452
2453 void
2454 Route::set_processor_state (const XMLNode& node)
2455 {
2456         const XMLNodeList &nlist = node.children();
2457         XMLNodeConstIterator niter;
2458         ProcessorList new_order;
2459         bool must_configure = false;
2460
2461         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2462
2463                 XMLProperty* prop = (*niter)->property ("type");
2464
2465                 if (prop->value() == "amp") {
2466                         _amp->set_state (**niter, Stateful::current_state_version);
2467                         new_order.push_back (_amp);
2468                 } else if (prop->value() == "meter") {
2469                         _meter->set_state (**niter, Stateful::current_state_version);
2470                         new_order.push_back (_meter);
2471                 } else if (prop->value() == "main-outs") {
2472                         _main_outs->set_state (**niter, Stateful::current_state_version);
2473                 } else if (prop->value() == "intreturn") {
2474                         if (!_intreturn) {
2475                                 _intreturn.reset (new InternalReturn (_session));
2476                                 must_configure = true;
2477                         }
2478                         _intreturn->set_state (**niter, Stateful::current_state_version);
2479                 } else if (is_monitor() && prop->value() == "monitor") {
2480                         if (!_monitor_control) {
2481                                 _monitor_control.reset (new MonitorProcessor (_session));
2482                                 must_configure = true;
2483                         }
2484                         _monitor_control->set_state (**niter, Stateful::current_state_version);
2485                 } else if (prop->value() == "capture") {
2486                         /* CapturingProcessor should never be restored, it's always
2487                            added explicitly when needed */
2488                 } else {
2489                         ProcessorList::iterator o;
2490
2491                         for (o = _processors.begin(); o != _processors.end(); ++o) {
2492                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2493                                 if (id_prop && (*o)->id() == id_prop->value()) {
2494                                         (*o)->set_state (**niter, Stateful::current_state_version);
2495                                         new_order.push_back (*o);
2496                                         break;
2497                                 }
2498                         }
2499
2500                         // If the processor (*niter) is not on the route then create it
2501
2502                         if (o == _processors.end()) {
2503
2504                                 boost::shared_ptr<Processor> processor;
2505
2506                                 if (prop->value() == "intsend") {
2507
2508                                         processor.reset (new InternalSend (_session, _pannable, _mute_master, boost::shared_ptr<Route>(), Delivery::Role (0)));
2509
2510                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
2511                                            prop->value() == "lv2" ||
2512                                            prop->value() == "windows-vst" ||
2513                                            prop->value() == "lxvst" ||
2514                                            prop->value() == "audiounit") {
2515
2516                                         processor.reset (new PluginInsert(_session));
2517
2518                                 } else if (prop->value() == "port") {
2519
2520                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
2521
2522                                 } else if (prop->value() == "send") {
2523
2524                                         processor.reset (new Send (_session, _pannable, _mute_master));
2525
2526                                 } else {
2527                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
2528                                         continue;
2529                                 }
2530
2531                                 if (processor->set_state (**niter, Stateful::current_state_version) != 0) {
2532                                         /* This processor could not be configured.  Turn it into a UnknownProcessor */
2533                                         processor.reset (new UnknownProcessor (_session, **niter));
2534                                 }
2535
2536                                 /* we have to note the monitor send here, otherwise a new one will be created
2537                                    and the state of this one will be lost.
2538                                 */
2539                                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
2540                                 if (isend && isend->role() == Delivery::Listen) {
2541                                         _monitor_send = isend;
2542                                 }
2543
2544                                 /* it doesn't matter if invisible processors are added here, as they
2545                                    will be sorted out by setup_invisible_processors () shortly.
2546                                 */
2547
2548                                 new_order.push_back (processor);
2549                                 must_configure = true;
2550                         }
2551                 }
2552         }
2553
2554         {
2555                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2556                 _processors = new_order;
2557
2558                 if (must_configure) {
2559                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2560                         configure_processors_unlocked (0);
2561                 }
2562
2563                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2564
2565                         (*i)->set_owner (this);
2566                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
2567
2568                         boost::shared_ptr<PluginInsert> pi;
2569
2570                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
2571                                 if (pi->has_no_inputs ()) {
2572                                         _have_internal_generator = true;
2573                                         break;
2574                                 }
2575                         }
2576                 }
2577         }
2578
2579         reset_instrument_info ();
2580         processors_changed (RouteProcessorChange ());
2581         set_processor_positions ();
2582 }
2583
2584 void
2585 Route::curve_reallocate ()
2586 {
2587 //      _gain_automation_curve.finish_resize ();
2588 //      _pan_automation_curve.finish_resize ();
2589 }
2590
2591 void
2592 Route::silence (framecnt_t nframes)
2593 {
2594         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
2595         if (!lm.locked()) {
2596                 return;
2597         }
2598
2599         silence_unlocked (nframes);
2600 }
2601
2602 void
2603 Route::silence_unlocked (framecnt_t nframes)
2604 {
2605         /* Must be called with the processor lock held */
2606
2607         if (!_silent) {
2608
2609                 _output->silence (nframes);
2610
2611                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2612                         boost::shared_ptr<PluginInsert> pi;
2613
2614                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2615                                 // skip plugins, they don't need anything when we're not active
2616                                 continue;
2617                         }
2618
2619                         (*i)->silence (nframes);
2620                 }
2621
2622                 if (nframes == _session.get_block_size()) {
2623                         // _silent = true;
2624                 }
2625         }
2626 }
2627
2628 void
2629 Route::add_internal_return ()
2630 {
2631         if (!_intreturn) {
2632                 _intreturn.reset (new InternalReturn (_session));
2633                 add_processor (_intreturn, PreFader);
2634         }
2635 }
2636
2637 void
2638 Route::add_send_to_internal_return (InternalSend* send)
2639 {
2640         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
2641
2642         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2643                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2644
2645                 if (d) {
2646                         return d->add_send (send);
2647                 }
2648         }
2649 }
2650
2651 void
2652 Route::remove_send_from_internal_return (InternalSend* send)
2653 {
2654         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
2655
2656         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2657                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2658
2659                 if (d) {
2660                         return d->remove_send (send);
2661                 }
2662         }
2663 }
2664
2665 void
2666 Route::enable_monitor_send ()
2667 {
2668         /* Caller must hold process lock */
2669         assert (!AudioEngine::instance()->process_lock().trylock());
2670
2671         /* master never sends to monitor section via the normal mechanism */
2672         assert (!is_master ());
2673
2674         /* make sure we have one */
2675         if (!_monitor_send) {
2676                 _monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, _session.monitor_out(), Delivery::Listen));
2677                 _monitor_send->set_display_to_user (false);
2678         }
2679
2680         /* set it up */
2681         configure_processors (0);
2682 }
2683
2684 /** Add an aux send to a route.
2685  *  @param route route to send to.
2686  *  @param before Processor to insert before, or 0 to insert at the end.
2687  */
2688 int
2689 Route::add_aux_send (boost::shared_ptr<Route> route, boost::shared_ptr<Processor> before)
2690 {
2691         assert (route != _session.monitor_out ());
2692
2693         {
2694                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
2695
2696                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2697
2698                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
2699
2700                         if (d && d->target_route() == route) {
2701                                 /* already listening via the specified IO: do nothing */
2702                                 return 0;
2703                         }
2704                 }
2705         }
2706
2707         try {
2708
2709                 boost::shared_ptr<InternalSend> listener;
2710
2711                 {
2712                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2713                         listener.reset (new InternalSend (_session, _pannable, _mute_master, route, Delivery::Aux));
2714                 }
2715
2716                 add_processor (listener, before);
2717
2718         } catch (failed_constructor& err) {
2719                 return -1;
2720         }
2721
2722         return 0;
2723 }
2724
2725 void
2726 Route::remove_aux_or_listen (boost::shared_ptr<Route> route)
2727 {
2728         ProcessorStreams err;
2729         ProcessorList::iterator tmp;
2730
2731         {
2732                 Glib::Threads::RWLock::ReaderLock rl(_processor_lock);
2733
2734                 /* have to do this early because otherwise processor reconfig
2735                  * will put _monitor_send back in the list
2736                  */
2737
2738                 if (route == _session.monitor_out()) {
2739                         _monitor_send.reset ();
2740                 }
2741
2742           again:
2743                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2744                         
2745                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2746                         
2747                         if (d && d->target_route() == route) {
2748                                 rl.release ();
2749                                 remove_processor (*x, &err, false);
2750                                 rl.acquire ();
2751
2752                                 /* list could have been demolished while we dropped the lock
2753                                    so start over.
2754                                 */
2755                                 
2756                                 goto again;
2757                         }
2758                 }
2759         }
2760 }
2761
2762 void
2763 Route::set_comment (string cmt, void *src)
2764 {
2765         _comment = cmt;
2766         comment_changed (src);
2767         _session.set_dirty ();
2768 }
2769
2770 bool
2771 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
2772 {
2773         FeedRecord fr (other, via_sends_only);
2774
2775         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
2776
2777         if (!result.second) {
2778
2779                 /* already a record for "other" - make sure sends-only information is correct */
2780                 if (!via_sends_only && result.first->sends_only) {
2781                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
2782                         frp->sends_only = false;
2783                 }
2784         }
2785
2786         return result.second;
2787 }
2788
2789 void
2790 Route::clear_fed_by ()
2791 {
2792         _fed_by.clear ();
2793 }
2794
2795 bool
2796 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
2797 {
2798         const FedBy& fed_by (other->fed_by());
2799
2800         for (FedBy::iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
2801                 boost::shared_ptr<Route> sr = f->r.lock();
2802
2803                 if (sr && (sr.get() == this)) {
2804
2805                         if (via_sends_only) {
2806                                 *via_sends_only = f->sends_only;
2807                         }
2808
2809                         return true;
2810                 }
2811         }
2812
2813         return false;
2814 }
2815
2816 bool
2817 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
2818 {
2819         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2820
2821         if (_output->connected_to (other->input())) {
2822                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2823                 if (via_send_only) {
2824                         *via_send_only = false;
2825                 }
2826
2827                 return true;
2828         }
2829
2830
2831         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
2832
2833                 boost::shared_ptr<IOProcessor> iop;
2834
2835                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2836                         if (iop->feeds (other)) {
2837                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2838                                 if (via_send_only) {
2839                                         *via_send_only = true;
2840                                 }
2841                                 return true;
2842                         } else {
2843                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2844                         }
2845                 } else {
2846                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2847                 }
2848
2849         }
2850
2851         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2852         return false;
2853 }
2854
2855 bool
2856 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
2857 {
2858         return _session._current_route_graph.has (shared_from_this (), other, via_send_only);
2859 }
2860
2861 /** Called from the (non-realtime) butler thread when the transport is stopped */
2862 void
2863 Route::nonrealtime_handle_transport_stopped (bool /*abort_ignored*/, bool /*did_locate*/, bool can_flush_processors)
2864 {
2865         framepos_t now = _session.transport_frame();
2866
2867         {
2868                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2869
2870                 Automatable::transport_stopped (now);
2871
2872                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2873
2874                         if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && can_flush_processors)) {
2875                                 (*i)->flush ();
2876                         }
2877
2878                         (*i)->transport_stopped (now);
2879                 }
2880         }
2881
2882         _roll_delay = _initial_delay;
2883 }
2884
2885 void
2886 Route::input_change_handler (IOChange change, void * /*src*/)
2887 {
2888         bool need_to_queue_solo_change = true;
2889
2890         if ((change.type & IOChange::ConfigurationChanged)) {
2891                 /* This is called with the process lock held if change 
2892                    contains ConfigurationChanged 
2893                 */
2894                 need_to_queue_solo_change = false;
2895                 configure_processors (0);
2896                 _phase_invert.resize (_input->n_ports().n_audio ());
2897                 io_changed (); /* EMIT SIGNAL */
2898         }
2899
2900         if (!_input->connected() && _soloed_by_others_upstream) {
2901                 if (need_to_queue_solo_change) {
2902                         _session.cancel_solo_after_disconnect (shared_from_this(), true);
2903                 } else {
2904                         cancel_solo_after_disconnect (true);
2905                 }
2906         }
2907 }
2908
2909 void
2910 Route::output_change_handler (IOChange change, void * /*src*/)
2911 {
2912         bool need_to_queue_solo_change = true;
2913         if (_initial_io_setup) {
2914                 return;
2915         }
2916
2917         if ((change.type & IOChange::ConfigurationChanged)) {
2918                 /* This is called with the process lock held if change 
2919                    contains ConfigurationChanged 
2920                 */
2921                 need_to_queue_solo_change = false;
2922                 configure_processors (0);
2923                 io_changed (); /* EMIT SIGNAL */
2924         }
2925
2926         if (!_output->connected() && _soloed_by_others_downstream) {
2927                 if (need_to_queue_solo_change) {
2928                         _session.cancel_solo_after_disconnect (shared_from_this(), false);
2929                 } else {
2930                         cancel_solo_after_disconnect (false);
2931                 }
2932         }
2933 }
2934
2935 void
2936 Route::cancel_solo_after_disconnect (bool upstream)
2937 {
2938         if (upstream) {
2939                 _soloed_by_others_upstream = 0;
2940         } else {
2941                 _soloed_by_others_downstream = 0;
2942         }
2943         set_mute_master_solo ();
2944         solo_changed (false, this);
2945 }
2946
2947 uint32_t
2948 Route::pans_required () const
2949 {
2950         if (n_outputs().n_audio() < 2) {
2951                 return 0;
2952         }
2953
2954         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2955 }
2956
2957 int
2958 Route::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool session_state_changing)
2959 {
2960         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
2961
2962         if (!lm.locked()) {
2963                 return 0;
2964         }
2965
2966         if (n_outputs().n_total() == 0) {
2967                 return 0;
2968         }
2969
2970         if (!_active || n_inputs() == ChanCount::ZERO)  {
2971                 silence_unlocked (nframes);
2972                 return 0;
2973         }
2974
2975         if (session_state_changing) {
2976                 if (_session.transport_speed() != 0.0f) {
2977                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2978                            so we cannot use them. Be silent till this is over.
2979
2980                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2981                         */
2982                         silence_unlocked (nframes);
2983                         return 0;
2984                 }
2985                 /* we're really not rolling, so we're either delivery silence or actually
2986                    monitoring, both of which are safe to do while session_state_changing is true.
2987                 */
2988         }
2989
2990         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
2991
2992         fill_buffers_with_input (bufs, _input, nframes);
2993
2994         if (_meter_point == MeterInput) {
2995                 _meter->run (bufs, start_frame, end_frame, nframes, true);
2996         }
2997
2998         _amp->apply_gain_automation (false);
2999         passthru (bufs, start_frame, end_frame, nframes, 0);
3000
3001         return 0;
3002 }
3003
3004 int
3005 Route::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& /* need_butler */)
3006 {
3007         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3008         if (!lm.locked()) {
3009                 return 0;
3010         }
3011
3012         if (n_outputs().n_total() == 0) {
3013                 return 0;
3014         }
3015
3016         if (!_active || n_inputs().n_total() == 0) {
3017                 silence_unlocked (nframes);
3018                 return 0;
3019         }
3020
3021         framepos_t unused = 0;
3022
3023         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
3024                 return 0;
3025         }
3026
3027         _silent = false;
3028
3029         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
3030
3031         fill_buffers_with_input (bufs, _input, nframes);
3032
3033         if (_meter_point == MeterInput) {
3034                 _meter->run (bufs, start_frame, end_frame, nframes, true);
3035         }
3036
3037         passthru (bufs, start_frame, end_frame, nframes, declick);
3038
3039         return 0;
3040 }
3041
3042 int
3043 Route::silent_roll (pframes_t nframes, framepos_t /*start_frame*/, framepos_t /*end_frame*/, bool& /* need_butler */)
3044 {
3045         silence (nframes);
3046         return 0;
3047 }
3048
3049 void
3050 Route::flush_processors ()
3051 {
3052         /* XXX shouldn't really try to take this lock, since
3053            this is called from the RT audio thread.
3054         */
3055
3056         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3057
3058         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3059                 (*i)->flush ();
3060         }
3061 }
3062
3063 void
3064 Route::set_meter_point (MeterPoint p, bool force)
3065 {
3066         if (_meter_point == p && !force) {
3067                 return;
3068         }
3069
3070         bool meter_was_visible_to_user = _meter->display_to_user ();
3071
3072         {
3073                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3074
3075                 maybe_note_meter_position ();
3076
3077                 _meter_point = p;
3078
3079                 if (_meter_point != MeterCustom) {
3080
3081                         _meter->set_display_to_user (false);
3082
3083                         setup_invisible_processors ();
3084
3085                 } else {
3086
3087                         _meter->set_display_to_user (true);
3088
3089                         /* If we have a previous position for the custom meter, try to put it there */
3090                         if (_custom_meter_position_noted) {
3091                                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
3092                                 
3093                                 if (after) {
3094                                         ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
3095                                         if (i != _processors.end ()) {
3096                                                 _processors.remove (_meter);
3097                                                 _processors.insert (i, _meter);
3098                                         }
3099                                 } else if (_last_custom_meter_was_at_end) {
3100                                         _processors.remove (_meter);
3101                                         _processors.push_back (_meter);
3102                                 }
3103                         }
3104                 }
3105
3106                 /* Set up the meter for its new position */
3107
3108                 ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
3109                 
3110                 ChanCount m_in;
3111                 
3112                 if (loc == _processors.begin()) {
3113                         m_in = _input->n_ports();
3114                 } else {
3115                         ProcessorList::iterator before = loc;
3116                         --before;
3117                         m_in = (*before)->output_streams ();
3118                 }
3119                 
3120                 _meter->reflect_inputs (m_in);
3121                 
3122                 /* we do not need to reconfigure the processors, because the meter
3123                    (a) is always ready to handle processor_max_streams
3124                    (b) is always an N-in/N-out processor, and thus moving
3125                    it doesn't require any changes to the other processors.
3126                 */
3127         }
3128
3129         meter_change (); /* EMIT SIGNAL */
3130
3131         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
3132
3133         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
3134 }
3135
3136 void
3137 Route::listen_position_changed ()
3138 {
3139         {
3140                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3141                 ProcessorState pstate (this);
3142
3143                 {
3144                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3145
3146                         if (configure_processors_unlocked (0)) {
3147                                 pstate.restore ();
3148                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
3149                                 return;
3150                         }
3151                 }
3152         }
3153
3154         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3155         _session.set_dirty ();
3156 }
3157
3158 boost::shared_ptr<CapturingProcessor>
3159 Route::add_export_point()
3160 {
3161         if (!_capturing_processor) {
3162
3163                 _capturing_processor.reset (new CapturingProcessor (_session));
3164                 _capturing_processor->activate ();
3165
3166                 {
3167                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3168                         configure_processors (0);
3169                 }
3170
3171         }
3172
3173         return _capturing_processor;
3174 }
3175
3176 framecnt_t
3177 Route::update_signal_latency ()
3178 {
3179         framecnt_t l = _output->user_latency();
3180
3181         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3182                 if ((*i)->active ()) {
3183                         l += (*i)->signal_latency ();
3184                 }
3185         }
3186
3187         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal signal latency = %2\n", _name, l));
3188
3189         if (_signal_latency != l) {
3190                 _signal_latency = l;
3191                 signal_latency_changed (); /* EMIT SIGNAL */
3192         }
3193
3194         return _signal_latency;
3195 }
3196
3197 void
3198 Route::set_user_latency (framecnt_t nframes)
3199 {
3200         _output->set_user_latency (nframes);
3201         _session.update_latency_compensation ();
3202 }
3203
3204 void
3205 Route::set_latency_compensation (framecnt_t longest_session_latency)
3206 {
3207         framecnt_t old = _initial_delay;
3208
3209         if (_signal_latency < longest_session_latency) {
3210                 _initial_delay = longest_session_latency - _signal_latency;
3211         } else {
3212                 _initial_delay = 0;
3213         }
3214
3215         DEBUG_TRACE (DEBUG::Latency, string_compose (
3216                              "%1: compensate for maximum latency of %2,"
3217                              "given own latency of %3, using initial delay of %4\n",
3218                              name(), longest_session_latency, _signal_latency, _initial_delay));
3219
3220         if (_initial_delay != old) {
3221                 initial_delay_changed (); /* EMIT SIGNAL */
3222         }
3223
3224         if (_session.transport_stopped()) {
3225                 _roll_delay = _initial_delay;
3226         }
3227 }
3228
3229 Route::SoloControllable::SoloControllable (std::string name, boost::shared_ptr<Route> r)
3230         : AutomationControl (r->session(), Evoral::Parameter (SoloAutomation),
3231                              boost::shared_ptr<AutomationList>(), name)
3232         , _route (r)
3233 {
3234         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
3235         set_list (gl);
3236 }
3237
3238 void
3239 Route::SoloControllable::set_value (double val)
3240 {
3241         bool bval = ((val >= 0.5f) ? true: false);
3242
3243         boost::shared_ptr<RouteList> rl (new RouteList);
3244
3245         boost::shared_ptr<Route> r = _route.lock ();
3246         if (!r) {
3247                 return;
3248         }
3249
3250         rl->push_back (r);
3251
3252         if (Config->get_solo_control_is_listen_control()) {
3253                 _session.set_listen (rl, bval);
3254         } else {
3255                 _session.set_solo (rl, bval);
3256         }
3257 }
3258
3259 double
3260 Route::SoloControllable::get_value () const
3261 {
3262         boost::shared_ptr<Route> r = _route.lock ();
3263         if (!r) {
3264                 return 0;
3265         }
3266
3267         if (Config->get_solo_control_is_listen_control()) {
3268                 return r->listening_via_monitor() ? 1.0f : 0.0f;
3269         } else {
3270                 return r->self_soloed() ? 1.0f : 0.0f;
3271         }
3272 }
3273
3274 Route::MuteControllable::MuteControllable (std::string name, boost::shared_ptr<Route> r)
3275         : AutomationControl (r->session(), Evoral::Parameter (MuteAutomation),
3276                              boost::shared_ptr<AutomationList>(), name)
3277         , _route (r)
3278 {
3279         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
3280         set_list (gl);
3281 }
3282
3283 void
3284 Route::MuteControllable::set_value (double val)
3285 {
3286         bool bval = ((val >= 0.5f) ? true: false);
3287
3288         boost::shared_ptr<RouteList> rl (new RouteList);
3289
3290         boost::shared_ptr<Route> r = _route.lock ();
3291         if (!r) {
3292                 return;
3293         }
3294
3295         rl->push_back (r);
3296         _session.set_mute (rl, bval);
3297 }
3298
3299 double
3300 Route::MuteControllable::get_value () const
3301 {
3302         boost::shared_ptr<Route> r = _route.lock ();
3303         if (!r) {
3304                 return 0;
3305         }
3306
3307         return r->muted() ? 1.0f : 0.0f;
3308 }
3309
3310 void
3311 Route::set_block_size (pframes_t nframes)
3312 {
3313         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3314                 (*i)->set_block_size (nframes);
3315         }
3316
3317         _session.ensure_buffers (n_process_buffers ());
3318 }
3319
3320 void
3321 Route::protect_automation ()
3322 {
3323         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3324                 (*i)->protect_automation();
3325 }
3326
3327 /** @param declick 1 to set a pending declick fade-in,
3328  *                -1 to set a pending declick fade-out
3329  */
3330 void
3331 Route::set_pending_declick (int declick)
3332 {
3333         if (_declickable) {
3334                 /* this call is not allowed to turn off a pending declick */
3335                 if (declick) {
3336                         _pending_declick = declick;
3337                 }
3338         } else {
3339                 _pending_declick = 0;
3340         }
3341 }
3342
3343 /** Shift automation forwards from a particular place, thereby inserting time.
3344  *  Adds undo commands for any shifts that are performed.
3345  *
3346  * @param pos Position to start shifting from.
3347  * @param frames Amount to shift forwards by.
3348  */
3349
3350 void
3351 Route::shift (framepos_t pos, framecnt_t frames)
3352 {
3353         /* gain automation */
3354         {
3355                 boost::shared_ptr<AutomationControl> gc = _amp->gain_control();
3356
3357                 XMLNode &before = gc->alist()->get_state ();
3358                 gc->alist()->shift (pos, frames);
3359                 XMLNode &after = gc->alist()->get_state ();
3360                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
3361         }
3362
3363         /* pan automation */
3364         if (_pannable) {
3365                 ControlSet::Controls& c (_pannable->controls());
3366
3367                 for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
3368                         boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
3369                         if (pc) {
3370                                 boost::shared_ptr<AutomationList> al = pc->alist();
3371                                 XMLNode& before = al->get_state ();
3372                                 al->shift (pos, frames);
3373                                 XMLNode& after = al->get_state ();
3374                                 _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
3375                         }
3376                 }
3377         }
3378
3379         /* redirect automation */
3380         {
3381                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3382                 for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
3383
3384                         set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
3385
3386                         for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
3387                                 boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
3388                                 if (ac) {
3389                                         boost::shared_ptr<AutomationList> al = ac->alist();
3390                                         XMLNode &before = al->get_state ();
3391                                         al->shift (pos, frames);
3392                                         XMLNode &after = al->get_state ();
3393                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
3394                                 }
3395                         }
3396                 }
3397         }
3398 }
3399
3400
3401 int
3402 Route::save_as_template (const string& path, const string& name)
3403 {
3404         XMLNode& node (state (false));
3405         XMLTree tree;
3406
3407         IO::set_name_in_state (*node.children().front(), name);
3408
3409         tree.set_root (&node);
3410         return tree.write (path.c_str());
3411 }
3412
3413
3414 bool
3415 Route::set_name (const string& str)
3416 {
3417         bool ret;
3418         string ioproc_name;
3419         string name;
3420
3421         name = Route::ensure_track_or_route_name (str, _session);
3422         SessionObject::set_name (name);
3423
3424         ret = (_input->set_name(name) && _output->set_name(name));
3425
3426         if (ret) {
3427                 /* rename the main outs. Leave other IO processors
3428                  * with whatever name they already have, because its
3429                  * just fine as it is (it will not contain the route
3430                  * name if its a port insert, port send or port return).
3431                  */
3432
3433                 if (_main_outs) {
3434                         if (_main_outs->set_name (name)) {
3435                                 /* XXX returning false here is stupid because
3436                                    we already changed the route name.
3437                                 */
3438                                 return false;
3439                         }
3440                 }
3441         }
3442
3443         return ret;
3444 }
3445
3446 /** Set the name of a route in an XML description.
3447  *  @param node XML <Route> node to set the name in.
3448  *  @param name New name.
3449  */
3450 void
3451 Route::set_name_in_state (XMLNode& node, string const & name)
3452 {
3453         node.add_property (X_("name"), name);
3454
3455         XMLNodeList children = node.children();
3456         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
3457                 
3458                 if ((*i)->name() == X_("IO")) {
3459
3460                         IO::set_name_in_state (**i, name);
3461
3462                 } else if ((*i)->name() == X_("Processor")) {
3463
3464                         XMLProperty* role = (*i)->property (X_("role"));
3465                         if (role && role->value() == X_("Main")) {
3466                                 (*i)->add_property (X_("name"), name);
3467                         }
3468                         
3469                 } else if ((*i)->name() == X_("Diskstream")) {
3470
3471                         (*i)->add_property (X_("playlist"), string_compose ("%1.1", name).c_str());
3472                         (*i)->add_property (X_("name"), name);
3473                         
3474                 }
3475         }
3476 }
3477
3478 boost::shared_ptr<Send>
3479 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3480 {
3481         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3482
3483         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3484                 boost::shared_ptr<InternalSend> send;
3485
3486                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3487                         if (send->target_route() == target) {
3488                                 return send;
3489                         }
3490                 }
3491         }
3492
3493         return boost::shared_ptr<Send>();
3494 }
3495
3496 /** @param c Audio channel index.
3497  *  @param yn true to invert phase, otherwise false.
3498  */
3499 void
3500 Route::set_phase_invert (uint32_t c, bool yn)
3501 {
3502         if (_phase_invert[c] != yn) {
3503                 _phase_invert[c] = yn;
3504                 phase_invert_changed (); /* EMIT SIGNAL */
3505                 _session.set_dirty ();
3506         }
3507 }
3508
3509 void
3510 Route::set_phase_invert (boost::dynamic_bitset<> p)
3511 {
3512         if (_phase_invert != p) {
3513                 _phase_invert = p;
3514                 phase_invert_changed (); /* EMIT SIGNAL */
3515                 _session.set_dirty ();
3516         }
3517 }
3518
3519 bool
3520 Route::phase_invert (uint32_t c) const
3521 {
3522         return _phase_invert[c];
3523 }
3524
3525 boost::dynamic_bitset<>
3526 Route::phase_invert () const
3527 {
3528         return _phase_invert;
3529 }
3530
3531 void
3532 Route::set_denormal_protection (bool yn)
3533 {
3534         if (_denormal_protection != yn) {
3535                 _denormal_protection = yn;
3536                 denormal_protection_changed (); /* EMIT SIGNAL */
3537         }
3538 }
3539
3540 bool
3541 Route::denormal_protection () const
3542 {
3543         return _denormal_protection;
3544 }
3545
3546 void
3547 Route::set_active (bool yn, void* src)
3548 {
3549         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
3550                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
3551                 return;
3552         }
3553
3554         if (_active != yn) {
3555                 _active = yn;
3556                 _input->set_active (yn);
3557                 _output->set_active (yn);
3558                 active_changed (); // EMIT SIGNAL
3559                 _session.set_dirty ();
3560         }
3561 }
3562
3563 void
3564 Route::meter ()
3565 {
3566         Glib::Threads::RWLock::ReaderLock rm (_processor_lock, Glib::Threads::TRY_LOCK);
3567
3568         assert (_meter);
3569
3570         _meter->meter ();
3571
3572         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3573
3574                 boost::shared_ptr<Send> s;
3575                 boost::shared_ptr<Return> r;
3576
3577                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3578                         s->meter()->meter();
3579                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3580                         r->meter()->meter ();
3581                 }
3582         }
3583 }
3584
3585 boost::shared_ptr<Pannable>
3586 Route::pannable() const
3587 {
3588         return _pannable;
3589 }
3590
3591 boost::shared_ptr<Panner>
3592 Route::panner() const
3593 {
3594         /* may be null ! */
3595         return _main_outs->panner_shell()->panner();
3596 }
3597
3598 boost::shared_ptr<PannerShell>
3599 Route::panner_shell() const
3600 {
3601         return _main_outs->panner_shell();
3602 }
3603
3604 boost::shared_ptr<AutomationControl>
3605 Route::gain_control() const
3606 {
3607         return _amp->gain_control();
3608 }
3609
3610 boost::shared_ptr<AutomationControl>
3611 Route::get_control (const Evoral::Parameter& param)
3612 {
3613         /* either we own the control or .... */
3614
3615         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3616
3617         if (!c) {
3618
3619                 /* maybe one of our processors does or ... */
3620
3621                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock, Glib::Threads::TRY_LOCK);
3622                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3623                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3624                                 break;
3625                         }
3626                 }
3627         }
3628
3629         if (!c) {
3630
3631                 /* nobody does so we'll make a new one */
3632
3633                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3634                 add_control(c);
3635         }
3636
3637         return c;
3638 }
3639
3640 boost::shared_ptr<Processor>
3641 Route::nth_plugin (uint32_t n)
3642 {
3643         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3644         ProcessorList::iterator i;
3645
3646         for (i = _processors.begin(); i != _processors.end(); ++i) {
3647                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3648                         if (n-- == 0) {
3649                                 return *i;
3650                         }
3651                 }
3652         }
3653
3654         return boost::shared_ptr<Processor> ();
3655 }
3656
3657 boost::shared_ptr<Processor>
3658 Route::nth_send (uint32_t n)
3659 {
3660         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3661         ProcessorList::iterator i;
3662
3663         for (i = _processors.begin(); i != _processors.end(); ++i) {
3664                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3665                         if (n-- == 0) {
3666                                 return *i;
3667                         }
3668                 }
3669         }
3670
3671         return boost::shared_ptr<Processor> ();
3672 }
3673
3674 bool
3675 Route::has_io_processor_named (const string& name)
3676 {
3677         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3678         ProcessorList::iterator i;
3679
3680         for (i = _processors.begin(); i != _processors.end(); ++i) {
3681                 if (boost::dynamic_pointer_cast<Send> (*i) ||
3682                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
3683                         if ((*i)->name() == name) {
3684                                 return true;
3685                         }
3686                 }
3687         }
3688
3689         return false;
3690 }
3691
3692 MuteMaster::MutePoint
3693 Route::mute_points () const
3694 {
3695         return _mute_master->mute_points ();
3696 }
3697
3698 void
3699 Route::set_processor_positions ()
3700 {
3701         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3702
3703         bool had_amp = false;
3704         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3705                 (*i)->set_pre_fader (!had_amp);
3706                 if (boost::dynamic_pointer_cast<Amp> (*i)) {
3707                         had_amp = true;
3708                 }
3709         }
3710 }
3711
3712 /** Called when there is a proposed change to the input port count */
3713 bool
3714 Route::input_port_count_changing (ChanCount to)
3715 {
3716         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
3717         if (c.empty()) {
3718                 /* The processors cannot be configured with the new input arrangement, so
3719                    block the change.
3720                 */
3721                 return true;
3722         }
3723
3724         /* The change is ok */
3725         return false;
3726 }
3727
3728 /** Called when there is a proposed change to the output port count */
3729 bool
3730 Route::output_port_count_changing (ChanCount to)
3731 {
3732         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3733                 if (processor_out_streams.get(*t) > to.get(*t)) {
3734                         return true;
3735                 }
3736         }
3737         /* The change is ok */
3738         return false;
3739 }
3740
3741 list<string>
3742 Route::unknown_processors () const
3743 {
3744         list<string> p;
3745
3746         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3747         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3748                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
3749                         p.push_back ((*i)->name ());
3750                 }
3751         }
3752
3753         return p;
3754 }
3755
3756
3757 framecnt_t
3758 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, framecnt_t our_latency) const
3759 {
3760         /* we assume that all our input ports feed all our output ports. its not
3761            universally true, but the alternative is way too corner-case to worry about.
3762         */
3763
3764         LatencyRange all_connections;
3765
3766         if (from.empty()) {
3767                 all_connections.min = 0;
3768                 all_connections.max = 0;
3769         } else {
3770                 all_connections.min = ~((pframes_t) 0);
3771                 all_connections.max = 0;
3772                 
3773                 /* iterate over all "from" ports and determine the latency range for all of their
3774                    connections to the "outside" (outside of this Route).
3775                 */
3776                 
3777                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
3778                         
3779                         LatencyRange range;
3780                         
3781                         p->get_connected_latency_range (range, playback);
3782                         
3783                         all_connections.min = min (all_connections.min, range.min);
3784                         all_connections.max = max (all_connections.max, range.max);
3785                 }
3786         }
3787
3788         /* set the "from" port latencies to the max/min range of all their connections */
3789
3790         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
3791                 p->set_private_latency_range (all_connections, playback);
3792         }
3793
3794         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
3795
3796         all_connections.min += our_latency;
3797         all_connections.max += our_latency;
3798
3799         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
3800                 p->set_private_latency_range (all_connections, playback);
3801         }
3802
3803         return all_connections.max;
3804 }
3805
3806 framecnt_t
3807 Route::set_private_port_latencies (bool playback) const
3808 {
3809         framecnt_t own_latency = 0;
3810
3811         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
3812            OR LATENCY CALLBACK.
3813
3814            This is called (early) from the latency callback. It computes the REAL
3815            latency associated with each port and stores the result as the "private"
3816            latency of the port. A later call to Route::set_public_port_latencies()
3817            sets all ports to the same value to reflect the fact that we do latency
3818            compensation and so all signals are delayed by the same amount as they
3819            flow through ardour.
3820         */
3821
3822         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3823                 if ((*i)->active ()) {
3824                         own_latency += (*i)->signal_latency ();
3825                 }
3826         }
3827
3828         if (playback) {
3829                 /* playback: propagate latency from "outside the route" to outputs to inputs */
3830                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
3831         } else {
3832                 /* capture: propagate latency from "outside the route" to inputs to outputs */
3833                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
3834         }
3835 }
3836
3837 void
3838 Route::set_public_port_latencies (framecnt_t value, bool playback) const
3839 {
3840         /* this is called to set the JACK-visible port latencies, which take
3841            latency compensation into account.
3842         */
3843
3844         LatencyRange range;
3845
3846         range.min = value;
3847         range.max = value;
3848
3849         {
3850                 const PortSet& ports (_input->ports());
3851                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
3852                         p->set_public_latency_range (range, playback);
3853                 }
3854         }
3855
3856         {
3857                 const PortSet& ports (_output->ports());
3858                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
3859                         p->set_public_latency_range (range, playback);
3860                 }
3861         }
3862 }
3863
3864 /** Put the invisible processors in the right place in _processors.
3865  *  Must be called with a writer lock on _processor_lock held.
3866  */
3867 void
3868 Route::setup_invisible_processors ()
3869 {
3870 #ifndef NDEBUG
3871         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3872         assert (!lm.locked ());
3873 #endif
3874
3875         if (!_main_outs) {
3876                 /* too early to be doing this stuff */
3877                 return;
3878         }
3879
3880         /* we'll build this new list here and then use it */
3881
3882         ProcessorList new_processors;
3883
3884         /* find visible processors */
3885
3886         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3887                 if ((*i)->display_to_user ()) {
3888                         new_processors.push_back (*i);
3889                 }
3890         }
3891
3892         /* find the amp */
3893
3894         ProcessorList::iterator amp = new_processors.begin ();
3895         while (amp != new_processors.end() && boost::dynamic_pointer_cast<Amp> (*amp) == 0) {
3896                 ++amp;
3897         }
3898
3899         assert (amp != _processors.end ());
3900
3901         /* and the processor after the amp */
3902
3903         ProcessorList::iterator after_amp = amp;
3904         ++after_amp;
3905
3906         /* METER */
3907
3908         if (_meter) {
3909                 switch (_meter_point) {
3910                 case MeterInput:
3911                         assert (!_meter->display_to_user ());
3912                         new_processors.push_front (_meter);
3913                         break;
3914                 case MeterPreFader:
3915                         assert (!_meter->display_to_user ());
3916                         new_processors.insert (amp, _meter);
3917                         break;
3918                 case MeterPostFader:
3919                         /* do nothing here */
3920                         break;
3921                 case MeterOutput:
3922                         /* do nothing here */
3923                         break;
3924                 case MeterCustom:
3925                         /* the meter is visible, so we don't touch it here */
3926                         break;
3927                 }
3928         }
3929
3930         /* MAIN OUTS */
3931
3932         assert (_main_outs);
3933         assert (!_main_outs->display_to_user ());
3934         new_processors.push_back (_main_outs);
3935
3936         /* iterator for the main outs */
3937
3938         ProcessorList::iterator main = new_processors.end();
3939         --main;
3940
3941         /* OUTPUT METERING */
3942
3943         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
3944                 assert (!_meter->display_to_user ());
3945
3946                 /* add the processor just before or just after the main outs */
3947
3948                 ProcessorList::iterator meter_point = main;
3949
3950                 if (_meter_point == MeterOutput) {
3951                         ++meter_point;
3952                 }
3953                 new_processors.insert (meter_point, _meter);
3954         }
3955
3956         /* MONITOR SEND */
3957
3958         if (_monitor_send && !is_monitor ()) {
3959                 assert (!_monitor_send->display_to_user ());
3960                 if (Config->get_solo_control_is_listen_control()) {
3961                         switch (Config->get_listen_position ()) {
3962                         case PreFaderListen:
3963                                 switch (Config->get_pfl_position ()) {
3964                                 case PFLFromBeforeProcessors:
3965                                         new_processors.push_front (_monitor_send);
3966                                         break;
3967                                 case PFLFromAfterProcessors:
3968                                         new_processors.insert (amp, _monitor_send);
3969                                         break;
3970                                 }
3971                                 _monitor_send->set_can_pan (false);
3972                                 break;
3973                         case AfterFaderListen:
3974                                 switch (Config->get_afl_position ()) {
3975                                 case AFLFromBeforeProcessors:
3976                                         new_processors.insert (after_amp, _monitor_send);
3977                                         break;
3978                                 case AFLFromAfterProcessors:
3979                                         new_processors.insert (new_processors.end(), _monitor_send);
3980                                         break;
3981                                 }
3982                                 _monitor_send->set_can_pan (true);
3983                                 break;
3984                         }
3985                 }  else {
3986                         new_processors.insert (new_processors.end(), _monitor_send);
3987                         _monitor_send->set_can_pan (false);
3988                 }
3989         }
3990
3991         /* MONITOR CONTROL */
3992
3993         if (_monitor_control && is_monitor ()) {
3994                 assert (!_monitor_control->display_to_user ());
3995                 new_processors.push_front (_monitor_control);
3996         }
3997
3998         /* INTERNAL RETURN */
3999
4000         /* doing this here means that any monitor control will come just after
4001            the return.
4002         */
4003
4004         if (_intreturn) {
4005                 assert (!_intreturn->display_to_user ());
4006                 new_processors.push_front (_intreturn);
4007         }
4008
4009         /* EXPORT PROCESSOR */
4010
4011         if (_capturing_processor) {
4012                 assert (!_capturing_processor->display_to_user ());
4013                 new_processors.push_front (_capturing_processor);
4014         }
4015
4016         _processors = new_processors;
4017
4018         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
4019         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4020                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
4021         }
4022 }
4023
4024 void
4025 Route::unpan ()
4026 {
4027         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
4028         Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
4029
4030         _pannable.reset ();
4031
4032         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4033                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
4034                 if (d) {
4035                         d->unpan ();
4036                 }
4037         }
4038 }
4039
4040 /** If the meter point is `Custom', make a note of where the meter is.
4041  *  This is so that if the meter point is subsequently set to something else,
4042  *  and then back to custom, we can put the meter back where it was last time
4043  *  custom was enabled.
4044  *
4045  *  Must be called with the _processor_lock held.
4046  */
4047 void
4048 Route::maybe_note_meter_position ()
4049 {
4050         if (_meter_point != MeterCustom) {
4051                 return;
4052         }
4053         
4054         _custom_meter_position_noted = true;
4055         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4056                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
4057                         ProcessorList::iterator j = i;
4058                         ++j;
4059                         if (j != _processors.end ()) {
4060                                 _processor_after_last_custom_meter = *j;
4061                                 _last_custom_meter_was_at_end = false;
4062                         } else {
4063                                 _last_custom_meter_was_at_end = true;
4064                         }
4065                 }
4066         }
4067 }
4068
4069 boost::shared_ptr<Processor>
4070 Route::processor_by_id (PBD::ID id) const
4071 {
4072         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4073         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4074                 if ((*i)->id() == id) {
4075                         return *i;
4076                 }
4077         }
4078
4079         return boost::shared_ptr<Processor> ();
4080 }
4081
4082 /** @return the monitoring state, or in other words what data we are pushing
4083  *  into the route (data from the inputs, data from disk or silence)
4084  */
4085 MonitorState
4086 Route::monitoring_state () const
4087 {
4088         return MonitoringInput;
4089 }
4090
4091 /** @return what we should be metering; either the data coming from the input
4092  *  IO or the data that is flowing through the route.
4093  */
4094 MeterState
4095 Route::metering_state () const
4096 {
4097         return MeteringRoute;
4098 }
4099
4100 bool
4101 Route::has_external_redirects () const
4102 {
4103         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4104
4105                 /* ignore inactive processors and obviously ignore the main
4106                  * outs since everything has them and we don't care.
4107                  */
4108                  
4109                 if ((*i)->active() && (*i) != _main_outs && (*i)->does_routing()) {
4110                         return true;;
4111                 }
4112         }
4113
4114         return false;
4115 }
4116
4117 boost::shared_ptr<Processor>
4118 Route::the_instrument () const
4119 {
4120         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4121         return the_instrument_unlocked ();
4122 }
4123
4124 boost::shared_ptr<Processor>
4125 Route::the_instrument_unlocked () const
4126 {
4127         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4128                 if (boost::dynamic_pointer_cast<PluginInsert>(*i)) {
4129                         if ((*i)->input_streams().n_midi() > 0 &&
4130                             (*i)->output_streams().n_audio() > 0) {
4131                                 return (*i);
4132                         }
4133                 }
4134         }
4135         return boost::shared_ptr<Processor>();
4136 }
4137
4138
4139
4140 void
4141 Route::non_realtime_locate (framepos_t pos)
4142 {
4143         if (_pannable) {
4144                 _pannable->transport_located (pos);
4145         }
4146
4147         {
4148                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4149                 
4150                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4151                         (*i)->transport_located (pos);
4152                 }
4153         }
4154 }
4155
4156 void
4157 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
4158 {
4159         size_t n_buffers;
4160         size_t i;
4161         
4162         /* MIDI 
4163          *  
4164          * We don't currently mix MIDI input together, so we don't need the
4165          * complex logic of the audio case.
4166          */
4167
4168         n_buffers = bufs.count().n_midi ();
4169
4170         for (i = 0; i < n_buffers; ++i) {
4171
4172                 boost::shared_ptr<MidiPort> source_port = io->midi (i);
4173                 MidiBuffer& buf (bufs.get_midi (i));
4174                 
4175                 if (source_port) {
4176                         buf.copy (source_port->get_midi_buffer(nframes));
4177                 } else {
4178                         buf.silence (nframes);
4179                 }
4180         }
4181
4182         /* AUDIO */
4183
4184         n_buffers = bufs.count().n_audio();
4185
4186         size_t n_ports = io->n_ports().n_audio();
4187         float scaling = 1.0f;
4188
4189         if (n_ports > n_buffers) {
4190                 scaling = ((float) n_buffers) / n_ports;
4191         }
4192         
4193         for (i = 0; i < n_ports; ++i) {
4194                 
4195                 /* if there are more ports than buffers, map them onto buffers
4196                  * in a round-robin fashion
4197                  */
4198
4199                 boost::shared_ptr<AudioPort> source_port = io->audio (i);
4200                 AudioBuffer& buf (bufs.get_audio (i%n_buffers));
4201                         
4202
4203                 if (i < n_buffers) {
4204                         
4205                         /* first time through just copy a channel into
4206                            the output buffer.
4207                         */
4208
4209                         buf.read_from (source_port->get_audio_buffer (nframes), nframes);
4210
4211                         if (scaling != 1.0f) {
4212                                 buf.apply_gain (scaling, nframes);
4213                         }
4214                         
4215                 } else {
4216                         
4217                         /* on subsequent times around, merge data from
4218                          * the port with what is already there 
4219                          */
4220
4221                         if (scaling != 1.0f) {
4222                                 buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
4223                         } else {
4224                                 buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
4225                         }
4226                 }
4227         }
4228
4229         /* silence any remaining buffers */
4230
4231         for (; i < n_buffers; ++i) {
4232                 AudioBuffer& buf (bufs.get_audio (i));
4233                 buf.silence (nframes);
4234         }
4235
4236         /* establish the initial setup of the buffer set, reflecting what was
4237            copied into it. unless, of course, we are the auditioner, in which
4238            case nothing was fed into it from the inputs at all.
4239         */
4240
4241         if (!is_auditioner()) {
4242                 bufs.set_count (io->n_ports());
4243         }
4244 }