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