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