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