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