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