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