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