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