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