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