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