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