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