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