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