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