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