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