drastic, deep and wide changes to make RouteGroup use boost::shared_ptr<Route> and...
[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 (false);
84         add_processor (_meter, PostFader);
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         _phase_invert = 0;
139         _denormal_protection = false;
140
141         /* add standard controls */
142
143         add_control (_solo_control);
144         add_control (_mute_master);
145
146         /* input and output objects */
147
148         _input.reset (new IO (_session, _name, IO::Input, _default_type));
149         _output.reset (new IO (_session, _name, IO::Output, _default_type));
150
151         _input->changed.connect (mem_fun (this, &Route::input_change_handler));
152         _output->changed.connect (mem_fun (this, &Route::output_change_handler));
153
154         /* add amp processor  */
155
156         _amp.reset (new Amp (_session, _mute_master));
157         add_processor (_amp, PostFader);
158 }
159
160 Route::~Route ()
161 {
162         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
163         Metering::disconnect (_meter_connection);
164
165         /* don't use clear_processors here, as it depends on the session which may
166            be half-destroyed by now */
167
168         Glib::RWLock::WriterLock lm (_processor_lock);
169         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
170                 (*i)->drop_references ();
171         }
172
173         _processors.clear ();
174 }
175
176 void
177 Route::set_remote_control_id (uint32_t id)
178 {
179         if (id != _remote_control_id) {
180                 _remote_control_id = id;
181                 RemoteControlIDChanged ();
182         }
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 (RouteProcessorChange ()); /* 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
987                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
988
989                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
990
991                         // Ensure meter only appears in the list once
992                         if (*i == _meter) {
993                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
994                                 if (m != _processors.end()) {
995                                         _processors.erase(m);
996                                 }
997                         }
998
999                         boost::shared_ptr<PluginInsert> pi;
1000
1001                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1002                                 pi->set_count (1);
1003
1004                                 ChanCount m = max (pi->input_streams(), pi->output_streams());
1005
1006                                 if (m > potential_max_streams) {
1007                                         potential_max_streams = m;
1008                                 }
1009                         }
1010
1011                         ProcessorList::iterator inserted = _processors.insert (iter, *i);
1012
1013                         if ((*i)->active()) {
1014                                 (*i)->activate ();
1015                         }
1016
1017                         if (configure_processors_unlocked (err)) {
1018                                 _processors.erase (inserted);
1019                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
1020                                 return -1;
1021                         }
1022
1023                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
1024                 }
1025
1026                 _output->set_user_latency (0);
1027         }
1028
1029         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1030
1031         return 0;
1032 }
1033
1034 void
1035 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1036 {
1037         if (p == PreFader) {
1038                 start = _processors.begin();
1039                 end = find(_processors.begin(), _processors.end(), _amp);
1040         } else {
1041                 start = find(_processors.begin(), _processors.end(), _amp);
1042                 ++start;
1043                 end = _processors.end();
1044         }
1045 }
1046
1047 /** Turn off all processors with a given placement
1048  * @param p Placement of processors to disable
1049  */
1050 void
1051 Route::disable_processors (Placement p)
1052 {
1053         Glib::RWLock::ReaderLock lm (_processor_lock);
1054
1055         ProcessorList::iterator start, end;
1056         placement_range(p, start, end);
1057
1058         for (ProcessorList::iterator i = start; i != end; ++i) {
1059                 (*i)->deactivate ();
1060         }
1061
1062         _session.set_dirty ();
1063 }
1064
1065 /** Turn off all redirects
1066  */
1067 void
1068 Route::disable_processors ()
1069 {
1070         Glib::RWLock::ReaderLock lm (_processor_lock);
1071
1072         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1073                 (*i)->deactivate ();
1074         }
1075
1076         _session.set_dirty ();
1077 }
1078
1079 /** Turn off all redirects with a given placement
1080  * @param p Placement of redirects to disable
1081  */
1082 void
1083 Route::disable_plugins (Placement p)
1084 {
1085         Glib::RWLock::ReaderLock lm (_processor_lock);
1086
1087         ProcessorList::iterator start, end;
1088         placement_range(p, start, end);
1089
1090         for (ProcessorList::iterator i = start; i != end; ++i) {
1091                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1092                         (*i)->deactivate ();
1093                 }
1094         }
1095
1096         _session.set_dirty ();
1097 }
1098
1099 /** Turn off all plugins
1100  */
1101 void
1102 Route::disable_plugins ()
1103 {
1104         Glib::RWLock::ReaderLock lm (_processor_lock);
1105
1106         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1107                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1108                         (*i)->deactivate ();
1109                 }
1110         }
1111
1112         _session.set_dirty ();
1113 }
1114
1115
1116 void
1117 Route::ab_plugins (bool forward)
1118 {
1119         Glib::RWLock::ReaderLock lm (_processor_lock);
1120
1121         if (forward) {
1122
1123                 /* forward = turn off all active redirects, and mark them so that the next time
1124                    we go the other way, we will revert them
1125                 */
1126
1127                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1128                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1129                                 continue;
1130                         }
1131
1132                         if ((*i)->active()) {
1133                                 (*i)->deactivate ();
1134                                 (*i)->set_next_ab_is_active (true);
1135                         } else {
1136                                 (*i)->set_next_ab_is_active (false);
1137                         }
1138                 }
1139
1140         } else {
1141
1142                 /* backward = if the redirect was marked to go active on the next ab, do so */
1143
1144                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1145
1146                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1147                                 continue;
1148                         }
1149
1150                         if ((*i)->get_next_ab_is_active()) {
1151                                 (*i)->activate ();
1152                         } else {
1153                                 (*i)->deactivate ();
1154                         }
1155                 }
1156         }
1157
1158         _session.set_dirty ();
1159 }
1160
1161
1162 /** Remove processors with a given placement.
1163  * @param p Placement of processors to remove.
1164  */
1165 void
1166 Route::clear_processors (Placement p)
1167 {
1168         const ChanCount old_pms = processor_max_streams;
1169
1170         if (!_session.engine().connected()) {
1171                 return;
1172         }
1173
1174         bool already_deleting = _session.deletion_in_progress();
1175         if (!already_deleting) {
1176                 _session.set_deletion_in_progress();
1177         }
1178
1179         {
1180                 Glib::RWLock::WriterLock lm (_processor_lock);
1181                 ProcessorList new_list;
1182                 ProcessorStreams err;
1183                 bool seen_amp = false;
1184
1185                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1186
1187                         if (*i == _amp) {
1188                                 seen_amp = true;
1189                         }
1190
1191                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1192
1193                                 /* you can't remove these */
1194
1195                                 new_list.push_back (*i);
1196
1197                         } else {
1198                                 if (seen_amp) {
1199
1200                                         switch (p) {
1201                                         case PreFader:
1202                                                 new_list.push_back (*i);
1203                                                 break;
1204                                         case PostFader:
1205                                                 (*i)->drop_references ();
1206                                                 break;
1207                                         }
1208
1209                                 } else {
1210
1211                                         switch (p) {
1212                                         case PreFader:
1213                                                 (*i)->drop_references ();
1214                                                 break;
1215                                         case PostFader:
1216                                                 new_list.push_back (*i);
1217                                                 break;
1218                                         }
1219                                 }
1220                         }
1221                 }
1222
1223                 _processors = new_list;
1224                 configure_processors_unlocked (&err); // this can't fail
1225         }
1226
1227         processor_max_streams.reset();
1228         _have_internal_generator = false;
1229         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1230
1231         if (!already_deleting) {
1232                 _session.clear_deletion_in_progress();
1233         }
1234 }
1235
1236 int
1237 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1238 {
1239         /* these can never be removed */
1240
1241         if (processor == _amp || processor == _meter || processor == _main_outs) {
1242                 return 0;
1243         }
1244
1245         ChanCount old_pms = processor_max_streams;
1246
1247         if (!_session.engine().connected()) {
1248                 return 1;
1249         }
1250
1251         processor_max_streams.reset();
1252
1253         {
1254                 Glib::RWLock::WriterLock lm (_processor_lock);
1255                 ProcessorList::iterator i;
1256                 bool removed = false;
1257
1258                 for (i = _processors.begin(); i != _processors.end(); ) {
1259                         if (*i == processor) {
1260
1261                                 /* move along, see failure case for configure_processors()
1262                                    where we may need to reconfigure the processor.
1263                                 */
1264
1265                                 /* stop redirects that send signals to JACK ports
1266                                    from causing noise as a result of no longer being
1267                                    run.
1268                                 */
1269
1270                                 boost::shared_ptr<IOProcessor> iop;
1271
1272                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1273                                         if (iop->input()) {
1274                                                 iop->input()->disconnect (this);
1275                                         }
1276                                         if (iop->output()) {
1277                                                 iop->output()->disconnect (this);
1278                                         }
1279                                 }
1280
1281                                 i = _processors.erase (i);
1282                                 removed = true;
1283                                 break;
1284
1285                         } else {
1286                                 ++i;
1287                         }
1288
1289                         _output->set_user_latency (0);
1290                 }
1291
1292                 if (!removed) {
1293                         /* what? */
1294                         return 1;
1295                 }
1296
1297                 if (configure_processors_unlocked (err)) {
1298                         /* get back to where we where */
1299                         _processors.insert (i, processor);
1300                         /* we know this will work, because it worked before :) */
1301                         configure_processors_unlocked (0);
1302                         return -1;
1303                 }
1304
1305                 _have_internal_generator = false;
1306
1307                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1308                         boost::shared_ptr<PluginInsert> pi;
1309
1310                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1311                                 if (pi->is_generator()) {
1312                                         _have_internal_generator = true;
1313                                         break;
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319         processor->drop_references ();
1320         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1321
1322         return 0;
1323 }
1324
1325 int
1326 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1327 {
1328         ProcessorList deleted;
1329         ProcessorList as_we_were;
1330
1331         if (!_session.engine().connected()) {
1332                 return 1;
1333         }
1334
1335         processor_max_streams.reset();
1336
1337         {
1338                 Glib::RWLock::WriterLock lm (_processor_lock);
1339                 ProcessorList::iterator i;
1340                 boost::shared_ptr<Processor> processor;
1341
1342                 as_we_were = _processors;
1343
1344                 for (i = _processors.begin(); i != _processors.end(); ) {
1345
1346                         processor = *i;
1347
1348                         /* these can never be removed */
1349
1350                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1351                                 ++i;
1352                                 continue;
1353                         }
1354
1355                         /* see if its in the list of processors to delete */
1356
1357                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1358                                 ++i;
1359                                 continue;
1360                         }
1361
1362                         /* stop IOProcessors that send to JACK ports
1363                            from causing noise as a result of no longer being
1364                            run.
1365                         */
1366
1367                         boost::shared_ptr<IOProcessor> iop;
1368
1369                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1370                                 iop->disconnect ();
1371                         }
1372
1373                         deleted.push_back (processor);
1374                         i = _processors.erase (i);
1375                 }
1376
1377                 if (deleted.empty()) {
1378                         /* none of those in the requested list were found */
1379                         return 0;
1380                 }
1381
1382                 _output->set_user_latency (0);
1383
1384                 if (configure_processors_unlocked (err)) {
1385                         /* get back to where we where */
1386                         _processors = as_we_were;
1387                         /* we know this will work, because it worked before :) */
1388                         configure_processors_unlocked (0);
1389                         return -1;
1390                 }
1391
1392                 _have_internal_generator = false;
1393
1394                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1395                         boost::shared_ptr<PluginInsert> pi;
1396
1397                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1398                                 if (pi->is_generator()) {
1399                                         _have_internal_generator = true;
1400                                         break;
1401                                 }
1402                         }
1403                 }
1404         }
1405
1406         /* now try to do what we need to so that those that were removed will be deleted */
1407
1408         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1409                 (*i)->drop_references ();
1410         }
1411
1412         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1413
1414         return 0;
1415 }
1416
1417
1418 int
1419 Route::configure_processors (ProcessorStreams* err)
1420 {
1421         if (!_in_configure_processors) {
1422                 Glib::RWLock::WriterLock lm (_processor_lock);
1423                 return configure_processors_unlocked (err);
1424         }
1425         return 0;
1426 }
1427
1428 /** Configure the input/output configuration of each processor in the processors list.
1429  * Return 0 on success, otherwise configuration is impossible.
1430  */
1431 int
1432 Route::configure_processors_unlocked (ProcessorStreams* err)
1433 {
1434         if (_in_configure_processors) {
1435            return 0;
1436         }
1437
1438         _in_configure_processors = true;
1439
1440         // Check each processor in order to see if we can configure as requested
1441         ChanCount in = _input->n_ports ();
1442         ChanCount out;
1443         list< pair<ChanCount,ChanCount> > configuration;
1444         uint32_t index = 0;
1445
1446         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1447 #ifndef NDEBUG
1448         DEBUG_TRACE (DEBUG::Processors, "{\n");
1449         for (list<boost::shared_ptr<Processor> >::const_iterator p = _processors.begin(); p != _processors.end(); ++p) {
1450                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID = %2\n", (*p)->name(), (*p)->id()));
1451         }
1452         DEBUG_TRACE (DEBUG::Processors, "}\n");
1453 #endif
1454
1455         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1456
1457                 if ((*p)->can_support_io_configuration(in, out)) {
1458                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1in = %2 out = %3\n",(*p)->name(), in, out));
1459                         configuration.push_back(make_pair(in, out));
1460                         in = out;
1461                 } else {
1462                         if (err) {
1463                                 err->index = index;
1464                                 err->count = in;
1465                         }
1466                         _in_configure_processors = false;
1467                         return -1;
1468                 }
1469         }
1470
1471         // We can, so configure everything
1472         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1473         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1474                 (*p)->configure_io(c->first, c->second);
1475                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1476                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1477                 out = c->second;
1478         }
1479
1480         if (_meter) {
1481                 _meter->reset_max_channels (processor_max_streams);
1482         }
1483
1484         /* make sure we have sufficient scratch buffers to cope with the new processor
1485            configuration */
1486         _session.ensure_buffers (n_process_buffers ());
1487
1488         _in_configure_processors = false;
1489         return 0;
1490 }
1491
1492 void
1493 Route::all_processors_flip ()
1494 {
1495         Glib::RWLock::ReaderLock lm (_processor_lock);
1496
1497         if (_processors.empty()) {
1498                 return;
1499         }
1500
1501         bool first_is_on = _processors.front()->active();
1502
1503         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1504                 if (first_is_on) {
1505                         (*i)->deactivate ();
1506                 } else {
1507                         (*i)->activate ();
1508                 }
1509         }
1510
1511         _session.set_dirty ();
1512 }
1513
1514 /** Set all processors with a given placement to a given active state.
1515  * @param p Placement of processors to change.
1516  * @param state New active state for those processors.
1517  */
1518 void
1519 Route::all_processors_active (Placement p, bool state)
1520 {
1521         Glib::RWLock::ReaderLock lm (_processor_lock);
1522
1523         if (_processors.empty()) {
1524                 return;
1525         }
1526         ProcessorList::iterator start, end;
1527         placement_range(p, start, end);
1528
1529         bool before_amp = true;
1530         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1531                 if ((*i) == _amp) {
1532                         before_amp = false;
1533                         continue;
1534                 }
1535                 if (p == PreFader && before_amp) {
1536                         if (state) {
1537                                 (*i)->activate ();
1538                         } else {
1539                                 (*i)->deactivate ();
1540                         }
1541                 }
1542         }
1543
1544         _session.set_dirty ();
1545 }
1546
1547 bool
1548 Route::processor_is_prefader (boost::shared_ptr<Processor> p)
1549 {
1550         bool pre_fader = true;
1551         Glib::RWLock::ReaderLock lm (_processor_lock);
1552
1553         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1554
1555                 /* semantic note: if p == amp, we want to return true, so test
1556                    for equality before checking if this is the amp
1557                 */
1558
1559                 if ((*i) == p) {
1560                         break;
1561                 }
1562
1563                 if ((*i) == _amp) {
1564                         pre_fader = false;
1565                         break;
1566                 }
1567         }
1568
1569         return pre_fader;
1570 }
1571
1572 int
1573 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1574 {
1575         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1576            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1577            processors in the current actual processor list that are hidden. Any visible processors
1578            in the current list but not in "new_order" will be assumed to be deleted.
1579         */
1580
1581         {
1582                 Glib::RWLock::WriterLock lm (_processor_lock);
1583                 ChanCount old_pms = processor_max_streams;
1584                 ProcessorList::iterator oiter;
1585                 ProcessorList::const_iterator niter;
1586                 ProcessorList as_it_was_before = _processors;
1587                 ProcessorList as_it_will_be;
1588
1589                 oiter = _processors.begin();
1590                 niter = new_order.begin();
1591
1592                 while (niter !=  new_order.end()) {
1593
1594                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1595                            then append it to the temp list.
1596
1597                            Otherwise, see if the next processor in the old list is in the new list. if not,
1598                            its been deleted. If its there, append it to the temp list.
1599                         */
1600
1601                         if (oiter == _processors.end()) {
1602
1603                                 /* no more elements in the old list, so just stick the rest of
1604                                    the new order onto the temp list.
1605                                 */
1606
1607                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1608                                 while (niter != new_order.end()) {
1609                                         ++niter;
1610                                 }
1611                                 break;
1612
1613                         } else {
1614
1615                                 if (!(*oiter)->display_to_user()) {
1616
1617                                         as_it_will_be.push_back (*oiter);
1618
1619                                 } else {
1620
1621                                         /* visible processor: check that its in the new order */
1622
1623                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1624                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1625                                         } else {
1626                                                 /* ignore this one, and add the next item from the new order instead */
1627                                                 as_it_will_be.push_back (*niter);
1628                                                 ++niter;
1629                                         }
1630                                 }
1631
1632                                 /* now remove from old order - its taken care of no matter what */
1633                                 oiter = _processors.erase (oiter);
1634                         }
1635
1636                 }
1637
1638                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1639
1640                 if (configure_processors_unlocked (err)) {
1641                         _processors = as_it_was_before;
1642                         processor_max_streams = old_pms;
1643                         return -1;
1644                 }
1645         }
1646
1647         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1648
1649         return 0;
1650 }
1651
1652 XMLNode&
1653 Route::get_state()
1654 {
1655         return state(true);
1656 }
1657
1658 XMLNode&
1659 Route::get_template()
1660 {
1661         return state(false);
1662 }
1663
1664 XMLNode&
1665 Route::state(bool full_state)
1666 {
1667         XMLNode *node = new XMLNode("Route");
1668         ProcessorList::iterator i;
1669         char buf[32];
1670
1671         id().print (buf, sizeof (buf));
1672         node->add_property("id", buf);
1673         node->add_property ("name", _name);
1674         node->add_property("default-type", _default_type.to_string());
1675
1676         if (_flags) {
1677                 node->add_property("flags", enum_2_string (_flags));
1678         }
1679
1680         node->add_property("active", _active?"yes":"no");
1681         node->add_property("phase-invert", _phase_invert?"yes":"no");
1682         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1683         node->add_property("meter-point", enum_2_string (_meter_point));
1684
1685         if (_route_group) {
1686                 node->add_property("route-group", _route_group->name());
1687         }
1688
1689         string order_string;
1690         OrderKeys::iterator x = order_keys.begin();
1691
1692         while (x != order_keys.end()) {
1693                 order_string += string ((*x).first);
1694                 order_string += '=';
1695                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1696                 order_string += buf;
1697
1698                 ++x;
1699
1700                 if (x == order_keys.end()) {
1701                         break;
1702                 }
1703
1704                 order_string += ':';
1705         }
1706         node->add_property ("order-keys", order_string);
1707         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1708         snprintf (buf, sizeof (buf), "%d", _soloed_by_others);
1709         node->add_property ("soloed-by-others", buf);
1710
1711         node->add_child_nocopy (_input->state (full_state));
1712         node->add_child_nocopy (_output->state (full_state));
1713         node->add_child_nocopy (_solo_control->get_state ());
1714         node->add_child_nocopy (_mute_master->get_state ());
1715
1716         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1717         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1718         remote_control_node->add_property (X_("id"), buf);
1719         node->add_child_nocopy (*remote_control_node);
1720
1721         if (_comment.length()) {
1722                 XMLNode *cmt = node->add_child ("Comment");
1723                 cmt->add_content (_comment);
1724         }
1725
1726         for (i = _processors.begin(); i != _processors.end(); ++i) {
1727                 node->add_child_nocopy((*i)->state (full_state));
1728         }
1729
1730         if (_extra_xml){
1731                 node->add_child_copy (*_extra_xml);
1732         }
1733
1734         return *node;
1735 }
1736
1737 int
1738 Route::set_state (const XMLNode& node, int version)
1739 {
1740         return _set_state (node, version, true);
1741 }
1742
1743 int
1744 Route::_set_state (const XMLNode& node, int version, bool /*call_base*/)
1745 {
1746         if (version < 3000) {
1747                 return _set_state_2X (node, version);
1748         }
1749
1750         XMLNodeList nlist;
1751         XMLNodeConstIterator niter;
1752         XMLNode *child;
1753         XMLPropertyList plist;
1754         const XMLProperty *prop;
1755
1756         if (node.name() != "Route"){
1757                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1758                 return -1;
1759         }
1760
1761         if ((prop = node.property (X_("name"))) != 0) {
1762                 Route::set_name (prop->value());
1763         }
1764
1765         if ((prop = node.property ("id")) != 0) {
1766                 _id = prop->value ();
1767         }
1768
1769         if ((prop = node.property (X_("flags"))) != 0) {
1770                 _flags = Flag (string_2_enum (prop->value(), _flags));
1771         } else {
1772                 _flags = Flag (0);
1773         }
1774
1775         /* add all processors (except amp, which is always present) */
1776
1777         nlist = node.children();
1778         XMLNode processor_state (X_("processor_state"));
1779
1780         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1781
1782                 child = *niter;
1783
1784                 if (child->name() == IO::state_node_name) {
1785                         if ((prop = child->property (X_("direction"))) == 0) {
1786                                 continue;
1787                         }
1788
1789                         if (prop->value() == "Input") {
1790                                 _input->set_state (*child, version);
1791                         } else if (prop->value() == "Output") {
1792                                 _output->set_state (*child, version);
1793                         }
1794                 }
1795
1796                 if (child->name() == X_("Processor")) {
1797                         processor_state.add_child_copy (*child);
1798                 }
1799         }
1800
1801         set_processor_state (processor_state);
1802
1803         if ((prop = node.property ("self-solo")) != 0) {
1804                 set_self_solo (string_is_affirmative (prop->value()));
1805         }
1806
1807         if ((prop = node.property ("soloed-by-others")) != 0) {
1808                 _soloed_by_others = 0; // needed for mod_solo_by_others () to work
1809                 mod_solo_by_others (atoi (prop->value()));
1810         }
1811
1812         if ((prop = node.property ("solo-isolated")) != 0) {
1813                 set_solo_isolated (string_is_affirmative (prop->value()), this);
1814         }
1815
1816         if ((prop = node.property (X_("phase-invert"))) != 0) {
1817                 set_phase_invert (string_is_affirmative (prop->value()));
1818         }
1819
1820         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1821                 set_denormal_protection (string_is_affirmative (prop->value()));
1822         }
1823
1824         if ((prop = node.property (X_("active"))) != 0) {
1825                 bool yn = string_is_affirmative (prop->value());
1826                 _active = !yn; // force switch
1827                 set_active (yn);
1828         }
1829
1830         if ((prop = node.property (X_("meter-point"))) != 0) {
1831                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1832                 if (_meter) {
1833                         _meter->set_display_to_user (_meter_point == MeterCustom);
1834                 }
1835         }
1836
1837         if ((prop = node.property (X_("order-keys"))) != 0) {
1838
1839                 long n;
1840
1841                 string::size_type colon, equal;
1842                 string remaining = prop->value();
1843
1844                 while (remaining.length()) {
1845
1846                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1847                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1848                                       << endmsg;
1849                         } else {
1850                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1851                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1852                                               << endmsg;
1853                                 } else {
1854                                         set_order_key (remaining.substr (0, equal), n);
1855                                 }
1856                         }
1857
1858                         colon = remaining.find_first_of (':');
1859
1860                         if (colon != string::npos) {
1861                                 remaining = remaining.substr (colon+1);
1862                         } else {
1863                                 break;
1864                         }
1865                 }
1866         }
1867
1868         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1869                 child = *niter;
1870
1871                 if (child->name() == X_("Comment")) {
1872
1873                         /* XXX this is a terrible API design in libxml++ */
1874
1875                         XMLNode *cmt = *(child->children().begin());
1876                         _comment = cmt->content();
1877
1878                 } else if (child->name() == X_("Extra")) {
1879
1880                         _extra_xml = new XMLNode (*child);
1881
1882                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1883
1884                         if (prop->value() == "solo") {
1885                                 _solo_control->set_state (*child, version);
1886                                 _session.add_controllable (_solo_control);
1887                         }
1888
1889                 } else if (child->name() == X_("RemoteControl")) {
1890                         if ((prop = child->property (X_("id"))) != 0) {
1891                                 int32_t x;
1892                                 sscanf (prop->value().c_str(), "%d", &x);
1893                                 set_remote_control_id (x);
1894                         }
1895
1896                 } else if (child->name() == X_("MuteMaster")) {
1897                         _mute_master->set_state (*child, version);
1898                 }
1899         }
1900
1901         return 0;
1902 }
1903
1904 int
1905 Route::_set_state_2X (const XMLNode& node, int version)
1906 {
1907         XMLNodeList nlist;
1908         XMLNodeConstIterator niter;
1909         XMLNode *child;
1910         XMLPropertyList plist;
1911         const XMLProperty *prop;
1912
1913         /* 2X things which still remain to be handled:
1914          * default-type
1915          * muted
1916          * mute-affects-pre-fader
1917          * mute-affects-post-fader
1918          * mute-affects-control-outs
1919          * mute-affects-main-outs
1920          * automation
1921          * controlouts
1922          */
1923
1924         if (node.name() != "Route") {
1925                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1926                 return -1;
1927         }
1928
1929         if ((prop = node.property (X_("flags"))) != 0) {
1930                 _flags = Flag (string_2_enum (prop->value(), _flags));
1931         } else {
1932                 _flags = Flag (0);
1933         }
1934
1935         /* add standard processors */
1936
1937         _meter.reset (new PeakMeter (_session));
1938         add_processor (_meter, PreFader);
1939
1940         if (_flags & ControlOut) {
1941                 /* where we listen to tracks */
1942                 _intreturn.reset (new InternalReturn (_session));
1943                 add_processor (_intreturn, PreFader);
1944         }
1945
1946         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
1947         add_processor (_main_outs, PostFader);
1948
1949         /* IOs */
1950
1951         nlist = node.children ();
1952         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1953
1954                 child = *niter;
1955
1956                 if (child->name() == IO::state_node_name) {
1957
1958                         /* there is a note in IO::set_state_2X() about why we have to call
1959                            this directly.
1960                            */
1961
1962                         _input->set_state_2X (*child, version, true);
1963                         _output->set_state_2X (*child, version, false);
1964
1965                         if ((prop = child->property (X_("name"))) != 0) {
1966                                 set_name (prop->value ());
1967                         }
1968
1969                         if ((prop = child->property (X_("id"))) != 0) {
1970                                 _id = prop->value ();
1971                         }
1972
1973                         if ((prop = child->property (X_("active"))) != 0) {
1974                                 bool yn = string_is_affirmative (prop->value());
1975                                 _active = !yn; // force switch
1976                                 set_active (yn);
1977                         }
1978                 }
1979
1980                 /* XXX: panners? */
1981         }
1982
1983         if ((prop = node.property (X_("phase-invert"))) != 0) {
1984                 set_phase_invert (string_is_affirmative (prop->value()));
1985         }
1986
1987         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1988                 set_denormal_protection (string_is_affirmative (prop->value()));
1989         }
1990
1991         if ((prop = node.property (X_("soloed"))) != 0) {
1992                 bool yn = string_is_affirmative (prop->value());
1993
1994                 /* XXX force reset of solo status */
1995
1996                 set_solo (yn, this);
1997         }
1998
1999         if ((prop = node.property (X_("meter-point"))) != 0) {
2000                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2001         }
2002
2003         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2004            don't mean the same thing.
2005         */
2006
2007         if ((prop = node.property (X_("order-keys"))) != 0) {
2008
2009                 long n;
2010
2011                 string::size_type colon, equal;
2012                 string remaining = prop->value();
2013
2014                 while (remaining.length()) {
2015
2016                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2017                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2018                                         << endmsg;
2019                         } else {
2020                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
2021                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2022                                                 << endmsg;
2023                                 } else {
2024                                         set_order_key (remaining.substr (0, equal), n);
2025                                 }
2026                         }
2027
2028                         colon = remaining.find_first_of (':');
2029
2030                         if (colon != string::npos) {
2031                                 remaining = remaining.substr (colon+1);
2032                         } else {
2033                                 break;
2034                         }
2035                 }
2036         }
2037
2038         XMLNodeList redirect_nodes;
2039
2040         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2041
2042                 child = *niter;
2043
2044                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2045                         redirect_nodes.push_back(child);
2046                 }
2047
2048         }
2049
2050         set_processor_state_2X (redirect_nodes, version);
2051
2052         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2053                 child = *niter;
2054
2055                 if (child->name() == X_("Comment")) {
2056
2057                         /* XXX this is a terrible API design in libxml++ */
2058
2059                         XMLNode *cmt = *(child->children().begin());
2060                         _comment = cmt->content();
2061
2062                 } else if (child->name() == X_("Extra")) {
2063
2064                         _extra_xml = new XMLNode (*child);
2065
2066                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
2067
2068                         if (prop->value() == "solo") {
2069                                 _solo_control->set_state (*child, version);
2070                                 _session.add_controllable (_solo_control);
2071                         }
2072
2073                 } else if (child->name() == X_("RemoteControl")) {
2074                         if ((prop = child->property (X_("id"))) != 0) {
2075                                 int32_t x;
2076                                 sscanf (prop->value().c_str(), "%d", &x);
2077                                 set_remote_control_id (x);
2078                         }
2079
2080                 } 
2081         }
2082
2083         return 0;
2084 }
2085
2086 XMLNode&
2087 Route::get_processor_state ()
2088 {
2089         XMLNode* root = new XMLNode (X_("redirects"));
2090         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2091                 root->add_child_nocopy ((*i)->state (true));
2092         }
2093
2094         return *root;
2095 }
2096
2097 void
2098 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2099 {
2100         /* We don't bother removing existing processors not in nList, as this
2101            method will only be called when creating a Route from scratch, not
2102            for undo purposes.  Just put processors in at the appropriate place
2103            in the list.
2104         */
2105
2106         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2107                 add_processor_from_xml_2X (**i, version, _processors.begin ());
2108         }
2109 }
2110
2111 void
2112 Route::set_processor_state (const XMLNode& node)
2113 {
2114         const XMLNodeList &nlist = node.children();
2115         XMLNodeConstIterator niter;
2116         ProcessorList::iterator i, o;
2117
2118         // Iterate through existing processors, remove those which are not in the state list
2119
2120         for (i = _processors.begin(); i != _processors.end(); ) {
2121
2122                 /* leave amp alone, always */
2123
2124                 if ((*i) == _amp) {
2125                         ++i;
2126                         continue;
2127                 }
2128
2129                 ProcessorList::iterator tmp = i;
2130                 ++tmp;
2131
2132                 bool processorInStateList = false;
2133
2134                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2135
2136                         XMLProperty* id_prop = (*niter)->property(X_("id"));
2137
2138                         if (id_prop && (*i)->id() == id_prop->value()) {
2139                                 processorInStateList = true;
2140                                 break;
2141                         }
2142                 }
2143
2144                 if (!processorInStateList) {
2145                         remove_processor (*i);
2146                 }
2147
2148                 i = tmp;
2149         }
2150
2151         // Iterate through state list and make sure all processors are on the track and in the correct order,
2152         // set the state of existing processors according to the new state on the same go
2153
2154         i = _processors.begin();
2155
2156         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
2157
2158                 XMLProperty* prop = (*niter)->property ("type");
2159
2160                 o = i;
2161
2162                 // Check whether the next processor in the list is the right one,
2163                 // except for "amp" which is always there and may not have the
2164                 // old ID since it is always created anew in every Route
2165
2166                 if (prop->value() != "amp") {
2167                         while (o != _processors.end()) {
2168                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2169                                 if (id_prop && (*o)->id() == id_prop->value()) {
2170                                         break;
2171                                 }
2172
2173                                 ++o;
2174                         }
2175                 }
2176
2177                 // If the processor (*niter) is not on the route,
2178                 // create it and move it to the correct location
2179
2180                 if (o == _processors.end()) {
2181
2182                         if (add_processor_from_xml (**niter, i)) {
2183                                 --i; // move iterator to the newly inserted processor
2184                         } else {
2185                                 cerr << "Error restoring route: unable to restore processor" << endl;
2186                         }
2187
2188                 } else {
2189
2190                         // Otherwise, the processor already exists; just
2191                         // ensure it is at the location provided in the XML state
2192
2193                         if (i != o) {
2194                                 boost::shared_ptr<Processor> tmp = (*o);
2195                                 _processors.erase (o); // remove the old copy
2196                                 _processors.insert (i, tmp); // insert the processor at the correct location
2197                                 --i; // move iterator to the correct processor
2198                         }
2199
2200                         // and make it (just) so
2201
2202                         (*i)->set_state (**niter, Stateful::current_state_version);
2203                 }
2204         }
2205
2206         /* note: there is no configure_processors() call because we figure that
2207            the XML state represents a working signal route.
2208         */
2209
2210         processors_changed (RouteProcessorChange ());
2211 }
2212
2213 void
2214 Route::curve_reallocate ()
2215 {
2216 //      _gain_automation_curve.finish_resize ();
2217 //      _pan_automation_curve.finish_resize ();
2218 }
2219
2220 void
2221 Route::silence (nframes_t nframes)
2222 {
2223         if (!_silent) {
2224
2225                 _output->silence (nframes);
2226
2227                 {
2228                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2229
2230                         if (lm.locked()) {
2231                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2232                                         boost::shared_ptr<PluginInsert> pi;
2233
2234                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2235                                                 // skip plugins, they don't need anything when we're not active
2236                                                 continue;
2237                                         }
2238
2239                                         (*i)->silence (nframes);
2240                                 }
2241
2242                                 if (nframes == _session.get_block_size()) {
2243                                         // _silent = true;
2244                                 }
2245                         }
2246                 }
2247
2248         }
2249 }
2250
2251 void
2252 Route::add_internal_return ()
2253 {
2254         if (!_intreturn) {
2255                 _intreturn.reset (new InternalReturn (_session));
2256                 add_processor (_intreturn, PreFader);
2257         }
2258 }
2259
2260 BufferSet*
2261 Route::get_return_buffer () const
2262 {
2263         Glib::RWLock::ReaderLock rm (_processor_lock);
2264
2265         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2266                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2267
2268                 if (d) {
2269                         BufferSet* bs = d->get_buffers ();
2270                         return bs;
2271                 }
2272         }
2273
2274         return 0;
2275 }
2276
2277 void
2278 Route::release_return_buffer () const
2279 {
2280         Glib::RWLock::ReaderLock rm (_processor_lock);
2281
2282         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2283                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2284
2285                 if (d) {
2286                         return d->release_buffers ();
2287                 }
2288         }
2289 }
2290
2291 int
2292 Route::listen_via (boost::shared_ptr<Route> route, Placement placement, bool /*active*/, bool aux)
2293 {
2294         vector<string> ports;
2295         vector<string>::const_iterator i;
2296
2297         {
2298                 Glib::RWLock::ReaderLock rm (_processor_lock);
2299
2300                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2301
2302                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2303
2304                         if (d && d->target_route() == route) {
2305
2306                                 /* if the target is the control outs, then make sure
2307                                    we take note of which i-send is doing that.
2308                                 */
2309
2310                                 if (route == _session.control_out()) {
2311                                         _control_outs = boost::dynamic_pointer_cast<Delivery>(d);
2312                                 }
2313
2314                                 /* already listening via the specified IO: do nothing */
2315
2316                                 return 0;
2317                         }
2318                 }
2319         }
2320
2321         boost::shared_ptr<InternalSend> listener;
2322
2323         try {
2324                 listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2325
2326         } catch (failed_constructor& err) {
2327                 return -1;
2328         }
2329
2330         if (route == _session.control_out()) {
2331                 _control_outs = listener;
2332         }
2333
2334         add_processor (listener, placement);
2335
2336         return 0;
2337 }
2338
2339 void
2340 Route::drop_listen (boost::shared_ptr<Route> route)
2341 {
2342         ProcessorStreams err;
2343         ProcessorList::iterator tmp;
2344
2345         Glib::RWLock::ReaderLock rl(_processor_lock);
2346         rl.acquire ();
2347
2348   again:
2349         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2350
2351                 boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2352
2353                 if (d && d->target_route() == route) {
2354                         rl.release ();
2355                         remove_processor (*x, &err);
2356                         rl.acquire ();
2357
2358                         /* list could have been demolished while we dropped the lock
2359                            so start over.
2360                         */
2361
2362                         goto again;
2363                 }
2364         }
2365
2366         rl.release ();
2367
2368         if (route == _session.control_out()) {
2369                 _control_outs.reset ();
2370         }
2371 }
2372
2373 void
2374 Route::set_comment (string cmt, void *src)
2375 {
2376         _comment = cmt;
2377         comment_changed (src);
2378         _session.set_dirty ();
2379 }
2380
2381 bool
2382 Route::feeds (boost::shared_ptr<Route> other, bool* only_send)
2383 {
2384         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2385
2386         if (_output->connected_to (other->input())) {
2387                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2388                 if (only_send) {
2389                         *only_send = false;
2390                 }
2391
2392                 return true;
2393         }
2394
2395         
2396         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2397
2398                 boost::shared_ptr<IOProcessor> iop;
2399
2400                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2401                         if (iop->feeds (other)) {
2402                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2403                                 if (only_send) {
2404                                         *only_send = true;
2405                                 }
2406                                 return true;
2407                         } else {
2408                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2409                         }
2410                 } else {
2411                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2412                 }
2413                         
2414         }
2415
2416         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2417         return false;
2418 }
2419
2420 void
2421 Route::handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2422 {
2423         nframes_t now = _session.transport_frame();
2424
2425         {
2426                 Glib::RWLock::ReaderLock lm (_processor_lock);
2427
2428                 if (!did_locate) {
2429                         automation_snapshot (now, true);
2430                 }
2431
2432                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2433
2434                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2435                                 (*i)->deactivate ();
2436                                 (*i)->activate ();
2437                         }
2438
2439                         (*i)->transport_stopped (now);
2440                 }
2441         }
2442
2443         _roll_delay = _initial_delay;
2444 }
2445
2446 void
2447 Route::input_change_handler (IOChange change, void * /*src*/)
2448 {
2449         if ((change & ConfigurationChanged)) {
2450                 configure_processors (0);
2451         }
2452 }
2453
2454 void
2455 Route::output_change_handler (IOChange change, void * /*src*/)
2456 {
2457         if ((change & ConfigurationChanged)) {
2458
2459                 /* XXX resize all listeners to match _main_outs? */
2460
2461                 // configure_processors (0);
2462         }
2463 }
2464
2465 uint32_t
2466 Route::pans_required () const
2467 {
2468         if (n_outputs().n_audio() < 2) {
2469                 return 0;
2470         }
2471
2472         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2473 }
2474
2475 int
2476 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
2477                 bool session_state_changing, bool /*can_record*/, bool /*rec_monitors_input*/)
2478 {
2479         if (n_outputs().n_total() == 0) {
2480                 return 0;
2481         }
2482
2483         if (session_state_changing || !_active || n_inputs() == ChanCount::ZERO)  {
2484                 silence (nframes);
2485                 return 0;
2486         }
2487
2488         _amp->apply_gain_automation (false);
2489         passthru (start_frame, end_frame, nframes, 0);
2490
2491         return 0;
2492 }
2493
2494 nframes_t
2495 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2496 {
2497         if (_roll_delay > nframes) {
2498
2499                 _roll_delay -= nframes;
2500                 silence (nframes);
2501                 /* transport frame is not legal for caller to use */
2502                 return 0;
2503
2504         } else if (_roll_delay > 0) {
2505
2506                 nframes -= _roll_delay;
2507                 silence (_roll_delay);
2508                 /* we've written _roll_delay of samples into the
2509                    output ports, so make a note of that for
2510                    future reference.
2511                 */
2512                 _main_outs->increment_output_offset (_roll_delay);
2513                 transport_frame += _roll_delay;
2514
2515                 _roll_delay = 0;
2516         }
2517
2518         return nframes;
2519 }
2520
2521 int
2522 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2523              bool /*can_record*/, bool /*rec_monitors_input*/)
2524 {
2525         {
2526                 // automation snapshot can also be called from the non-rt context
2527                 // and it uses the processor list, so we try to acquire the lock here
2528                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2529
2530                 if (lm.locked()) {
2531                         automation_snapshot (_session.transport_frame(), false);
2532                 }
2533         }
2534
2535         if (n_outputs().n_total() == 0) {
2536                 return 0;
2537         }
2538
2539         if (!_active || n_inputs().n_total() == 0) {
2540                 silence (nframes);
2541                 return 0;
2542         }
2543
2544         nframes_t unused = 0;
2545
2546         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2547                 return 0;
2548         }
2549
2550         _silent = false;
2551
2552         passthru (start_frame, end_frame, nframes, declick);
2553
2554         return 0;
2555 }
2556
2557 int
2558 Route::silent_roll (nframes_t nframes, sframes_t /*start_frame*/, sframes_t /*end_frame*/,
2559                     bool /*can_record*/, bool /*rec_monitors_input*/)
2560 {
2561         silence (nframes);
2562         return 0;
2563 }
2564
2565 void
2566 Route::toggle_monitor_input ()
2567 {
2568         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2569                 i->ensure_monitor_input( ! i->monitoring_input());
2570         }
2571 }
2572
2573 bool
2574 Route::has_external_redirects () const
2575 {
2576         // FIXME: what about sends? - they don't return a signal back to ardour?
2577
2578         boost::shared_ptr<const PortInsert> pi;
2579
2580         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2581
2582                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2583
2584                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2585
2586                                 string port_name = port->name();
2587                                 string client_name = port_name.substr (0, port_name.find(':'));
2588
2589                                 /* only say "yes" if the redirect is actually in use */
2590
2591                                 if (client_name != "ardour" && pi->active()) {
2592                                         return true;
2593                                 }
2594                         }
2595                 }
2596         }
2597
2598         return false;
2599 }
2600
2601 void
2602 Route::flush_processors ()
2603 {
2604         /* XXX shouldn't really try to take this lock, since
2605            this is called from the RT audio thread.
2606         */
2607
2608         Glib::RWLock::ReaderLock lm (_processor_lock);
2609
2610         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2611                 (*i)->deactivate ();
2612                 (*i)->activate ();
2613         }
2614 }
2615
2616 void
2617 Route::set_meter_point (MeterPoint p, void *src)
2618 {
2619         /* CAN BE CALLED FROM PROCESS CONTEXT */
2620
2621         if (_meter_point == p) {
2622                 return;
2623         }
2624
2625         bool meter_was_visible_to_user = _meter->display_to_user ();
2626
2627         {
2628                 Glib::RWLock::WriterLock lm (_processor_lock);
2629         
2630                 if (p != MeterCustom) {
2631                         // Move meter in the processors list to reflect the new position
2632                         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2633                         _processors.erase(loc);
2634                         switch (p) {
2635                         case MeterInput:
2636                                 loc = _processors.begin();
2637                                 break;
2638                         case MeterPreFader:
2639                                 loc = find (_processors.begin(), _processors.end(), _amp);
2640                                 break;
2641                         case MeterPostFader:
2642                                 loc = _processors.end();
2643                                 break;
2644                         default:
2645                                 break;
2646                         }
2647                         
2648                         ChanCount m_in;
2649                         
2650                         if (loc == _processors.begin()) {
2651                                 m_in = _input->n_ports();
2652                         } else {
2653                                 ProcessorList::iterator before = loc;
2654                                 --before;
2655                                 m_in = (*before)->output_streams ();
2656                         }
2657                         
2658                         _meter->reflect_inputs (m_in);
2659                         
2660                         _processors.insert (loc, _meter);
2661                         
2662                         /* we do not need to reconfigure the processors, because the meter
2663                            (a) is always ready to handle processor_max_streams
2664                            (b) is always an N-in/N-out processor, and thus moving
2665                            it doesn't require any changes to the other processors.
2666                         */
2667                         
2668                         _meter->set_display_to_user (false);
2669                         
2670                 } else {
2671                         
2672                         // just make it visible and let the user move it
2673                         
2674                         _meter->set_display_to_user (true);
2675                 }
2676         }
2677
2678         _meter_point = p;
2679         meter_change (src); /* EMIT SIGNAL */
2680
2681         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
2682         
2683         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
2684 }
2685
2686 void
2687 Route::put_control_outs_at (Placement p)
2688 {
2689         if (!_control_outs) {
2690                 return;
2691         }
2692
2693         {
2694                 Glib::RWLock::WriterLock lm (_processor_lock);
2695                 ProcessorList as_it_was (_processors);
2696                 // Move meter in the processors list
2697                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _control_outs);
2698                 _processors.erase(loc);
2699                 
2700                 switch (p) {
2701                 case PreFader:
2702                         loc = find(_processors.begin(), _processors.end(), _amp);
2703                         if (loc != _processors.begin()) {
2704                                 --loc;
2705                         }
2706                         break;
2707                 case PostFader:
2708                         loc = find(_processors.begin(), _processors.end(), _amp);
2709                         assert (loc != _processors.end());
2710                         loc++;
2711                         break;
2712                 }
2713                 
2714                 _processors.insert(loc, _control_outs);
2715
2716                 if (configure_processors_unlocked (0)) {
2717                         _processors = as_it_was;
2718                         configure_processors_unlocked (0); // it worked before we tried to add it ...
2719                         return;
2720                 }
2721         }
2722
2723         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2724         _session.set_dirty ();
2725 }
2726
2727 nframes_t
2728 Route::update_total_latency ()
2729 {
2730         nframes_t old = _output->effective_latency();
2731         nframes_t own_latency = _output->user_latency();
2732
2733         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2734                 if ((*i)->active ()) {
2735                         own_latency += (*i)->signal_latency ();
2736                 }
2737         }
2738
2739         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal redirect latency = %2\n", _name, own_latency));
2740
2741         _output->set_port_latency (own_latency);
2742
2743         if (_output->user_latency() == 0) {
2744
2745                 /* this (virtual) function is used for pure Routes,
2746                    not derived classes like AudioTrack.  this means
2747                    that the data processed here comes from an input
2748                    port, not prerecorded material, and therefore we
2749                    have to take into account any input latency.
2750                 */
2751
2752                 own_latency += _input->signal_latency ();
2753         }
2754
2755         if (old != own_latency) {
2756                 _output->set_latency_delay (own_latency);
2757                 signal_latency_changed (); /* EMIT SIGNAL */
2758         }
2759
2760         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: input latency = %2 total = %3\n", _name, _input->signal_latency(), own_latency));
2761
2762         return _output->effective_latency ();
2763 }
2764
2765 void
2766 Route::set_user_latency (nframes_t nframes)
2767 {
2768         _output->set_user_latency (nframes);
2769         _session.update_latency_compensation (false, false);
2770 }
2771
2772 void
2773 Route::set_latency_delay (nframes_t longest_session_latency)
2774 {
2775         nframes_t old = _initial_delay;
2776
2777         if (_output->effective_latency() < longest_session_latency) {
2778                 _initial_delay = longest_session_latency - _output->effective_latency();
2779         } else {
2780                 _initial_delay = 0;
2781         }
2782
2783         if (_initial_delay != old) {
2784                 initial_delay_changed (); /* EMIT SIGNAL */
2785         }
2786
2787         if (_session.transport_stopped()) {
2788                 _roll_delay = _initial_delay;
2789         }
2790 }
2791
2792 void
2793 Route::automation_snapshot (nframes_t now, bool force)
2794 {
2795         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2796                 (*i)->automation_snapshot (now, force);
2797         }
2798 }
2799
2800 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2801         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation),
2802                              boost::shared_ptr<AutomationList>(), name)
2803         , route (r)
2804 {
2805         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2806         set_list (gl);
2807 }
2808
2809 void
2810 Route::SoloControllable::set_value (float val)
2811 {
2812         bool bval = ((val >= 0.5f) ? true: false);
2813
2814         route.set_solo (bval, this);
2815 }
2816
2817 float
2818 Route::SoloControllable::get_value (void) const
2819 {
2820         return route.self_soloed() ? 1.0f : 0.0f;
2821 }
2822
2823 void
2824 Route::set_block_size (nframes_t nframes)
2825 {
2826         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2827                 (*i)->set_block_size (nframes);
2828         }
2829         
2830         _session.ensure_buffers (n_process_buffers ());
2831 }
2832
2833 void
2834 Route::protect_automation ()
2835 {
2836         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2837                 (*i)->protect_automation();
2838 }
2839
2840 void
2841 Route::set_pending_declick (int declick)
2842 {
2843         if (_declickable) {
2844                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2845                 if (declick) {
2846                         _pending_declick = declick;
2847                 }
2848                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2849         } else {
2850                 _pending_declick = 0;
2851         }
2852
2853 }
2854
2855 /** Shift automation forwards from a particular place, thereby inserting time.
2856  *  Adds undo commands for any shifts that are performed.
2857  *
2858  * @param pos Position to start shifting from.
2859  * @param frames Amount to shift forwards by.
2860  */
2861
2862 void
2863 Route::shift (nframes64_t /*pos*/, nframes64_t /*frames*/)
2864 {
2865 #ifdef THIS_NEEDS_FIXING_FOR_V3
2866
2867         /* gain automation */
2868         XMLNode &before = _gain_control->get_state ();
2869         _gain_control->shift (pos, frames);
2870         XMLNode &after = _gain_control->get_state ();
2871         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2872
2873         /* pan automation */
2874         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2875                 Curve & c = (*i)->automation ();
2876                 XMLNode &before = c.get_state ();
2877                 c.shift (pos, frames);
2878                 XMLNode &after = c.get_state ();
2879                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2880         }
2881
2882         /* redirect automation */
2883         {
2884                 Glib::RWLock::ReaderLock lm (redirect_lock);
2885                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2886
2887                         set<uint32_t> a;
2888                         (*i)->what_has_automation (a);
2889
2890                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2891                                 AutomationList & al = (*i)->automation_list (*j);
2892                                 XMLNode &before = al.get_state ();
2893                                 al.shift (pos, frames);
2894                                 XMLNode &after = al.get_state ();
2895                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2896                         }
2897                 }
2898         }
2899 #endif
2900
2901 }
2902
2903
2904 int
2905 Route::save_as_template (const string& path, const string& name)
2906 {
2907         XMLNode& node (state (false));
2908         XMLTree tree;
2909
2910         IO::set_name_in_state (*node.children().front(), name);
2911
2912         tree.set_root (&node);
2913         return tree.write (path.c_str());
2914 }
2915
2916
2917 bool
2918 Route::set_name (const string& str)
2919 {
2920         bool ret;
2921         string ioproc_name;
2922         string name;
2923
2924         name = Route::ensure_track_or_route_name (str, _session);
2925         SessionObject::set_name (name);
2926
2927         ret = (_input->set_name(name) && _output->set_name(name));
2928
2929         if (ret) {
2930
2931                 Glib::RWLock::ReaderLock lm (_processor_lock);
2932
2933                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2934
2935                         /* rename all I/O processors that have inputs or outputs */
2936
2937                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
2938
2939                         if (iop && (iop->output() || iop->input())) {
2940                                 if (!iop->set_name (name)) {
2941                                         ret = false;
2942                                 }
2943                         }
2944                 }
2945
2946         }
2947
2948         return ret;
2949 }
2950
2951 boost::shared_ptr<Send>
2952 Route::internal_send_for (boost::shared_ptr<const Route> target) const
2953 {
2954         Glib::RWLock::ReaderLock lm (_processor_lock);
2955
2956         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2957                 boost::shared_ptr<InternalSend> send;
2958
2959                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
2960                         if (send->target_route() == target) {
2961                                 return send;
2962                         }
2963                 }
2964         }
2965
2966         return boost::shared_ptr<Send>();
2967 }
2968
2969 void
2970 Route::set_phase_invert (bool yn)
2971 {
2972         if (_phase_invert != yn) {
2973                 _phase_invert = 0xffff; // XXX all channels
2974                 phase_invert_changed (); /* EMIT SIGNAL */
2975         }
2976 }
2977
2978 bool
2979 Route::phase_invert () const
2980 {
2981         return _phase_invert != 0;
2982 }
2983
2984 void
2985 Route::set_denormal_protection (bool yn)
2986 {
2987         if (_denormal_protection != yn) {
2988                 _denormal_protection = yn;
2989                 denormal_protection_changed (); /* EMIT SIGNAL */
2990         }
2991 }
2992
2993 bool
2994 Route::denormal_protection () const
2995 {
2996         return _denormal_protection;
2997 }
2998
2999 void
3000 Route::set_active (bool yn)
3001 {
3002         if (_active != yn) {
3003                 _active = yn;
3004                 _input->set_active (yn);
3005                 _output->set_active (yn);
3006                 active_changed (); // EMIT SIGNAL
3007         }
3008 }
3009
3010 void
3011 Route::meter ()
3012 {
3013         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3014
3015         assert (_meter);
3016
3017         _meter->meter ();
3018
3019         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3020
3021                 boost::shared_ptr<Send> s;
3022                 boost::shared_ptr<Return> r;
3023
3024                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3025                         s->meter()->meter();
3026                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3027                         r->meter()->meter ();
3028                 }
3029         }
3030 }
3031
3032 boost::shared_ptr<Panner>
3033 Route::panner() const
3034 {
3035
3036         return _main_outs->panner();
3037 }
3038
3039 boost::shared_ptr<AutomationControl>
3040 Route::gain_control() const
3041 {
3042
3043         return _amp->gain_control();
3044 }
3045
3046 boost::shared_ptr<AutomationControl>
3047 Route::get_control (const Evoral::Parameter& param)
3048 {
3049         /* either we own the control or .... */
3050
3051         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(data().control (param));
3052
3053         if (!c) {
3054
3055                 /* maybe one of our processors does or ... */
3056
3057                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3058                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3059                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->data().control (param))) != 0) {
3060                                 break;
3061                         }
3062                 }
3063         }
3064
3065         if (!c) {
3066
3067                 /* nobody does so we'll make a new one */
3068
3069                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3070                 add_control(c);
3071         }
3072
3073         return c;
3074 }