239a189a0d205e1147c3a09bcf7aa2782c03604a
[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 #include <cmath>
21 #include <fstream>
22 #include <cassert>
23 #include <algorithm>
24
25 #include "pbd/xml++.h"
26 #include "pbd/enumwriter.h"
27 #include "pbd/memento_command.h"
28 #include "pbd/stacktrace.h"
29 #include "pbd/convert.h"
30
31 #include "evoral/Curve.hpp"
32
33 #include "ardour/amp.h"
34 #include "ardour/audio_port.h"
35 #include "ardour/audioengine.h"
36 #include "ardour/buffer.h"
37 #include "ardour/buffer_set.h"
38 #include "ardour/configuration.h"
39 #include "ardour/cycle_timer.h"
40 #include "ardour/debug.h"
41 #include "ardour/delivery.h"
42 #include "ardour/dB.h"
43 #include "ardour/internal_send.h"
44 #include "ardour/internal_return.h"
45 #include "ardour/ladspa_plugin.h"
46 #include "ardour/meter.h"
47 #include "ardour/mix.h"
48 #include "ardour/monitor_processor.h"
49 #include "ardour/panner.h"
50 #include "ardour/plugin_insert.h"
51 #include "ardour/port.h"
52 #include "ardour/port_insert.h"
53 #include "ardour/processor.h"
54 #include "ardour/profile.h"
55 #include "ardour/route.h"
56 #include "ardour/route_group.h"
57 #include "ardour/send.h"
58 #include "ardour/session.h"
59 #include "ardour/timestamps.h"
60 #include "ardour/utils.h"
61
62 #include "i18n.h"
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 uint32_t Route::order_key_cnt = 0;
69 PBD::Signal1<void,string const&> Route::SyncOrderKeys;
70 PBD::Signal0<void> Route::RemoteControlIDChange;
71
72 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
73         : SessionObject (sess, name)
74         , AutomatableControls (sess)
75         , _active (true)
76         , _initial_delay (0)
77         , _roll_delay (0)
78         , _flags (flg)
79         , _pending_declick (true)
80         , _meter_point (MeterPostFader)
81         , _phase_invert (0)
82         , _self_solo (false)
83         , _soloed_by_others (0)
84         , _solo_isolated (0)
85         , _denormal_protection (false)
86         , _recordable (true)
87         , _silent (false)
88         , _declickable (false)
89         , _solo_control (new SoloControllable (X_("solo"), *this))
90         , _mute_control (new MuteControllable (X_("mute"), *this))
91         , _mute_master (new MuteMaster (sess, name))
92         , _mute_points (MuteMaster::AllPoints)
93         , _have_internal_generator (false)
94         , _solo_safe (false)
95         , _default_type (default_type)
96         , _remote_control_id (0)
97         , _in_configure_processors (false)
98 {
99         processor_max_streams.reset();
100         order_keys[N_("signal")] = order_key_cnt++;
101 }
102
103 int
104 Route::init ()
105 {
106         /* add standard controls */
107
108         _solo_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
109         _mute_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
110         
111         add_control (_solo_control);
112         add_control (_mute_control);
113
114         /* input and output objects */
115
116         _input.reset (new IO (_session, _name, IO::Input, _default_type));
117         _output.reset (new IO (_session, _name, IO::Output, _default_type));
118
119         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
120         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
121
122         /* add amp processor  */
123
124         _amp.reset (new Amp (_session, _mute_master));
125         add_processor (_amp, PostFader);
126
127         /* add standard processors: meter, main outs, monitor out */
128
129         _meter.reset (new PeakMeter (_session));
130         _meter->set_display_to_user (false);
131
132         add_processor (_meter, PostFader);
133
134         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
135
136         add_processor (_main_outs, PostFader);
137
138         if (is_monitor()) {
139                 /* where we listen to tracks */
140                 _intreturn.reset (new InternalReturn (_session));
141                 add_processor (_intreturn, PreFader);
142
143                 ProcessorList::iterator i;
144
145                 for (i = _processors.begin(); i != _processors.end(); ++i) {
146                         if (*i == _intreturn) {
147                                 ++i;
148                                 break;
149                         }
150                 }
151
152                 /* the thing that provides proper control over a control/monitor/listen bus 
153                    (such as per-channel cut, dim, solo, invert, etc).
154                    It always goes right after the internal return;
155                  */
156                 _monitor_control.reset (new MonitorProcessor (_session));
157                 add_processor (_monitor_control, i);
158
159                 /* no panning on the monitor main outs */
160
161                 _main_outs->panner()->set_bypassed (true);
162         }
163
164         markup_solo_ignore ();
165
166         /* now that we have _meter, its safe to connect to this */
167
168         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
169
170         return 0;
171 }
172
173 Route::~Route ()
174 {
175         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
176
177         /* do this early so that we don't get incoming signals as we are going through destruction 
178          */
179
180         drop_connections ();
181
182         /* don't use clear_processors here, as it depends on the session which may
183            be half-destroyed by now 
184         */
185
186         Glib::RWLock::WriterLock lm (_processor_lock);
187         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
188                 (*i)->drop_references ();
189         }
190
191         _processors.clear ();
192 }
193
194 void
195 Route::set_remote_control_id (uint32_t id, bool notify_class_listeners)
196 {
197         if (id != _remote_control_id) {
198                 _remote_control_id = id;
199                 RemoteControlIDChanged ();
200                 if (notify_class_listeners) {
201                         RemoteControlIDChange ();
202                 }
203         }
204 }
205
206 uint32_t
207 Route::remote_control_id() const
208 {
209         return _remote_control_id;
210 }
211
212 long
213 Route::order_key (std::string const & name) const
214 {
215         OrderKeys::const_iterator i = order_keys.find (name);
216         if (i == order_keys.end()) {
217                 return -1;
218         }
219
220         return i->second;
221 }
222
223 void
224 Route::set_order_key (std::string const & name, long n)
225 {
226         order_keys[name] = n;
227
228         if (Config->get_sync_all_route_ordering()) {
229                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
230                         x->second = n;
231                 }
232         }
233
234         _session.set_dirty ();
235 }
236
237 /** Set all order keys to be the same as that for `base', if such a key
238  *  exists in this route.
239  *  @param base Base key.
240  */
241 void
242 Route::sync_order_keys (std::string const & base)
243 {
244         if (order_keys.empty()) {
245                 return;
246         }
247
248         OrderKeys::iterator i;
249         uint32_t key;
250
251         if ((i = order_keys.find (base)) == order_keys.end()) {
252                 /* key doesn't exist, use the first existing key (during session initialization) */
253                 i = order_keys.begin();
254                 key = i->second;
255                 ++i;
256         } else {
257                 /* key exists - use it and reset all others (actually, itself included) */
258                 key = i->second;
259                 i = order_keys.begin();
260         }
261
262         for (; i != order_keys.end(); ++i) {
263                 i->second = key;
264         }
265 }
266
267 string
268 Route::ensure_track_or_route_name(string name, Session &session)
269 {
270         string newname = name;
271
272         while (!session.io_name_is_legal (newname)) {
273                 newname = bump_name_once (newname);
274         }
275
276         return newname;
277 }
278
279
280 void
281 Route::inc_gain (gain_t fraction, void *src)
282 {
283         _amp->inc_gain (fraction, src);
284 }
285
286 void
287 Route::set_gain (gain_t val, void *src)
288 {
289         if (src != 0 && _route_group && src != _route_group && _route_group->is_active() && _route_group->is_gain()) {
290
291                 if (_route_group->is_relative()) {
292
293                         gain_t usable_gain = _amp->gain();
294                         if (usable_gain < 0.000001f) {
295                                 usable_gain = 0.000001f;
296                         }
297
298                         gain_t delta = val;
299                         if (delta < 0.000001f) {
300                                 delta = 0.000001f;
301                         }
302
303                         delta -= usable_gain;
304
305                         if (delta == 0.0f)
306                                 return;
307
308                         gain_t factor = delta / usable_gain;
309
310                         if (factor > 0.0f) {
311                                 factor = _route_group->get_max_factor(factor);
312                                 if (factor == 0.0f) {
313                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
314                                         return;
315                                 }
316                         } else {
317                                 factor = _route_group->get_min_factor(factor);
318                                 if (factor == 0.0f) {
319                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
320                                         return;
321                                 }
322                         }
323
324                         _route_group->apply (&Route::inc_gain, factor, _route_group);
325
326                 } else {
327
328                         _route_group->apply (&Route::set_gain, val, _route_group);
329                 }
330
331                 return;
332         }
333
334         if (val == _amp->gain()) {
335                 return;
336         }
337
338         _amp->set_gain (val, src);
339 }
340
341 /** Process this route for one (sub) cycle (process thread)
342  *
343  * @param bufs Scratch buffers to use for the signal path
344  * @param start_frame Initial transport frame
345  * @param end_frame Final transport frame
346  * @param nframes Number of frames to output (to ports)
347  *
348  * Note that (end_frame - start_frame) may not be equal to nframes when the
349  * transport speed isn't 1.0 (eg varispeed).
350  */
351 void
352 Route::process_output_buffers (BufferSet& bufs,
353                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
354                                bool /*with_processors*/, int declick)
355 {
356         bool monitor;
357
358         bufs.is_silent (false);
359
360         switch (Config->get_monitoring_model()) {
361         case HardwareMonitoring:
362         case ExternalMonitoring:
363                 monitor = !record_enabled() || (_session.config.get_auto_input() && !_session.actively_recording());
364                 break;
365         default:
366                 monitor = true;
367         }
368
369         if (!declick) {
370                 declick = _pending_declick;
371         }
372
373         /* figure out if we're going to use gain automation */
374         _amp->setup_gain_automation (start_frame, end_frame, nframes);
375
376
377         /* tell main outs what to do about monitoring */
378         _main_outs->no_outs_cuz_we_no_monitor (!monitor);
379
380
381         /* -------------------------------------------------------------------------------------------
382            GLOBAL DECLICK (for transport changes etc.)
383            ----------------------------------------------------------------------------------------- */
384
385         if (declick > 0) {
386                 Amp::apply_gain (bufs, nframes, 0.0, 1.0);
387         } else if (declick < 0) {
388                 Amp::apply_gain (bufs, nframes, 1.0, 0.0);
389         }
390
391         _pending_declick = 0;
392
393         /* -------------------------------------------------------------------------------------------
394            DENORMAL CONTROL/PHASE INVERT
395            ----------------------------------------------------------------------------------------- */
396
397         if (_phase_invert) {
398
399                 int chn = 0;
400
401                 if (_denormal_protection || Config->get_denormal_protection()) {
402
403                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
404                                 Sample* const sp = i->data();
405
406                                 if (_phase_invert & chn) {
407                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
408                                                 sp[nx]  = -sp[nx];
409                                                 sp[nx] += 1.0e-27f;
410                                         }
411                                 } else {
412                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
413                                                 sp[nx] += 1.0e-27f;
414                                         }
415                                 }
416                         }
417
418                 } else {
419
420                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
421                                 Sample* const sp = i->data();
422
423                                 if (_phase_invert & (1<<chn)) {
424                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
425                                                 sp[nx] = -sp[nx];
426                                         }
427                                 }
428                         }
429                 }
430
431         } else {
432
433                 if (_denormal_protection || Config->get_denormal_protection()) {
434
435                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
436                                 Sample* const sp = i->data();
437                                 for (nframes_t nx = 0; nx < nframes; ++nx) {
438                                         sp[nx] += 1.0e-27f;
439                                 }
440                         }
441
442                 }
443         }
444
445         /* -------------------------------------------------------------------------------------------
446            and go ....
447            ----------------------------------------------------------------------------------------- */
448
449         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
450
451         if (rm.locked()) {
452                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
453
454                         if (bufs.count() != (*i)->input_streams()) {
455                                 cerr << _name << " bufs = " << bufs.count()
456                                      << " input for " << (*i)->name() << " = " << (*i)->input_streams()
457                                      << endl;
458                         }
459                         assert (bufs.count() == (*i)->input_streams());
460
461                         (*i)->run (bufs, start_frame, end_frame, nframes, *i != _processors.back());
462                         bufs.set_count ((*i)->output_streams());
463                 }
464         }
465 }
466
467 ChanCount
468 Route::n_process_buffers ()
469 {
470         return max (_input->n_ports(), processor_max_streams);
471 }
472
473 void
474 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
475 {
476         BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
477
478         _silent = false;
479
480         assert (bufs.available() >= input_streams());
481
482         if (_input->n_ports() == ChanCount::ZERO) {
483                 silence (nframes);
484         }
485
486         bufs.set_count (input_streams());
487
488         if (is_monitor() && _session.listening() && !_session.is_auditioning()) {
489
490                 /* control/monitor bus ignores input ports when something is
491                    feeding the listen "stream". data will "arrive" into the
492                    route from the intreturn processor element.
493                 */
494                 bufs.silence (nframes, 0);
495
496         } else {
497
498                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
499
500                         BufferSet::iterator o = bufs.begin(*t);
501                         PortSet& ports (_input->ports());
502
503                         for (PortSet::iterator i = ports.begin(*t); i != ports.end(*t); ++i, ++o) {
504                                 o->read_from (i->get_buffer(nframes), nframes);
505                         }
506                 }
507         }
508
509         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
510         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
511 }
512
513 void
514 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
515 {
516         BufferSet& bufs (_session.get_silent_buffers (n_process_buffers()));
517         bufs.set_count (_input->n_ports());
518         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
519         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
520 }
521
522 void
523 Route::set_listen (bool yn, void* src)
524 {
525         if (_solo_safe) {
526                 return;
527         }
528
529         if (_monitor_send) {
530                 if (yn != _monitor_send->active()) {
531                         if (yn) {
532                                 _monitor_send->set_solo_level (1);
533                                 _monitor_send->activate ();
534                         } else {
535                                 _monitor_send->set_solo_level (0);
536                                 _monitor_send->deactivate ();
537                         }
538
539                         listen_changed (src); /* EMIT SIGNAL */
540                 }
541         }
542 }
543
544 bool
545 Route::listening () const
546 {
547         if (_monitor_send) {
548                 return _monitor_send->active ();
549         } else {
550                 return false;
551         }
552 }
553
554 void
555 Route::set_solo_safe (bool yn, void *src)
556 {
557         if (_solo_safe != yn) {
558                 _solo_safe = yn;
559                 solo_safe_changed (src);
560         } 
561 }
562
563 bool
564 Route::solo_safe() const
565 {
566         return _solo_safe;
567 }
568
569 void
570 Route::set_solo (bool yn, void *src)
571 {
572         if (_solo_safe) {
573                 return;
574         }
575
576         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
577                 _route_group->apply (&Route::set_solo, yn, _route_group);
578                 return;
579         }
580
581         if (self_soloed() != yn) {
582                 set_self_solo (yn);
583                 set_delivery_solo ();
584                 solo_changed (true, src); /* EMIT SIGNAL */
585                 _solo_control->Changed (); /* EMIT SIGNAL */
586         }
587 }
588
589 void
590 Route::set_self_solo (bool yn)
591 {
592         _self_solo = yn;
593 }
594
595 void
596 Route::mod_solo_by_others (int32_t delta)
597 {
598         if (_solo_safe) {
599                 return;
600         }
601
602         if (delta < 0) {
603                 if (_soloed_by_others >= (uint32_t) abs (delta)) {
604                         _soloed_by_others += delta;
605                 } else {
606                         _soloed_by_others = 0;
607                 }
608         } else {
609                 _soloed_by_others += delta;
610         }
611
612         set_delivery_solo ();
613         solo_changed (false, this);
614 }
615
616 void
617 Route::set_delivery_solo ()
618 {
619         /* tell all delivery processors what the solo situation is, so that they keep
620            delivering even though Session::soloing() is true and they were not
621            explicitly soloed.
622         */
623
624         Glib::RWLock::ReaderLock rm (_processor_lock);
625         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
626                 boost::shared_ptr<Delivery> d;
627                 
628                 if ((d = boost::dynamic_pointer_cast<Delivery> (*i)) != 0) {
629                         d->set_solo_level (soloed ());
630                         d->set_solo_isolated (solo_isolated());
631                 }
632         }
633 }
634
635 void
636 Route::set_solo_isolated (bool yn, void *src)
637 {
638         if (is_master() || is_monitor() || is_hidden()) {
639                 return;
640         }
641
642         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
643                 _route_group->apply (&Route::set_solo_isolated, yn, _route_group);
644                 return;
645         }
646         
647         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
648
649         boost::shared_ptr<RouteList> routes = _session.get_routes ();
650         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
651                 bool sends_only;
652                 bool does_feed = direct_feeds (*i, &sends_only);
653                 
654                 if (does_feed && !sends_only) {
655                         (*i)->set_solo_isolated (yn, (*i)->route_group());
656                 }
657         }
658
659         /* XXX should we back-propagate as well? */
660
661         bool changed = false;
662
663         if (yn) {
664                 if (_solo_isolated == 0) {
665                         changed = true;
666                 }
667                 _solo_isolated++;
668         } else {
669                 changed = (_solo_isolated == 1);
670                 if (_solo_isolated > 0) {
671                         _solo_isolated--;
672                 }
673         }
674
675         if (changed) {
676                 set_delivery_solo ();
677                 solo_isolated_changed (src);
678         }
679 }
680
681 bool
682 Route::solo_isolated () const
683 {
684         return _solo_isolated > 0;
685 }
686
687 void
688 Route::set_mute_points (MuteMaster::MutePoint mp)
689 {
690         if (mp != _mute_points) {
691                 _mute_points = mp;
692                 _mute_master->set_mute_points (_mute_points);
693                 mute_points_changed (); /* EMIT SIGNAL */
694
695                 if (_mute_master->muted()) {
696                         mute_changed (this); /* EMIT SIGNAL */
697                 }
698         }
699 }
700
701 void
702 Route::set_mute (bool yn, void *src)
703 {
704         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_mute()) {
705                 _route_group->apply (&Route::set_mute, yn, _route_group);
706                 return;
707         }
708
709         if (self_muted() != yn) {
710                 _mute_master->set_self_muted (yn);
711                 mute_changed (src); /* EMIT SIGNAL */
712         }
713 }
714
715 bool
716 Route::muted () const
717 {
718         return self_muted() || muted_by_others();
719 }
720
721 bool
722 Route::self_muted() const
723 {
724         return _mute_master->self_muted ();
725 }
726
727 bool
728 Route::muted_by_others() const
729 {
730         return _mute_master->muted_by_others ();
731 }
732
733 void
734 Route::mod_muted_by_others (int delta)
735 {
736         bool old = muted ();
737
738         _mute_master->mod_muted_by_others (delta);
739
740         if (old != muted()) {
741                 mute_changed (this);
742         }
743 }
744
745 #if 0
746 static void
747 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
748 {
749         cerr << name << " {" << endl;
750         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
751                         p != procs.end(); ++p) {
752                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << endl;
753         }
754         cerr << "}" << endl;
755 }
756 #endif
757
758 int
759 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err)
760 {
761         ProcessorList::iterator loc;
762
763         /* XXX this is not thread safe - we don't hold the lock across determining the iter
764            to add before and actually doing the insertion. dammit.
765         */
766
767         if (placement == PreFader) {
768                 /* generic pre-fader: insert immediately before the amp */
769                 loc = find (_processors.begin(), _processors.end(), _amp);
770         } else {
771                 /* generic post-fader: insert right before the main outs */
772                 loc = find (_processors.begin(), _processors.end(), _main_outs);
773         }
774
775         return add_processor (processor, loc, err);
776 }
777
778
779 /** Add a processor to the route.
780  * @a iter must point to an iterator in _processors and the new
781  * processor will be inserted immediately before this location.  Otherwise,
782  * @a position is used.
783  */
784 int
785 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorList::iterator iter, ProcessorStreams* err, bool activation_allowed)
786 {
787         ChanCount old_pms = processor_max_streams;
788
789         if (!_session.engine().connected() || !processor) {
790                 return 1;
791         }
792
793         {
794                 Glib::RWLock::WriterLock lm (_processor_lock);
795
796                 boost::shared_ptr<PluginInsert> pi;
797                 boost::shared_ptr<PortInsert> porti;
798
799                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
800
801                 if (processor == _amp || processor == _meter || processor == _main_outs) {
802                         // Ensure only one of these are in the list at any time
803                         if (loc != _processors.end()) {
804                                 if (iter == loc) { // Already in place, do nothing
805                                         return 0;
806                                 } else { // New position given, relocate
807                                         _processors.erase (loc);
808                                 }
809                         }
810
811                 } else {
812                         if (loc != _processors.end()) {
813                                 cerr << "ERROR: Processor added to route twice!" << endl;
814                                 return 1;
815                         }
816
817                         loc = iter;
818                 }
819
820                 _processors.insert (loc, processor);
821
822                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
823                 // configure redirect ports properly, etc.
824
825                 if (configure_processors_unlocked (err)) {
826                         ProcessorList::iterator ploc = loc;
827                         --ploc;
828                         _processors.erase(ploc);
829                         configure_processors_unlocked (0); // it worked before we tried to add it ...
830                         cerr << "configure failed\n";
831                         return -1;
832                 }
833
834                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
835
836                         if (pi->natural_input_streams() == ChanCount::ZERO) {
837                                 /* generator plugin */
838                                 _have_internal_generator = true;
839                         }
840
841                 }
842
843                 /* is this the monitor send ? if so, make sure we keep track of it */
844
845                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
846
847                 if (isend && _session.monitor_out() && (isend->target_id() == _session.monitor_out()->id())) {
848                         _monitor_send = isend;
849                         
850                         if (_monitor_send->active()) {
851                                 _monitor_send->set_solo_level (1);
852                         } else {
853                                 _monitor_send->set_solo_level (0);
854                         }
855                 }
856
857                 if (activation_allowed && (processor != _monitor_send)) {
858                         processor->activate ();
859                 }
860
861                 processor->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
862
863                 _output->set_user_latency (0);
864         }
865
866         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
867
868         return 0;
869 }
870
871 bool
872 Route::add_processor_from_xml_2X (const XMLNode& node, int version, ProcessorList::iterator iter)
873 {
874         const XMLProperty *prop;
875
876         try {
877                 boost::shared_ptr<Processor> processor;
878
879                 if (node.name() == "Insert") {
880
881                         if ((prop = node.property ("type")) != 0) {
882
883                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
884                                                 prop->value() == "lv2" ||
885                                                 prop->value() == "vst" ||
886                                                 prop->value() == "audiounit") {
887
888                                         processor.reset (new PluginInsert (_session));
889
890                                 } else {
891
892                                         processor.reset (new PortInsert (_session, _mute_master));
893                                 }
894
895                         }
896
897                 } else if (node.name() == "Send") {
898
899                         processor.reset (new Send (_session, _mute_master));
900
901                 } else {
902
903                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
904                         return false;
905                 }
906
907                 if (processor->set_state (node, version)) {
908                         return false;
909                 }
910
911                 if (iter == _processors.end() && processor->display_to_user() && !_processors.empty()) {
912                         /* check for invisible processors stacked at the end and leave them there */
913                         ProcessorList::iterator p;
914                         p = _processors.end();
915                         --p;
916                         while (!(*p)->display_to_user() && p != _processors.begin()) {
917                                 --p;
918                         }
919                         ++p;
920                         iter = p;
921                 }
922
923                 return (add_processor (processor, iter) == 0);
924         }
925
926         catch (failed_constructor &err) {
927                 warning << _("processor could not be created. Ignored.") << endmsg;
928                 return false;
929         }
930 }
931
932 int
933 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
934 {
935         ProcessorList::iterator loc;
936
937         if (before) {
938                 loc = find(_processors.begin(), _processors.end(), before);
939         } else {
940                 /* nothing specified - at end but before main outs */
941                 loc = find (_processors.begin(), _processors.end(), _main_outs);
942         }
943
944         return add_processors (others, loc, err);
945 }
946
947 int
948 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
949 {
950         /* NOTE: this is intended to be used ONLY when copying
951            processors from another Route. Hence the subtle
952            differences between this and ::add_processor()
953         */
954
955         ChanCount old_pms = processor_max_streams;
956
957         if (!_session.engine().connected()) {
958                 return 1;
959         }
960
961         if (others.empty()) {
962                 return 0;
963         }
964
965         {
966                 Glib::RWLock::WriterLock lm (_processor_lock);
967
968                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
969
970                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
971
972                         // Ensure meter only appears in the list once
973                         if (*i == _meter) {
974                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
975                                 if (m != _processors.end()) {
976                                         _processors.erase(m);
977                                 }
978                         }
979
980                         boost::shared_ptr<PluginInsert> pi;
981
982                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
983                                 pi->set_count (1);
984
985                                 ChanCount m = max (pi->input_streams(), pi->output_streams());
986
987                                 if (m > potential_max_streams) {
988                                         potential_max_streams = m;
989                                 }
990                         }
991
992                         ProcessorList::iterator inserted = _processors.insert (iter, *i);
993
994                         if ((*i)->active()) {
995                                 (*i)->activate ();
996                         }
997
998                         if (configure_processors_unlocked (err)) {
999                                 _processors.erase (inserted);
1000                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
1001                                 return -1;
1002                         }
1003
1004                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
1005                 }
1006
1007                 _output->set_user_latency (0);
1008         }
1009
1010         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1011
1012         return 0;
1013 }
1014
1015 void
1016 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1017 {
1018         if (p == PreFader) {
1019                 start = _processors.begin();
1020                 end = find(_processors.begin(), _processors.end(), _amp);
1021         } else {
1022                 start = find(_processors.begin(), _processors.end(), _amp);
1023                 ++start;
1024                 end = _processors.end();
1025         }
1026 }
1027
1028 /** Turn off all processors with a given placement
1029  * @param p Placement of processors to disable
1030  */
1031 void
1032 Route::disable_processors (Placement p)
1033 {
1034         Glib::RWLock::ReaderLock lm (_processor_lock);
1035
1036         ProcessorList::iterator start, end;
1037         placement_range(p, start, end);
1038
1039         for (ProcessorList::iterator i = start; i != end; ++i) {
1040                 (*i)->deactivate ();
1041         }
1042
1043         _session.set_dirty ();
1044 }
1045
1046 /** Turn off all redirects
1047  */
1048 void
1049 Route::disable_processors ()
1050 {
1051         Glib::RWLock::ReaderLock lm (_processor_lock);
1052
1053         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1054                 (*i)->deactivate ();
1055         }
1056
1057         _session.set_dirty ();
1058 }
1059
1060 /** Turn off all redirects with a given placement
1061  * @param p Placement of redirects to disable
1062  */
1063 void
1064 Route::disable_plugins (Placement p)
1065 {
1066         Glib::RWLock::ReaderLock lm (_processor_lock);
1067
1068         ProcessorList::iterator start, end;
1069         placement_range(p, start, end);
1070
1071         for (ProcessorList::iterator i = start; i != end; ++i) {
1072                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1073                         (*i)->deactivate ();
1074                 }
1075         }
1076
1077         _session.set_dirty ();
1078 }
1079
1080 /** Turn off all plugins
1081  */
1082 void
1083 Route::disable_plugins ()
1084 {
1085         Glib::RWLock::ReaderLock lm (_processor_lock);
1086
1087         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1088                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1089                         (*i)->deactivate ();
1090                 }
1091         }
1092
1093         _session.set_dirty ();
1094 }
1095
1096
1097 void
1098 Route::ab_plugins (bool forward)
1099 {
1100         Glib::RWLock::ReaderLock lm (_processor_lock);
1101
1102         if (forward) {
1103
1104                 /* forward = turn off all active redirects, and mark them so that the next time
1105                    we go the other way, we will revert them
1106                 */
1107
1108                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1109                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1110                                 continue;
1111                         }
1112
1113                         if ((*i)->active()) {
1114                                 (*i)->deactivate ();
1115                                 (*i)->set_next_ab_is_active (true);
1116                         } else {
1117                                 (*i)->set_next_ab_is_active (false);
1118                         }
1119                 }
1120
1121         } else {
1122
1123                 /* backward = if the redirect was marked to go active on the next ab, do so */
1124
1125                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1126
1127                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1128                                 continue;
1129                         }
1130
1131                         if ((*i)->get_next_ab_is_active()) {
1132                                 (*i)->activate ();
1133                         } else {
1134                                 (*i)->deactivate ();
1135                         }
1136                 }
1137         }
1138
1139         _session.set_dirty ();
1140 }
1141
1142
1143 /** Remove processors with a given placement.
1144  * @param p Placement of processors to remove.
1145  */
1146 void
1147 Route::clear_processors (Placement p)
1148 {
1149         const ChanCount old_pms = processor_max_streams;
1150
1151         if (!_session.engine().connected()) {
1152                 return;
1153         }
1154
1155         bool already_deleting = _session.deletion_in_progress();
1156         if (!already_deleting) {
1157                 _session.set_deletion_in_progress();
1158         }
1159
1160         {
1161                 Glib::RWLock::WriterLock lm (_processor_lock);
1162                 ProcessorList new_list;
1163                 ProcessorStreams err;
1164                 bool seen_amp = false;
1165
1166                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1167
1168                         if (*i == _amp) {
1169                                 seen_amp = true;
1170                         }
1171
1172                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1173
1174                                 /* you can't remove these */
1175
1176                                 new_list.push_back (*i);
1177
1178                         } else {
1179                                 if (seen_amp) {
1180
1181                                         switch (p) {
1182                                         case PreFader:
1183                                                 new_list.push_back (*i);
1184                                                 break;
1185                                         case PostFader:
1186                                                 (*i)->drop_references ();
1187                                                 break;
1188                                         }
1189
1190                                 } else {
1191
1192                                         switch (p) {
1193                                         case PreFader:
1194                                                 (*i)->drop_references ();
1195                                                 break;
1196                                         case PostFader:
1197                                                 new_list.push_back (*i);
1198                                                 break;
1199                                         }
1200                                 }
1201                         }
1202                 }
1203
1204                 _processors = new_list;
1205                 configure_processors_unlocked (&err); // this can't fail
1206         }
1207
1208         processor_max_streams.reset();
1209         _have_internal_generator = false;
1210         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1211
1212         if (!already_deleting) {
1213                 _session.clear_deletion_in_progress();
1214         }
1215 }
1216
1217 int
1218 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1219 {
1220         /* these can never be removed */
1221
1222         if (processor == _amp || processor == _meter || processor == _main_outs) {
1223                 return 0;
1224         }
1225
1226         ChanCount old_pms = processor_max_streams;
1227
1228         if (!_session.engine().connected()) {
1229                 return 1;
1230         }
1231
1232         processor_max_streams.reset();
1233
1234         {
1235                 Glib::RWLock::WriterLock lm (_processor_lock);
1236                 ProcessorList::iterator i;
1237                 bool removed = false;
1238
1239                 for (i = _processors.begin(); i != _processors.end(); ) {
1240                         if (*i == processor) {
1241
1242                                 /* move along, see failure case for configure_processors()
1243                                    where we may need to reconfigure the processor.
1244                                 */
1245
1246                                 /* stop redirects that send signals to JACK ports
1247                                    from causing noise as a result of no longer being
1248                                    run.
1249                                 */
1250
1251                                 boost::shared_ptr<IOProcessor> iop;
1252
1253                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1254                                         if (iop->input()) {
1255                                                 iop->input()->disconnect (this);
1256                                         }
1257                                         if (iop->output()) {
1258                                                 iop->output()->disconnect (this);
1259                                         }
1260                                 }
1261
1262                                 i = _processors.erase (i);
1263                                 removed = true;
1264                                 break;
1265
1266                         } else {
1267                                 ++i;
1268                         }
1269
1270                         _output->set_user_latency (0);
1271                 }
1272
1273                 if (!removed) {
1274                         /* what? */
1275                         return 1;
1276                 }
1277
1278                 if (configure_processors_unlocked (err)) {
1279                         /* get back to where we where */
1280                         _processors.insert (i, processor);
1281                         /* we know this will work, because it worked before :) */
1282                         configure_processors_unlocked (0);
1283                         return -1;
1284                 }
1285
1286                 _have_internal_generator = false;
1287
1288                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1289                         boost::shared_ptr<PluginInsert> pi;
1290
1291                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1292                                 if (pi->is_generator()) {
1293                                         _have_internal_generator = true;
1294                                         break;
1295                                 }
1296                         }
1297                 }
1298         }
1299
1300         processor->drop_references ();
1301         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1302
1303         return 0;
1304 }
1305
1306 int
1307 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1308 {
1309         ProcessorList deleted;
1310
1311         if (!_session.engine().connected()) {
1312                 return 1;
1313         }
1314
1315         processor_max_streams.reset();
1316
1317         {
1318                 Glib::RWLock::WriterLock lm (_processor_lock);
1319                 ProcessorList::iterator i;
1320                 boost::shared_ptr<Processor> processor;
1321
1322                 ProcessorList as_we_were = _processors;
1323
1324                 for (i = _processors.begin(); i != _processors.end(); ) {
1325
1326                         processor = *i;
1327
1328                         /* these can never be removed */
1329
1330                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1331                                 ++i;
1332                                 continue;
1333                         }
1334
1335                         /* see if its in the list of processors to delete */
1336
1337                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1338                                 ++i;
1339                                 continue;
1340                         }
1341
1342                         /* stop IOProcessors that send to JACK ports
1343                            from causing noise as a result of no longer being
1344                            run.
1345                         */
1346
1347                         boost::shared_ptr<IOProcessor> iop;
1348
1349                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1350                                 iop->disconnect ();
1351                         }
1352
1353                         deleted.push_back (processor);
1354                         i = _processors.erase (i);
1355                 }
1356
1357                 if (deleted.empty()) {
1358                         /* none of those in the requested list were found */
1359                         return 0;
1360                 }
1361
1362                 _output->set_user_latency (0);
1363
1364                 if (configure_processors_unlocked (err)) {
1365                         /* get back to where we where */
1366                         _processors = as_we_were;
1367                         /* we know this will work, because it worked before :) */
1368                         configure_processors_unlocked (0);
1369                         return -1;
1370                 }
1371
1372                 _have_internal_generator = false;
1373
1374                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1375                         boost::shared_ptr<PluginInsert> pi;
1376
1377                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1378                                 if (pi->is_generator()) {
1379                                         _have_internal_generator = true;
1380                                         break;
1381                                 }
1382                         }
1383                 }
1384         }
1385
1386         /* now try to do what we need to so that those that were removed will be deleted */
1387
1388         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1389                 (*i)->drop_references ();
1390         }
1391
1392         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1393
1394         return 0;
1395 }
1396
1397
1398 int
1399 Route::configure_processors (ProcessorStreams* err)
1400 {
1401         if (!_in_configure_processors) {
1402                 Glib::RWLock::WriterLock lm (_processor_lock);
1403                 return configure_processors_unlocked (err);
1404         }
1405         return 0;
1406 }
1407
1408 ChanCount
1409 Route::input_streams () const
1410 {
1411         return _input->n_ports ();
1412 }
1413
1414 /** Configure the input/output configuration of each processor in the processors list.
1415  * Return 0 on success, otherwise configuration is impossible.
1416  */
1417 int
1418 Route::configure_processors_unlocked (ProcessorStreams* err)
1419 {
1420         if (_in_configure_processors) {
1421            return 0;
1422         }
1423
1424         _in_configure_processors = true;
1425
1426         // Check each processor in order to see if we can configure as requested
1427         ChanCount in = input_streams ();
1428         ChanCount out;
1429         list< pair<ChanCount,ChanCount> > configuration;
1430         uint32_t index = 0;
1431
1432         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1433 #ifndef NDEBUG
1434         DEBUG_TRACE (DEBUG::Processors, "{\n");
1435         for (list<boost::shared_ptr<Processor> >::const_iterator p = _processors.begin(); p != _processors.end(); ++p) {
1436                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID = %2\n", (*p)->name(), (*p)->id()));
1437         }
1438         DEBUG_TRACE (DEBUG::Processors, "}\n");
1439 #endif
1440
1441         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1442
1443                 if ((*p)->can_support_io_configuration(in, out)) {
1444                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1in = %2 out = %3\n",(*p)->name(), in, out));
1445                         configuration.push_back(make_pair(in, out));
1446                         in = out;
1447                 } else {
1448                         if (err) {
1449                                 err->index = index;
1450                                 err->count = in;
1451                         }
1452                         _in_configure_processors = false;
1453                         return -1;
1454                 }
1455         }
1456
1457         // We can, so configure everything
1458         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1459         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1460                 (*p)->configure_io(c->first, c->second);
1461                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1462                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1463                 out = c->second;
1464         }
1465
1466         if (_meter) {
1467                 _meter->reset_max_channels (processor_max_streams);
1468         }
1469
1470         /* make sure we have sufficient scratch buffers to cope with the new processor
1471            configuration */
1472         {
1473                 Glib::Mutex::Lock em (_session.engine().process_lock ());
1474                 _session.ensure_buffers (n_process_buffers ());
1475         }
1476
1477         _in_configure_processors = false;
1478         return 0;
1479 }
1480
1481 void
1482 Route::all_processors_flip ()
1483 {
1484         Glib::RWLock::ReaderLock lm (_processor_lock);
1485
1486         if (_processors.empty()) {
1487                 return;
1488         }
1489
1490         bool first_is_on = _processors.front()->active();
1491
1492         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1493                 if (first_is_on) {
1494                         (*i)->deactivate ();
1495                 } else {
1496                         (*i)->activate ();
1497                 }
1498         }
1499
1500         _session.set_dirty ();
1501 }
1502
1503 /** Set all processors with a given placement to a given active state.
1504  * @param p Placement of processors to change.
1505  * @param state New active state for those processors.
1506  */
1507 void
1508 Route::all_processors_active (Placement p, bool state)
1509 {
1510         Glib::RWLock::ReaderLock lm (_processor_lock);
1511
1512         if (_processors.empty()) {
1513                 return;
1514         }
1515         ProcessorList::iterator start, end;
1516         placement_range(p, start, end);
1517
1518         bool before_amp = true;
1519         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1520                 if ((*i) == _amp) {
1521                         before_amp = false;
1522                         continue;
1523                 }
1524                 if (p == PreFader && before_amp) {
1525                         if (state) {
1526                                 (*i)->activate ();
1527                         } else {
1528                                 (*i)->deactivate ();
1529                         }
1530                 }
1531         }
1532
1533         _session.set_dirty ();
1534 }
1535
1536 bool
1537 Route::processor_is_prefader (boost::shared_ptr<Processor> p)
1538 {
1539         bool pre_fader = true;
1540         Glib::RWLock::ReaderLock lm (_processor_lock);
1541
1542         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1543
1544                 /* semantic note: if p == amp, we want to return true, so test
1545                    for equality before checking if this is the amp
1546                 */
1547
1548                 if ((*i) == p) {
1549                         break;
1550                 }
1551
1552                 if ((*i) == _amp) {
1553                         pre_fader = false;
1554                         break;
1555                 }
1556         }
1557
1558         return pre_fader;
1559 }
1560
1561 int
1562 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1563 {
1564         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1565            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1566            processors in the current actual processor list that are hidden. Any visible processors
1567            in the current list but not in "new_order" will be assumed to be deleted.
1568         */
1569
1570         {
1571                 Glib::RWLock::WriterLock lm (_processor_lock);
1572                 ChanCount old_pms = processor_max_streams;
1573                 ProcessorList::iterator oiter;
1574                 ProcessorList::const_iterator niter;
1575                 ProcessorList as_it_was_before = _processors;
1576                 ProcessorList as_it_will_be;
1577
1578                 oiter = _processors.begin();
1579                 niter = new_order.begin();
1580
1581                 while (niter !=  new_order.end()) {
1582
1583                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1584                            then append it to the temp list.
1585
1586                            Otherwise, see if the next processor in the old list is in the new list. if not,
1587                            its been deleted. If its there, append it to the temp list.
1588                         */
1589
1590                         if (oiter == _processors.end()) {
1591
1592                                 /* no more elements in the old list, so just stick the rest of
1593                                    the new order onto the temp list.
1594                                 */
1595
1596                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1597                                 while (niter != new_order.end()) {
1598                                         ++niter;
1599                                 }
1600                                 break;
1601
1602                         } else {
1603
1604                                 if (!(*oiter)->display_to_user()) {
1605
1606                                         as_it_will_be.push_back (*oiter);
1607
1608                                 } else {
1609
1610                                         /* visible processor: check that its in the new order */
1611
1612                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1613                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1614                                         } else {
1615                                                 /* ignore this one, and add the next item from the new order instead */
1616                                                 as_it_will_be.push_back (*niter);
1617                                                 ++niter;
1618                                         }
1619                                 }
1620
1621                                 /* now remove from old order - its taken care of no matter what */
1622                                 oiter = _processors.erase (oiter);
1623                         }
1624
1625                 }
1626
1627                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1628
1629                 if (configure_processors_unlocked (err)) {
1630                         _processors = as_it_was_before;
1631                         processor_max_streams = old_pms;
1632                         return -1;
1633                 }
1634         }
1635
1636         if (true) {
1637                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1638         }
1639
1640         return 0;
1641 }
1642
1643 XMLNode&
1644 Route::get_state()
1645 {
1646         return state(true);
1647 }
1648
1649 XMLNode&
1650 Route::get_template()
1651 {
1652         return state(false);
1653 }
1654
1655 XMLNode&
1656 Route::state(bool full_state)
1657 {
1658         XMLNode *node = new XMLNode("Route");
1659         ProcessorList::iterator i;
1660         char buf[32];
1661
1662         id().print (buf, sizeof (buf));
1663         node->add_property("id", buf);
1664         node->add_property ("name", _name);
1665         node->add_property("default-type", _default_type.to_string());
1666
1667         if (_flags) {
1668                 node->add_property("flags", enum_2_string (_flags));
1669         }
1670
1671         node->add_property("active", _active?"yes":"no");
1672         node->add_property("phase-invert", _phase_invert?"yes":"no");
1673         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1674         node->add_property("meter-point", enum_2_string (_meter_point));
1675
1676         if (_route_group) {
1677                 node->add_property("route-group", _route_group->name());
1678         }
1679
1680         string order_string;
1681         OrderKeys::iterator x = order_keys.begin();
1682
1683         while (x != order_keys.end()) {
1684                 order_string += string ((*x).first);
1685                 order_string += '=';
1686                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1687                 order_string += buf;
1688
1689                 ++x;
1690
1691                 if (x == order_keys.end()) {
1692                         break;
1693                 }
1694
1695                 order_string += ':';
1696         }
1697         node->add_property ("order-keys", order_string);
1698         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1699         snprintf (buf, sizeof (buf), "%d", _soloed_by_others);
1700         node->add_property ("soloed-by-others", buf);
1701
1702         node->add_child_nocopy (_input->state (full_state));
1703         node->add_child_nocopy (_output->state (full_state));
1704         node->add_child_nocopy (_solo_control->get_state ());
1705         node->add_child_nocopy (_mute_master->get_state ());
1706
1707         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1708         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1709         remote_control_node->add_property (X_("id"), buf);
1710         node->add_child_nocopy (*remote_control_node);
1711
1712         if (_comment.length()) {
1713                 XMLNode *cmt = node->add_child ("Comment");
1714                 cmt->add_content (_comment);
1715         }
1716
1717         for (i = _processors.begin(); i != _processors.end(); ++i) {
1718                 node->add_child_nocopy((*i)->state (full_state));
1719         }
1720
1721         if (_extra_xml){
1722                 node->add_child_copy (*_extra_xml);
1723         }
1724
1725         return *node;
1726 }
1727
1728 int
1729 Route::set_state (const XMLNode& node, int version)
1730 {
1731         return _set_state (node, version, true);
1732 }
1733
1734 int
1735 Route::_set_state (const XMLNode& node, int version, bool /*call_base*/)
1736 {
1737         if (version < 3000) {
1738                 return _set_state_2X (node, version);
1739         }
1740
1741         XMLNodeList nlist;
1742         XMLNodeConstIterator niter;
1743         XMLNode *child;
1744         XMLPropertyList plist;
1745         const XMLProperty *prop;
1746
1747         if (node.name() != "Route"){
1748                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1749                 return -1;
1750         }
1751
1752         if ((prop = node.property (X_("name"))) != 0) {
1753                 Route::set_name (prop->value());
1754         }
1755
1756         if ((prop = node.property ("id")) != 0) {
1757                 _id = prop->value ();
1758         }
1759
1760         if ((prop = node.property (X_("flags"))) != 0) {
1761                 _flags = Flag (string_2_enum (prop->value(), _flags));
1762         } else {
1763                 _flags = Flag (0);
1764         }
1765
1766         /* add all processors (except amp, which is always present) */
1767
1768         nlist = node.children();
1769         XMLNode processor_state (X_("processor_state"));
1770
1771         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1772
1773                 child = *niter;
1774
1775                 if (child->name() == IO::state_node_name) {
1776                         if ((prop = child->property (X_("direction"))) == 0) {
1777                                 continue;
1778                         }
1779
1780                         if (prop->value() == "Input") {
1781                                 _input->set_state (*child, version);
1782                         } else if (prop->value() == "Output") {
1783                                 _output->set_state (*child, version);
1784                         }
1785                 }
1786
1787                 if (child->name() == X_("Processor")) {
1788                         processor_state.add_child_copy (*child);
1789                 }
1790         }
1791
1792         set_processor_state (processor_state);
1793
1794         if ((prop = node.property ("self-solo")) != 0) {
1795                 set_self_solo (string_is_affirmative (prop->value()));
1796         }
1797
1798         if ((prop = node.property ("soloed-by-others")) != 0) {
1799                 _soloed_by_others = 0; // needed for mod_solo_by_others () to work
1800                 mod_solo_by_others (atoi (prop->value()));
1801         }
1802
1803         if ((prop = node.property ("solo-isolated")) != 0) {
1804                 set_solo_isolated (string_is_affirmative (prop->value()), this);
1805         }
1806
1807         if ((prop = node.property (X_("phase-invert"))) != 0) {
1808                 set_phase_invert (string_is_affirmative (prop->value()));
1809         }
1810
1811         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1812                 set_denormal_protection (string_is_affirmative (prop->value()));
1813         }
1814
1815         if ((prop = node.property (X_("active"))) != 0) {
1816                 bool yn = string_is_affirmative (prop->value());
1817                 _active = !yn; // force switch
1818                 set_active (yn);
1819         }
1820
1821         if ((prop = node.property (X_("meter-point"))) != 0) {
1822                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
1823                 set_meter_point (mp);
1824                 if (_meter) {
1825                         _meter->set_display_to_user (_meter_point == MeterCustom);
1826                 }
1827         }
1828
1829         if ((prop = node.property (X_("order-keys"))) != 0) {
1830
1831                 long n;
1832
1833                 string::size_type colon, equal;
1834                 string remaining = prop->value();
1835
1836                 while (remaining.length()) {
1837
1838                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1839                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1840                                       << endmsg;
1841                         } else {
1842                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1843                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1844                                               << endmsg;
1845                                 } else {
1846                                         set_order_key (remaining.substr (0, equal), n);
1847                                 }
1848                         }
1849
1850                         colon = remaining.find_first_of (':');
1851
1852                         if (colon != string::npos) {
1853                                 remaining = remaining.substr (colon+1);
1854                         } else {
1855                                 break;
1856                         }
1857                 }
1858         }
1859
1860         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1861                 child = *niter;
1862
1863                 if (child->name() == X_("Comment")) {
1864
1865                         /* XXX this is a terrible API design in libxml++ */
1866
1867                         XMLNode *cmt = *(child->children().begin());
1868                         _comment = cmt->content();
1869
1870                 } else if (child->name() == X_("Extra")) {
1871
1872                         _extra_xml = new XMLNode (*child);
1873
1874                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1875
1876                         if (prop->value() == "solo") {
1877                                 _solo_control->set_state (*child, version);
1878                                 _session.add_controllable (_solo_control);
1879                         }
1880
1881                 } else if (child->name() == X_("RemoteControl")) {
1882                         if ((prop = child->property (X_("id"))) != 0) {
1883                                 int32_t x;
1884                                 sscanf (prop->value().c_str(), "%d", &x);
1885                                 set_remote_control_id (x);
1886                         }
1887
1888                 } else if (child->name() == X_("MuteMaster")) {
1889                         _mute_master->set_state (*child, version);
1890                 }
1891         }
1892
1893         return 0;
1894 }
1895
1896 int
1897 Route::_set_state_2X (const XMLNode& node, int version)
1898 {
1899         XMLNodeList nlist;
1900         XMLNodeConstIterator niter;
1901         XMLNode *child;
1902         XMLPropertyList plist;
1903         const XMLProperty *prop;
1904
1905         /* 2X things which still remain to be handled:
1906          * default-type
1907          * automation
1908          * controlouts
1909          */
1910
1911         if (node.name() != "Route") {
1912                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1913                 return -1;
1914         }
1915
1916         if ((prop = node.property (X_("flags"))) != 0) {
1917                 _flags = Flag (string_2_enum (prop->value(), _flags));
1918         } else {
1919                 _flags = Flag (0);
1920         }
1921         
1922         if ((prop = node.property (X_("phase-invert"))) != 0) {
1923                 set_phase_invert (string_is_affirmative (prop->value()));
1924         }
1925
1926         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1927                 set_denormal_protection (string_is_affirmative (prop->value()));
1928         }
1929
1930         if ((prop = node.property (X_("soloed"))) != 0) {
1931                 bool yn = string_is_affirmative (prop->value());
1932
1933                 /* XXX force reset of solo status */
1934
1935                 set_solo (yn, this);
1936         }
1937
1938         if ((prop = node.property (X_("muted"))) != 0) {
1939                 
1940                 bool first = true;
1941                 bool muted = string_is_affirmative (prop->value());
1942                 
1943                 if(muted){
1944                   
1945                         string mute_point;
1946                         
1947                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1948                           
1949                                 if (string_is_affirmative (prop->value())){
1950                                         mute_point = mute_point + "PreFader";
1951                                         first = false;
1952                                 }
1953                         }
1954                         
1955                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1956                           
1957                                 if (string_is_affirmative (prop->value())){
1958                                   
1959                                         if (!first) {
1960                                                 mute_point = mute_point + ",";
1961                                         }
1962                                         
1963                                         mute_point = mute_point + "PostFader";
1964                                         first = false;
1965                                 }
1966                         }
1967
1968                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1969                           
1970                                 if (string_is_affirmative (prop->value())){
1971                                   
1972                                         if (!first) {
1973                                                 mute_point = mute_point + ",";
1974                                         }
1975                                         
1976                                         mute_point = mute_point + "Listen";
1977                                         first = false;
1978                                 }
1979                         }
1980
1981                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1982                           
1983                                 if (string_is_affirmative (prop->value())){
1984                                   
1985                                         if (!first) {
1986                                                 mute_point = mute_point + ",";
1987                                         }
1988                                         
1989                                         mute_point = mute_point + "Main";
1990                                 }
1991                         }
1992                         
1993                         _mute_master->set_mute_points (mute_point);
1994                 }
1995         }
1996
1997         if ((prop = node.property (X_("meter-point"))) != 0) {
1998                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1999         }
2000
2001         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2002            don't mean the same thing.
2003         */
2004
2005         if ((prop = node.property (X_("order-keys"))) != 0) {
2006
2007                 long n;
2008
2009                 string::size_type colon, equal;
2010                 string remaining = prop->value();
2011
2012                 while (remaining.length()) {
2013
2014                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2015                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2016                                         << endmsg;
2017                         } else {
2018                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
2019                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2020                                                 << endmsg;
2021                                 } else {
2022                                         set_order_key (remaining.substr (0, equal), n);
2023                                 }
2024                         }
2025
2026                         colon = remaining.find_first_of (':');
2027
2028                         if (colon != string::npos) {
2029                                 remaining = remaining.substr (colon+1);
2030                         } else {
2031                                 break;
2032                         }
2033                 }
2034         }
2035
2036         /* add standard processors */
2037
2038         //_meter.reset (new PeakMeter (_session));
2039         //add_processor (_meter, PreFader);
2040
2041         if (is_monitor()) {
2042                 /* where we listen to tracks */
2043                 _intreturn.reset (new InternalReturn (_session));
2044                 add_processor (_intreturn, PreFader);
2045
2046                 _monitor_control.reset (new MonitorProcessor (_session));
2047                 add_processor (_monitor_control, PostFader);
2048         }
2049
2050         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
2051         add_processor (_main_outs, PostFader);
2052
2053         /* IOs */
2054
2055         nlist = node.children ();
2056         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2057
2058                 child = *niter;
2059
2060                 if (child->name() == IO::state_node_name) {
2061
2062                         /* there is a note in IO::set_state_2X() about why we have to call
2063                            this directly.
2064                            */
2065
2066                         _input->set_state_2X (*child, version, true);
2067                         _output->set_state_2X (*child, version, false);
2068
2069                         if ((prop = child->property (X_("name"))) != 0) {
2070                                 Route::set_name (prop->value ());
2071                         }
2072
2073                         if ((prop = child->property (X_("id"))) != 0) {
2074                                 _id = prop->value ();
2075                         }
2076
2077                         if ((prop = child->property (X_("active"))) != 0) {
2078                                 bool yn = string_is_affirmative (prop->value());
2079                                 _active = !yn; // force switch
2080                                 set_active (yn);
2081                         }
2082                         
2083                         if ((prop = child->property (X_("gain"))) != 0) {
2084                                 gain_t val;
2085
2086                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2087                                         _amp->gain_control()->set_value (val);
2088                                 }
2089                         }
2090                         
2091                         /* Set up Panners in the IO */
2092                         XMLNodeList io_nlist = child->children ();
2093                         
2094                         XMLNodeConstIterator io_niter;
2095                         XMLNode *io_child;
2096                         
2097                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2098
2099                                 io_child = *io_niter;
2100                                 
2101                                 if (io_child->name() == X_("Panner")) {
2102                                         _main_outs->panner()->set_state(*io_child, version);
2103                                 }
2104                         }
2105                 }
2106         }
2107
2108         XMLNodeList redirect_nodes;
2109
2110         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2111
2112                 child = *niter;
2113
2114                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2115                         redirect_nodes.push_back(child);
2116                 }
2117
2118         }
2119
2120         set_processor_state_2X (redirect_nodes, version);
2121
2122         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2123                 child = *niter;
2124
2125                 if (child->name() == X_("Comment")) {
2126
2127                         /* XXX this is a terrible API design in libxml++ */
2128
2129                         XMLNode *cmt = *(child->children().begin());
2130                         _comment = cmt->content();
2131
2132                 } else if (child->name() == X_("Extra")) {
2133
2134                         _extra_xml = new XMLNode (*child);
2135
2136                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
2137
2138                         if (prop->value() == "solo") {
2139                                 _solo_control->set_state (*child, version);
2140                                 _session.add_controllable (_solo_control);
2141                         }
2142
2143                 } else if (child->name() == X_("RemoteControl")) {
2144                         if ((prop = child->property (X_("id"))) != 0) {
2145                                 int32_t x;
2146                                 sscanf (prop->value().c_str(), "%d", &x);
2147                                 set_remote_control_id (x);
2148                         }
2149
2150                 } 
2151         }
2152
2153         return 0;
2154 }
2155
2156 XMLNode&
2157 Route::get_processor_state ()
2158 {
2159         XMLNode* root = new XMLNode (X_("redirects"));
2160         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2161                 root->add_child_nocopy ((*i)->state (true));
2162         }
2163
2164         return *root;
2165 }
2166
2167 void
2168 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2169 {
2170         /* We don't bother removing existing processors not in nList, as this
2171            method will only be called when creating a Route from scratch, not
2172            for undo purposes.  Just put processors in at the appropriate place
2173            in the list.
2174         */
2175
2176         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2177                 add_processor_from_xml_2X (**i, version, _processors.begin ());
2178         }
2179 }
2180
2181 void
2182 Route::set_processor_state (const XMLNode& node)
2183 {
2184         const XMLNodeList &nlist = node.children();
2185         XMLNodeConstIterator niter;
2186         ProcessorList new_order;
2187         bool must_configure = false;
2188
2189         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2190
2191                 XMLProperty* prop = (*niter)->property ("type");
2192
2193                 if (prop->value() == "amp") {
2194                         _amp->set_state (**niter, Stateful::current_state_version);
2195                         new_order.push_back (_amp);
2196                 } else if (prop->value() == "meter") {
2197                         _meter->set_state (**niter, Stateful::current_state_version);
2198                         new_order.push_back (_meter);
2199                 } else if (prop->value() == "main-outs") {
2200                         _main_outs->set_state (**niter, Stateful::current_state_version);
2201                         new_order.push_back (_main_outs);
2202                 } else if (prop->value() == "intreturn") {
2203                         if (!_intreturn) {
2204                                 _intreturn.reset (new InternalReturn (_session));
2205                                 must_configure = true;
2206                         }
2207                         _intreturn->set_state (**niter, Stateful::current_state_version);
2208                         new_order.push_back (_intreturn);
2209                 } else if (is_monitor() && prop->value() == "monitor") {
2210                         if (!_monitor_control) {
2211                                 _monitor_control.reset (new MonitorProcessor (_session));
2212                                 must_configure = true;
2213                         }
2214                         _monitor_control->set_state (**niter, Stateful::current_state_version);
2215                         new_order.push_back (_monitor_control);
2216                 } else {
2217                         ProcessorList::iterator o;
2218
2219                         for (o = _processors.begin(); o != _processors.end(); ++o) {
2220                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2221                                 if (id_prop && (*o)->id() == id_prop->value()) {
2222                                         (*o)->set_state (**niter, Stateful::current_state_version);
2223                                         new_order.push_back (*o);
2224                                         break;
2225                                 }
2226                         }
2227
2228                         // If the processor (*niter) is not on the route then create it 
2229                         
2230                         if (o == _processors.end()) {
2231                                 
2232                                 boost::shared_ptr<Processor> processor;
2233
2234                                 if (prop->value() == "intsend") {
2235                                         
2236                                         processor.reset (new InternalSend (_session, _mute_master, boost::shared_ptr<Route>(), Delivery::Role (0)));
2237                                         
2238                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
2239                                            prop->value() == "lv2" ||
2240                                            prop->value() == "vst" ||
2241                                            prop->value() == "audiounit") {
2242                                         
2243                                         processor.reset (new PluginInsert(_session));
2244                                         
2245                                 } else if (prop->value() == "port") {
2246                                         
2247                                         processor.reset (new PortInsert (_session, _mute_master));
2248                                         
2249                                 } else if (prop->value() == "send") {
2250                                         
2251                                         processor.reset (new Send (_session, _mute_master));
2252                                         
2253                                 } else {
2254                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
2255                                         continue;
2256                                 }
2257
2258                                 processor->set_state (**niter, Stateful::current_state_version);
2259                                 new_order.push_back (processor);
2260                                 must_configure = true;
2261                         }
2262                 }
2263         }
2264
2265         { 
2266                 Glib::RWLock::WriterLock lm (_processor_lock);
2267                 _processors = new_order;
2268                 if (must_configure) {
2269                         configure_processors_unlocked (0);
2270                 }
2271         }
2272
2273         markup_solo_ignore ();
2274
2275         processors_changed (RouteProcessorChange ());
2276 }
2277
2278 void
2279 Route::markup_solo_ignore ()
2280 {
2281         Glib::RWLock::ReaderLock lm (_processor_lock);
2282         
2283         for (ProcessorList::iterator p = _processors.begin(); p !=  _processors.end(); ++p) {
2284
2285                 /* all delivery processors on master, monitor and auditioner never ever pay attention to solo
2286                  */
2287
2288                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*p);
2289                 
2290                 if (d && (is_master() || is_monitor() || is_hidden())) {
2291                         cerr << _name << " Found a delivery unit, mark solo ignored\n";
2292                         d->set_solo_ignored (true);
2293                 }
2294         }
2295 }
2296
2297 void
2298 Route::curve_reallocate ()
2299 {
2300 //      _gain_automation_curve.finish_resize ();
2301 //      _pan_automation_curve.finish_resize ();
2302 }
2303
2304 void
2305 Route::silence (nframes_t nframes)
2306 {
2307         if (!_silent) {
2308
2309                 _output->silence (nframes);
2310
2311                 {
2312                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2313
2314                         if (lm.locked()) {
2315                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2316                                         boost::shared_ptr<PluginInsert> pi;
2317
2318                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2319                                                 // skip plugins, they don't need anything when we're not active
2320                                                 continue;
2321                                         }
2322
2323                                         (*i)->silence (nframes);
2324                                 }
2325
2326                                 if (nframes == _session.get_block_size()) {
2327                                         // _silent = true;
2328                                 }
2329                         }
2330                 }
2331
2332         }
2333 }
2334
2335 void
2336 Route::add_internal_return ()
2337 {
2338         if (!_intreturn) {
2339                 _intreturn.reset (new InternalReturn (_session));
2340                 add_processor (_intreturn, PreFader);
2341         }
2342 }
2343
2344 BufferSet*
2345 Route::get_return_buffer () const
2346 {
2347         Glib::RWLock::ReaderLock rm (_processor_lock);
2348
2349         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2350                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2351
2352                 if (d) {
2353                         BufferSet* bs = d->get_buffers ();
2354                         return bs;
2355                 }
2356         }
2357
2358         return 0;
2359 }
2360
2361 void
2362 Route::release_return_buffer () const
2363 {
2364         Glib::RWLock::ReaderLock rm (_processor_lock);
2365
2366         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2367                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2368
2369                 if (d) {
2370                         return d->release_buffers ();
2371                 }
2372         }
2373 }
2374
2375 int
2376 Route::listen_via (boost::shared_ptr<Route> route, Placement placement, bool /*active*/, bool aux)
2377 {
2378         vector<string> ports;
2379         vector<string>::const_iterator i;
2380
2381         {
2382                 Glib::RWLock::ReaderLock rm (_processor_lock);
2383
2384                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2385
2386                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2387
2388                         if (d && d->target_route() == route) {
2389
2390                                 /* if the target is the control outs, then make sure
2391                                    we take note of which i-send is doing that.
2392                                 */
2393
2394                                 if (route == _session.monitor_out()) {
2395                                         _monitor_send = boost::dynamic_pointer_cast<Delivery>(d);
2396                                         if (_monitor_send->active()) {
2397                                                 _monitor_send->set_solo_level (1);
2398                                         } else {
2399                                                 _monitor_send->set_solo_level (0);
2400                                         }
2401                                 }
2402
2403                                 /* already listening via the specified IO: do nothing */
2404
2405                                 return 0;
2406                         }
2407                 }
2408         }
2409
2410         boost::shared_ptr<InternalSend> listener;
2411
2412         try {
2413
2414                 if (is_master()) {
2415                         
2416                         if (route == _session.monitor_out()) {
2417                                 /* master never sends to control outs */
2418                                 return 0;
2419                         } else {
2420                                 listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2421                         }
2422
2423                 } else {
2424                         listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2425                 }
2426
2427         } catch (failed_constructor& err) {
2428                 return -1;
2429         }
2430
2431         if (route == _session.monitor_out()) {
2432                 _monitor_send = listener;
2433         }
2434
2435         if (placement == PostFader) {
2436                 /* put it *really* at the end, not just after the panner (main outs)
2437                  */
2438                 add_processor (listener, _processors.end());
2439         } else {
2440                 add_processor (listener, PreFader);
2441         }
2442
2443         return 0;
2444 }
2445
2446 void
2447 Route::drop_listen (boost::shared_ptr<Route> route)
2448 {
2449         ProcessorStreams err;
2450         ProcessorList::iterator tmp;
2451
2452         Glib::RWLock::ReaderLock rl(_processor_lock);
2453         rl.acquire ();
2454
2455   again:
2456         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2457
2458                 boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2459
2460                 if (d && d->target_route() == route) {
2461                         rl.release ();
2462                         remove_processor (*x, &err);
2463                         rl.acquire ();
2464
2465                         /* list could have been demolished while we dropped the lock
2466                            so start over.
2467                         */
2468
2469                         goto again;
2470                 }
2471         }
2472
2473         rl.release ();
2474
2475         if (route == _session.monitor_out()) {
2476                 _monitor_send.reset ();
2477         }
2478 }
2479
2480 void
2481 Route::set_comment (string cmt, void *src)
2482 {
2483         _comment = cmt;
2484         comment_changed (src);
2485         _session.set_dirty ();
2486 }
2487
2488 bool
2489 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
2490 {
2491         FeedRecord fr (other, via_sends_only);
2492
2493         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
2494
2495         if (!result.second) {
2496
2497                 /* already a record for "other" - make sure sends-only information is correct */
2498                 if (!via_sends_only && result.first->sends_only) {
2499                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
2500                         frp->sends_only = false;
2501                 }
2502         }
2503         
2504         return result.second;
2505 }
2506
2507 void
2508 Route::clear_fed_by ()
2509 {
2510         _fed_by.clear ();
2511 }
2512
2513 bool
2514 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
2515 {
2516         const FedBy& fed_by (other->fed_by());
2517
2518         for (FedBy::iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
2519                 boost::shared_ptr<Route> sr = f->r.lock();
2520
2521                 if (sr && (sr.get() == this)) {
2522
2523                         if (via_sends_only) {
2524                                 *via_sends_only = f->sends_only;
2525                         }
2526
2527                         return true;
2528                 }
2529         }
2530
2531         return false;
2532 }
2533
2534 bool
2535 Route::direct_feeds (boost::shared_ptr<Route> other, bool* only_send)
2536 {
2537         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2538
2539         if (_output->connected_to (other->input())) {
2540                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2541                 if (only_send) {
2542                         *only_send = false;
2543                 }
2544
2545                 return true;
2546         }
2547
2548         
2549         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
2550
2551                 boost::shared_ptr<IOProcessor> iop;
2552
2553                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2554                         if (iop->feeds (other)) {
2555                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2556                                 if (only_send) {
2557                                         *only_send = true;
2558                                 }
2559                                 return true;
2560                         } else {
2561                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2562                         }
2563                 } else {
2564                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2565                 }
2566                         
2567         }
2568
2569         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2570         return false;
2571 }
2572
2573 void
2574 Route::handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2575 {
2576         nframes_t now = _session.transport_frame();
2577
2578         {
2579                 Glib::RWLock::ReaderLock lm (_processor_lock);
2580
2581                 if (!did_locate) {
2582                         automation_snapshot (now, true);
2583                 }
2584
2585                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2586
2587                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2588                                 (*i)->deactivate ();
2589                                 (*i)->activate ();
2590                         }
2591
2592                         (*i)->transport_stopped (now);
2593                 }
2594         }
2595
2596         _roll_delay = _initial_delay;
2597 }
2598
2599 void
2600 Route::input_change_handler (IOChange change, void * /*src*/)
2601 {
2602         if ((change & ConfigurationChanged)) {
2603                 configure_processors (0);
2604         }
2605 }
2606
2607 void
2608 Route::output_change_handler (IOChange change, void * /*src*/)
2609 {
2610         if ((change & ConfigurationChanged)) {
2611
2612                 /* XXX resize all listeners to match _main_outs? */
2613
2614                 // configure_processors (0);
2615         }
2616 }
2617
2618 uint32_t
2619 Route::pans_required () const
2620 {
2621         if (n_outputs().n_audio() < 2) {
2622                 return 0;
2623         }
2624
2625         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2626 }
2627
2628 int
2629 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
2630                 bool session_state_changing, bool /*can_record*/, bool /*rec_monitors_input*/)
2631 {
2632         if (n_outputs().n_total() == 0) {
2633                 return 0;
2634         }
2635
2636         if (!_active || n_inputs() == ChanCount::ZERO)  {
2637                 silence (nframes);
2638                 return 0;
2639         }
2640         if (session_state_changing) {
2641                 if (_session.transport_speed() != 0.0f) {
2642                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2643                            so we cannot use them. Be silent till this is over.
2644                            
2645                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2646                         */
2647                         silence (nframes);
2648                         return 0;
2649                 }
2650                 /* we're really not rolling, so we're either delivery silence or actually
2651                    monitoring, both of which are safe to do while session_state_changing is true.
2652                 */
2653         }
2654
2655         _amp->apply_gain_automation (false);
2656         passthru (start_frame, end_frame, nframes, 0);
2657
2658         return 0;
2659 }
2660
2661 nframes_t
2662 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2663 {
2664         if (_roll_delay > nframes) {
2665
2666                 _roll_delay -= nframes;
2667                 silence (nframes);
2668                 /* transport frame is not legal for caller to use */
2669                 return 0;
2670
2671         } else if (_roll_delay > 0) {
2672
2673                 nframes -= _roll_delay;
2674                 silence (_roll_delay);
2675                 /* we've written _roll_delay of samples into the
2676                    output ports, so make a note of that for
2677                    future reference.
2678                 */
2679                 _main_outs->increment_output_offset (_roll_delay);
2680                 transport_frame += _roll_delay;
2681
2682                 _roll_delay = 0;
2683         }
2684
2685         return nframes;
2686 }
2687
2688 int
2689 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2690              bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2691 {
2692         {
2693                 // automation snapshot can also be called from the non-rt context
2694                 // and it uses the processor list, so we try to acquire the lock here
2695                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2696
2697                 if (lm.locked()) {
2698                         automation_snapshot (_session.transport_frame(), false);
2699                 }
2700         }
2701
2702         if (n_outputs().n_total() == 0) {
2703                 return 0;
2704         }
2705
2706         if (!_active || n_inputs().n_total() == 0) {
2707                 silence (nframes);
2708                 return 0;
2709         }
2710
2711         nframes_t unused = 0;
2712
2713         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2714                 return 0;
2715         }
2716
2717         _silent = false;
2718
2719         passthru (start_frame, end_frame, nframes, declick);
2720
2721         return 0;
2722 }
2723
2724 int
2725 Route::silent_roll (nframes_t nframes, sframes_t /*start_frame*/, sframes_t /*end_frame*/,
2726                     bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2727 {
2728         silence (nframes);
2729         return 0;
2730 }
2731
2732 void
2733 Route::toggle_monitor_input ()
2734 {
2735         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2736                 i->ensure_monitor_input( ! i->monitoring_input());
2737         }
2738 }
2739
2740 bool
2741 Route::has_external_redirects () const
2742 {
2743         // FIXME: what about sends? - they don't return a signal back to ardour?
2744
2745         boost::shared_ptr<const PortInsert> pi;
2746
2747         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2748
2749                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2750
2751                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2752
2753                                 string port_name = port->name();
2754                                 string client_name = port_name.substr (0, port_name.find(':'));
2755
2756                                 /* only say "yes" if the redirect is actually in use */
2757
2758                                 if (client_name != "ardour" && pi->active()) {
2759                                         return true;
2760                                 }
2761                         }
2762                 }
2763         }
2764
2765         return false;
2766 }
2767
2768 void
2769 Route::flush_processors ()
2770 {
2771         /* XXX shouldn't really try to take this lock, since
2772            this is called from the RT audio thread.
2773         */
2774
2775         Glib::RWLock::ReaderLock lm (_processor_lock);
2776
2777         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2778                 (*i)->deactivate ();
2779                 (*i)->activate ();
2780         }
2781 }
2782
2783 void
2784 Route::set_meter_point (MeterPoint p)
2785 {
2786         /* CAN BE CALLED FROM PROCESS CONTEXT */
2787
2788         if (_meter_point == p) {
2789                 return;
2790         }
2791
2792         bool meter_was_visible_to_user = _meter->display_to_user ();
2793
2794         {
2795                 Glib::RWLock::WriterLock lm (_processor_lock);
2796         
2797                 if (p != MeterCustom) {
2798                         // Move meter in the processors list to reflect the new position
2799                         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2800                         _processors.erase(loc);
2801                         switch (p) {
2802                         case MeterInput:
2803                                 loc = _processors.begin();
2804                                 break;
2805                         case MeterPreFader:
2806                                 loc = find (_processors.begin(), _processors.end(), _amp);
2807                                 break;
2808                         case MeterPostFader:
2809                                 loc = _processors.end();
2810                                 break;
2811                         default:
2812                                 break;
2813                         }
2814                         
2815                         ChanCount m_in;
2816                         
2817                         if (loc == _processors.begin()) {
2818                                 m_in = _input->n_ports();
2819                         } else {
2820                                 ProcessorList::iterator before = loc;
2821                                 --before;
2822                                 m_in = (*before)->output_streams ();
2823                         }
2824                         
2825                         _meter->reflect_inputs (m_in);
2826                         
2827                         _processors.insert (loc, _meter);
2828                         
2829                         /* we do not need to reconfigure the processors, because the meter
2830                            (a) is always ready to handle processor_max_streams
2831                            (b) is always an N-in/N-out processor, and thus moving
2832                            it doesn't require any changes to the other processors.
2833                         */
2834                         
2835                         _meter->set_display_to_user (false);
2836                         
2837                 } else {
2838                         
2839                         // just make it visible and let the user move it
2840                         
2841                         _meter->set_display_to_user (true);
2842                 }
2843         }
2844
2845         _meter_point = p;
2846         meter_change (); /* EMIT SIGNAL */
2847
2848         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
2849         
2850         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
2851 }
2852
2853 void
2854 Route::put_monitor_send_at (Placement p)
2855 {
2856         if (!_monitor_send) {
2857                 return;
2858         }
2859
2860         {
2861                 Glib::RWLock::WriterLock lm (_processor_lock);
2862                 ProcessorList as_it_was (_processors);
2863                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _monitor_send);
2864                 _processors.erase(loc);
2865                 
2866                 switch (p) {
2867                 case PreFader:
2868                         loc = find(_processors.begin(), _processors.end(), _amp);
2869                         if (loc != _processors.begin()) {
2870                                 --loc;
2871                         }
2872                         break;
2873                 case PostFader:
2874                         loc = _processors.end();
2875                         break;
2876                 }
2877                 
2878                 _processors.insert (loc, _monitor_send);
2879
2880                 if (configure_processors_unlocked (0)) {
2881                         _processors = as_it_was;
2882                         configure_processors_unlocked (0); // it worked before we tried to add it ...
2883                         return;
2884                 }
2885         }
2886
2887         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2888         _session.set_dirty ();
2889 }
2890
2891 nframes_t
2892 Route::update_total_latency ()
2893 {
2894         nframes_t old = _output->effective_latency();
2895         nframes_t own_latency = _output->user_latency();
2896
2897         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2898                 if ((*i)->active ()) {
2899                         own_latency += (*i)->signal_latency ();
2900                 }
2901         }
2902
2903         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal redirect latency = %2\n", _name, own_latency));
2904
2905         _output->set_port_latency (own_latency);
2906
2907         if (_output->user_latency() == 0) {
2908
2909                 /* this (virtual) function is used for pure Routes,
2910                    not derived classes like AudioTrack.  this means
2911                    that the data processed here comes from an input
2912                    port, not prerecorded material, and therefore we
2913                    have to take into account any input latency.
2914                 */
2915
2916                 own_latency += _input->signal_latency ();
2917         }
2918
2919         if (old != own_latency) {
2920                 _output->set_latency_delay (own_latency);
2921                 signal_latency_changed (); /* EMIT SIGNAL */
2922         }
2923
2924         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: input latency = %2 total = %3\n", _name, _input->signal_latency(), own_latency));
2925
2926         return _output->effective_latency ();
2927 }
2928
2929 void
2930 Route::set_user_latency (nframes_t nframes)
2931 {
2932         _output->set_user_latency (nframes);
2933         _session.update_latency_compensation (false, false);
2934 }
2935
2936 void
2937 Route::set_latency_delay (nframes_t longest_session_latency)
2938 {
2939         nframes_t old = _initial_delay;
2940
2941         if (_output->effective_latency() < longest_session_latency) {
2942                 _initial_delay = longest_session_latency - _output->effective_latency();
2943         } else {
2944                 _initial_delay = 0;
2945         }
2946
2947         if (_initial_delay != old) {
2948                 initial_delay_changed (); /* EMIT SIGNAL */
2949         }
2950
2951         if (_session.transport_stopped()) {
2952                 _roll_delay = _initial_delay;
2953         }
2954 }
2955
2956 void
2957 Route::automation_snapshot (nframes_t now, bool force)
2958 {
2959         panner()->automation_snapshot (now, force);
2960         
2961         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2962                 (*i)->automation_snapshot (now, force);
2963         }
2964 }
2965
2966 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2967         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation),
2968                              boost::shared_ptr<AutomationList>(), name)
2969         , route (r)
2970 {
2971         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2972         set_list (gl);
2973 }
2974
2975 void
2976 Route::SoloControllable::set_value (float val)
2977 {
2978         bool bval = ((val >= 0.5f) ? true: false);
2979 # if 0
2980         this is how it should be done 
2981
2982         boost::shared_ptr<RouteList> rl (new RouteList);
2983         rl->push_back (route);
2984
2985         if (Config->get_solo_control_is_listen_control()) {
2986                 _session.set_listen (rl, bval);
2987         } else {
2988                 _session.set_solo (rl, bval);
2989         }
2990 #else
2991         route.set_solo (bval, this);
2992 #endif
2993 }
2994
2995 float
2996 Route::SoloControllable::get_value (void) const
2997 {
2998         if (Config->get_solo_control_is_listen_control()) {
2999                 return route.listening() ? 1.0f : 0.0f;
3000         } else {
3001                 return route.self_soloed() ? 1.0f : 0.0f;
3002         }
3003 }
3004
3005 Route::MuteControllable::MuteControllable (std::string name, Route& r)
3006         : AutomationControl (r.session(), Evoral::Parameter (MuteAutomation),
3007                              boost::shared_ptr<AutomationList>(), name)
3008         , route (r)
3009 {
3010         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
3011         set_list (gl);
3012 }
3013
3014 void
3015 Route::MuteControllable::set_value (float val)
3016 {
3017         bool bval = ((val >= 0.5f) ? true: false);
3018 # if 0
3019         this is how it should be done 
3020
3021         boost::shared_ptr<RouteList> rl (new RouteList);
3022         rl->push_back (route);
3023         _session.set_mute (rl, bval);
3024 #else
3025         route.set_mute (bval, this);
3026 #endif
3027 }
3028
3029 float
3030 Route::MuteControllable::get_value (void) const
3031 {
3032         return route.muted() ? 1.0f : 0.0f;
3033 }
3034
3035 void
3036 Route::set_block_size (nframes_t nframes)
3037 {
3038         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3039                 (*i)->set_block_size (nframes);
3040         }
3041         
3042         _session.ensure_buffers (n_process_buffers ());
3043 }
3044
3045 void
3046 Route::protect_automation ()
3047 {
3048         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3049                 (*i)->protect_automation();
3050 }
3051
3052 void
3053 Route::set_pending_declick (int declick)
3054 {
3055         if (_declickable) {
3056                 /* this call is not allowed to turn off a pending declick unless "force" is true */
3057                 if (declick) {
3058                         _pending_declick = declick;
3059                 }
3060                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
3061         } else {
3062                 _pending_declick = 0;
3063         }
3064
3065 }
3066
3067 /** Shift automation forwards from a particular place, thereby inserting time.
3068  *  Adds undo commands for any shifts that are performed.
3069  *
3070  * @param pos Position to start shifting from.
3071  * @param frames Amount to shift forwards by.
3072  */
3073
3074 void
3075 Route::shift (nframes64_t /*pos*/, nframes64_t /*frames*/)
3076 {
3077 #ifdef THIS_NEEDS_FIXING_FOR_V3
3078
3079         /* gain automation */
3080         XMLNode &before = _gain_control->get_state ();
3081         _gain_control->shift (pos, frames);
3082         XMLNode &after = _gain_control->get_state ();
3083         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
3084
3085         /* pan automation */
3086         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
3087                 Curve & c = (*i)->automation ();
3088                 XMLNode &before = c.get_state ();
3089                 c.shift (pos, frames);
3090                 XMLNode &after = c.get_state ();
3091                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
3092         }
3093
3094         /* redirect automation */
3095         {
3096                 Glib::RWLock::ReaderLock lm (redirect_lock);
3097                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
3098
3099                         set<uint32_t> a;
3100                         (*i)->what_has_automation (a);
3101
3102                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
3103                                 AutomationList & al = (*i)->automation_list (*j);
3104                                 XMLNode &before = al.get_state ();
3105                                 al.shift (pos, frames);
3106                                 XMLNode &after = al.get_state ();
3107                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
3108                         }
3109                 }
3110         }
3111 #endif
3112
3113 }
3114
3115
3116 int
3117 Route::save_as_template (const string& path, const string& name)
3118 {
3119         XMLNode& node (state (false));
3120         XMLTree tree;
3121
3122         IO::set_name_in_state (*node.children().front(), name);
3123
3124         tree.set_root (&node);
3125         return tree.write (path.c_str());
3126 }
3127
3128
3129 bool
3130 Route::set_name (const string& str)
3131 {
3132         bool ret;
3133         string ioproc_name;
3134         string name;
3135
3136         name = Route::ensure_track_or_route_name (str, _session);
3137         SessionObject::set_name (name);
3138
3139         ret = (_input->set_name(name) && _output->set_name(name));
3140
3141         if (ret) {
3142
3143                 Glib::RWLock::ReaderLock lm (_processor_lock);
3144
3145                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3146
3147                         /* rename all I/O processors that have inputs or outputs */
3148
3149                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
3150
3151                         if (iop && (iop->output() || iop->input())) {
3152                                 if (!iop->set_name (name)) {
3153                                         ret = false;
3154                                 }
3155                         }
3156                 }
3157
3158         }
3159
3160         return ret;
3161 }
3162
3163 boost::shared_ptr<Send>
3164 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3165 {
3166         Glib::RWLock::ReaderLock lm (_processor_lock);
3167
3168         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3169                 boost::shared_ptr<InternalSend> send;
3170
3171                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3172                         if (send->target_route() == target) {
3173                                 return send;
3174                         }
3175                 }
3176         }
3177
3178         return boost::shared_ptr<Send>();
3179 }
3180
3181 void
3182 Route::set_phase_invert (bool yn)
3183 {
3184         if (_phase_invert != yn) {
3185                 if (yn) {
3186                         _phase_invert = 0xffff; // XXX all channels
3187                 } else {
3188                         _phase_invert = 0; // XXX no channels
3189                 }
3190
3191                 phase_invert_changed (); /* EMIT SIGNAL */
3192                 _session.set_dirty ();
3193         }
3194 }
3195
3196 bool
3197 Route::phase_invert () const
3198 {
3199         return _phase_invert != 0;
3200 }
3201
3202 void
3203 Route::set_denormal_protection (bool yn)
3204 {
3205         if (_denormal_protection != yn) {
3206                 _denormal_protection = yn;
3207                 denormal_protection_changed (); /* EMIT SIGNAL */
3208         }
3209 }
3210
3211 bool
3212 Route::denormal_protection () const
3213 {
3214         return _denormal_protection;
3215 }
3216
3217 void
3218 Route::set_active (bool yn)
3219 {
3220         if (_active != yn) {
3221                 _active = yn;
3222                 _input->set_active (yn);
3223                 _output->set_active (yn);
3224                 active_changed (); // EMIT SIGNAL
3225         }
3226 }
3227
3228 void
3229 Route::meter ()
3230 {
3231         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3232
3233         assert (_meter);
3234
3235         _meter->meter ();
3236
3237         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3238
3239                 boost::shared_ptr<Send> s;
3240                 boost::shared_ptr<Return> r;
3241
3242                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3243                         s->meter()->meter();
3244                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3245                         r->meter()->meter ();
3246                 }
3247         }
3248 }
3249
3250 boost::shared_ptr<Panner>
3251 Route::panner() const
3252 {
3253         return _main_outs->panner();
3254 }
3255
3256 boost::shared_ptr<AutomationControl>
3257 Route::gain_control() const
3258 {
3259         return _amp->gain_control();
3260 }
3261
3262 boost::shared_ptr<AutomationControl>
3263 Route::get_control (const Evoral::Parameter& param)
3264 {
3265         /* either we own the control or .... */
3266
3267         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3268
3269         if (!c) {
3270
3271                 /* maybe one of our processors does or ... */
3272
3273                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3274                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3275                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3276                                 break;
3277                         }
3278                 }
3279         }
3280
3281         if (!c) {
3282
3283                 /* nobody does so we'll make a new one */
3284
3285                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3286                 add_control(c);
3287         }
3288
3289         return c;
3290 }
3291
3292 boost::shared_ptr<Processor>
3293 Route::nth_plugin (uint32_t n)
3294 {
3295         Glib::RWLock::ReaderLock lm (_processor_lock);
3296         ProcessorList::iterator i;
3297
3298         for (i = _processors.begin(); i != _processors.end(); ++i) {
3299                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3300                         if (n-- == 0) {
3301                                 return *i;
3302                         }
3303                 }
3304         }
3305
3306         return boost::shared_ptr<Processor> ();
3307 }
3308
3309 boost::shared_ptr<Processor>
3310 Route::nth_send (uint32_t n)
3311 {
3312         Glib::RWLock::ReaderLock lm (_processor_lock);
3313         ProcessorList::iterator i;
3314
3315         for (i = _processors.begin(); i != _processors.end(); ++i) {
3316                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3317                         if (n-- == 0) {
3318                                 return *i;
3319                         }
3320                 } 
3321         }
3322
3323         return boost::shared_ptr<Processor> ();
3324 }
3325
3326 bool
3327 Route::has_io_processor_named (const string& name)
3328 {
3329         Glib::RWLock::ReaderLock lm (_processor_lock);
3330         ProcessorList::iterator i;
3331         
3332         for (i = _processors.begin(); i != _processors.end(); ++i) {
3333                 if (boost::dynamic_pointer_cast<Send> (*i) ||
3334                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
3335                         if ((*i)->name() == name) {
3336                                 return true;
3337                         }
3338                 }
3339         }
3340         
3341         return false;
3342 }