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