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