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