Factor source copying into a method and use it in a couple of places where it is...
[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/stacktrace.h"
29 #include "pbd/memento_command.h"
30
31 #include "evoral/Curve.hpp"
32
33 #include "ardour/amp.h"
34 #include "ardour/audio_port.h"
35 #include "ardour/audioengine.h"
36 #include "ardour/buffer.h"
37 #include "ardour/buffer_set.h"
38 #include "ardour/configuration.h"
39 #include "ardour/cycle_timer.h"
40 #include "ardour/dB.h"
41 #include "ardour/ladspa_plugin.h"
42 #include "ardour/meter.h"
43 #include "ardour/mix.h"
44 #include "ardour/panner.h"
45 #include "ardour/plugin_insert.h"
46 #include "ardour/port.h"
47 #include "ardour/port_insert.h"
48 #include "ardour/processor.h"
49 #include "ardour/profile.h"
50 #include "ardour/route.h"
51 #include "ardour/route_group.h"
52 #include "ardour/send.h"
53 #include "ardour/session.h"
54 #include "ardour/timestamps.h"
55 #include "ardour/utils.h"
56
57 #include "i18n.h"
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 uint32_t Route::order_key_cnt = 0;
64 sigc::signal<void,const char*> Route::SyncOrderKeys;
65
66 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
67         : SessionObject (sess, name)
68         , AutomatableControls (sess)
69         , _flags (flg)
70         , _solo_control (new SoloControllable (X_("solo"), *this))
71         , _mute_master (new MuteMaster (sess, name))
72         , _default_type (default_type)
73           
74 {
75         init ();
76 }
77
78 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
79         : SessionObject (sess, "toBeReset")
80         , AutomatableControls (sess)
81         , _solo_control (new SoloControllable (X_("solo"), *this))
82         , _mute_master (new MuteMaster (sess, "toBeReset"))
83         , _default_type (default_type)
84 {
85         init ();
86         _set_state (node, false);
87 }
88
89 void
90 Route::init ()
91 {
92         _active = true;
93         processor_max_streams.reset();
94         _solo_safe = false;
95         _recordable = true;
96         order_keys[strdup (N_("signal"))] = order_key_cnt++;
97         _silent = false;
98         _meter_point = MeterPostFader;
99         _initial_delay = 0;
100         _roll_delay = 0;
101         _have_internal_generator = false;
102         _declickable = false;
103         _pending_declick = true;
104         _remote_control_id = 0;
105         _in_configure_processors = false;
106         
107         _edit_group = 0;
108         _mix_group = 0;
109
110         _phase_invert = 0;
111         _denormal_protection = false;
112
113         /* add standard controls */
114
115         add_control (_solo_control);
116         add_control (_mute_master);
117         
118         /* input and output objects */
119
120         _input.reset (new IO (_session, _name, IO::Input, _default_type));
121         _output.reset (new IO (_session, _name, IO::Output, _default_type));
122
123         _input->changed.connect (mem_fun (this, &Route::input_change_handler));
124         _output->changed.connect (mem_fun (this, &Route::output_change_handler));
125
126         /* add standard processors */
127
128         _amp.reset (new Amp (_session, _mute_master));
129         add_processor (_amp, PostFader);
130
131         _meter.reset (new PeakMeter (_session));
132         add_processor (_meter, PreFader);
133         
134         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
135         add_processor (_main_outs, PostFader);
136
137         /* now we can meter */
138         
139         _meter_connection = Metering::connect (mem_fun (*this, &Route::meter));
140 }
141
142 Route::~Route ()
143 {
144         Metering::disconnect (_meter_connection);
145
146         clear_processors (PreFader);
147         clear_processors (PostFader);
148
149         for (OrderKeys::iterator i = order_keys.begin(); i != order_keys.end(); ++i) {
150                 free ((void*)(i->first));
151         }
152 }
153
154 void
155 Route::set_remote_control_id (uint32_t id)
156 {
157         if (id != _remote_control_id) {
158                 _remote_control_id = id;
159                 RemoteControlIDChanged ();
160         }
161 }
162
163 uint32_t
164 Route::remote_control_id() const
165 {
166         return _remote_control_id;
167 }
168
169 long
170 Route::order_key (const char* name) const
171 {
172         OrderKeys::const_iterator i;
173
174         for (i = order_keys.begin(); i != order_keys.end(); ++i) {
175                 if (!strcmp (name, i->first)) {
176                         return i->second;
177                 }
178         }
179
180         return -1;
181 }
182
183 void
184 Route::set_order_key (const char* name, long n)
185 {
186         order_keys[strdup(name)] = n;
187
188         if (Config->get_sync_all_route_ordering()) {
189                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
190                         x->second = n;
191                 }
192         } 
193
194         _session.set_dirty ();
195 }
196
197 void
198 Route::sync_order_keys (const char* base)
199 {
200         if (order_keys.empty()) {
201                 return;
202         }
203
204         OrderKeys::iterator i;
205         uint32_t key;
206
207         if ((i = order_keys.find (base)) == order_keys.end()) {
208                 /* key doesn't exist, use the first existing key (during session initialization) */
209                 i = order_keys.begin();
210                 key = i->second;
211                 ++i;
212         } else {
213                 /* key exists - use it and reset all others (actually, itself included) */
214                 key = i->second;
215                 i = order_keys.begin();
216         }
217
218         for (; i != order_keys.end(); ++i) {
219                 i->second = key;
220         }
221 }
222
223 string
224 Route::ensure_track_or_route_name(string name, Session &session)
225 {
226         string newname = name;
227
228         while (session.route_by_name (newname) != NULL) {
229                 newname = bump_name_once (newname);
230         }
231
232         return newname;
233 }
234
235
236 void
237 Route::inc_gain (gain_t fraction, void *src)
238 {
239         _amp->inc_gain (fraction, src);
240 }
241
242 void
243 Route::set_gain (gain_t val, void *src)
244 {
245         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
246                 
247                 if (_mix_group->is_relative()) {
248                         
249                         gain_t usable_gain = _amp->gain();
250                         if (usable_gain < 0.000001f) {
251                                 usable_gain = 0.000001f;
252                         }
253                                                 
254                         gain_t delta = val;
255                         if (delta < 0.000001f) {
256                                 delta = 0.000001f;
257                         }
258
259                         delta -= usable_gain;
260
261                         if (delta == 0.0f)
262                                 return;
263
264                         gain_t factor = delta / usable_gain;
265
266                         if (factor > 0.0f) {
267                                 factor = _mix_group->get_max_factor(factor);
268                                 if (factor == 0.0f) {
269                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
270                                         return;
271                                 }
272                         } else {
273                                 factor = _mix_group->get_min_factor(factor);
274                                 if (factor == 0.0f) {
275                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
276                                         return;
277                                 }
278                         }
279                                         
280                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
281
282                 } else {
283                         
284                         _mix_group->apply (&Route::set_gain, val, _mix_group);
285                 }
286
287                 return;
288         } 
289
290         if (val == _amp->gain()) {
291                 return;
292         }
293
294         _amp->set_gain (val, src);
295 }
296
297 /** Process this route for one (sub) cycle (process thread)
298  *
299  * @param bufs Scratch buffers to use for the signal path
300  * @param start_frame Initial transport frame 
301  * @param end_frame Final transport frame
302  * @param nframes Number of frames to output (to ports)
303  *
304  * Note that (end_frame - start_frame) may not be equal to nframes when the
305  * transport speed isn't 1.0 (eg varispeed).
306  */
307 void
308 Route::process_output_buffers (BufferSet& bufs,
309                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
310                                bool with_processors, int declick)
311 {
312         bool monitor;
313
314         bufs.is_silent (false);
315
316         switch (Config->get_monitoring_model()) {
317         case HardwareMonitoring:
318         case ExternalMonitoring:
319                 monitor = record_enabled() && (_session.config.get_auto_input() || _session.actively_recording());
320                 break;
321         default:
322                 monitor = true;
323         }
324
325         if (!declick) {
326                 declick = _pending_declick;
327         }
328
329         /* figure out if we're going to use gain automation */
330
331         _amp->setup_gain_automation (start_frame, end_frame, nframes);
332         
333         /* tell main outs what to do about monitoring */
334
335         _main_outs->no_outs_cuz_we_no_monitor (!monitor);
336
337         /* -------------------------------------------------------------------------------------------
338            GLOBAL DECLICK (for transport changes etc.)
339            ----------------------------------------------------------------------------------------- */
340
341         if (declick > 0) {
342                 Amp::apply_gain (bufs, nframes, 0.0, 1.0);
343         } else if (declick < 0) {
344                 Amp::apply_gain (bufs, nframes, 1.0, 0.0);
345         } 
346
347         _pending_declick = 0;
348                 
349         /* -------------------------------------------------------------------------------------------
350            DENORMAL CONTROL/PHASE INVERT
351            ----------------------------------------------------------------------------------------- */
352
353         if (_phase_invert) {
354                 
355                 int chn = 0;
356
357                 if (_denormal_protection || Config->get_denormal_protection()) {
358                         
359                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
360                                 Sample* const sp = i->data();
361
362                                 if (_phase_invert & chn) {
363                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
364                                                 sp[nx]  = -sp[nx];
365                                                 sp[nx] += 1.0e-27f;
366                                         }
367                                 } else {
368                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
369                                                 sp[nx] += 1.0e-27f;
370                                         }
371                                 }
372                         }
373
374                 } else {
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                                         }
383                                 } 
384                         }
385                 }
386         }
387
388         /* -------------------------------------------------------------------------------------------
389            and go ....
390            ----------------------------------------------------------------------------------------- */
391
392         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
393
394         if (rm.locked()) {
395                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
396                         bufs.set_count (ChanCount::max(bufs.count(), (*i)->input_streams()));
397                         (*i)->run_in_place (bufs, start_frame, end_frame, nframes);
398                         bufs.set_count (ChanCount::max(bufs.count(), (*i)->output_streams()));
399                 }
400
401                 if (!_processors.empty()) {
402                         bufs.set_count (ChanCount::max (bufs.count(), _processors.back()->output_streams()));
403                 }
404         }
405 }
406
407 ChanCount
408 Route::n_process_buffers ()
409 {
410         return max (_input->n_ports(), processor_max_streams);
411 }
412
413 void
414 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
415 {
416         BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
417
418         _silent = false;
419
420         assert (bufs.available() >= _input->n_ports());
421         
422         if (_input->n_ports() == ChanCount::ZERO) {
423                 silence (nframes);
424         }
425         
426         bufs.set_count (_input->n_ports());
427         
428         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
429                 
430                 BufferSet::iterator o = bufs.begin(*t);
431                 PortSet& ports (_input->ports());
432
433                 for (PortSet::iterator i = ports.begin(*t); i != ports.end(*t); ++i, ++o) {
434                         o->read_from (i->get_buffer(nframes), nframes);
435                 }
436         }
437
438         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
439 }
440
441 void
442 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
443 {
444         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, true, declick);
445 }
446
447 void
448 Route::set_solo (bool yn, void *src)
449 {
450         if (_solo_safe) {
451                 return;
452         }
453
454         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
455                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
456                 return;
457         }
458
459         if (_main_outs->soloed() != yn) {
460                 _main_outs->mod_solo_level (yn ? 1 : -1);
461                 solo_changed (src); /* EMIT SIGNAL */
462                 _solo_control->Changed (); /* EMIT SIGNAL */
463         }       
464 }
465
466 bool
467 Route::soloed() const
468 {
469         return _main_outs->soloed ();
470 }
471
472 void
473 Route::set_solo_isolated (bool yn, void *src)
474 {
475         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
476                 _mix_group->apply (&Route::set_solo_isolated, yn, _mix_group);
477                 return;
478         }
479
480         _main_outs->set_solo_isolated (yn);
481         solo_isolated_changed (src);
482 }
483
484 bool
485 Route::solo_isolated () const 
486 {
487         return _main_outs->solo_isolated();
488 }
489
490 void
491 Route::set_mute (bool yn, void *src)
492 {
493         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
494                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
495                 return;
496         }
497
498         if (muted() != yn) {
499                 _mute_master->mute (yn);
500                 mute_changed (src);
501         }
502 }       
503
504 bool
505 Route::muted() const 
506 {
507         return _mute_master->muted ();
508 }
509
510 #if DEFINE_IF_YOU_NEED_THIS
511 static void
512 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
513 {
514         cerr << name << " {" << endl;
515         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
516                         p != procs.end(); ++p) {
517                 cerr << "\t" << (*p)->name() << endl;
518         }
519         cerr << "}" << endl;
520 }
521 #endif
522
523 Route::ProcessorList::iterator
524 Route::prefader_iterator() 
525 {
526         Glib::RWLock::ReaderLock lm (_processor_lock);
527         return find (_processors.begin(), _processors.end(), _amp);
528 }
529
530 int
531 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err)
532 {
533         ProcessorList::iterator loc;
534
535         /* XXX this is not thread safe - we don't hold the lock across determining the iter
536            to add before and actually doing the insertion. dammit.
537         */
538
539         if (placement == PreFader) {
540                 /* generic pre-fader: insert immediately before the amp */
541                 loc = find(_processors.begin(), _processors.end(), _amp);
542         } else {
543                 /* generic post-fader: insert at end */
544                 loc = _processors.end();
545
546                 if (processor->visible() && !_processors.empty()) {
547                         /* check for invisible processors stacked at the end and leave them there */
548                         ProcessorList::iterator p;
549                         p = _processors.end();
550                         --p;
551                         cerr << "Let's check " << (*p)->name() << " vis ? " << (*p)->visible() << endl;
552                         while (!(*p)->visible() && p != _processors.begin()) {
553                                 --p;
554                         }
555                         ++p;
556                         loc = p;
557                 }
558         }
559
560         return add_processor (processor, loc, err);
561 }
562
563
564 /** Add a processor to the route.
565  * If @a iter is not NULL, it must point to an iterator in _processors and the new
566  * processor will be inserted immediately before this location.  Otherwise,
567  * @a position is used.
568  */
569 int
570 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorList::iterator iter, ProcessorStreams* err)
571 {
572         ChanCount old_pms = processor_max_streams;
573
574         if (!_session.engine().connected() || !processor) {
575                 return 1;
576         }
577
578         {
579                 Glib::RWLock::WriterLock lm (_processor_lock);
580
581                 boost::shared_ptr<PluginInsert> pi;
582                 boost::shared_ptr<PortInsert> porti;
583
584                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
585
586                 if (processor == _amp || processor == _meter || processor == _main_outs) {
587                         // Ensure only one of these are in the list at any time
588                         if (loc != _processors.end()) {
589                                 if (iter == loc) { // Already in place, do nothing
590                                         return 0;
591                                 } else { // New position given, relocate
592                                         _processors.erase (loc);
593                                 }
594                         }
595
596                 } else {
597                         if (loc != _processors.end()) {
598                                 cerr << "ERROR: Processor added to route twice!" << endl;
599                                 return 1;
600                         }
601
602                         loc = iter;
603                 }
604
605                 _processors.insert (loc, processor);
606
607                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
608                 // configure redirect ports properly, etc.
609                 
610
611                 if (configure_processors_unlocked (err)) {
612                         ProcessorList::iterator ploc = loc;
613                         --ploc;
614                         _processors.erase(ploc);
615                         configure_processors_unlocked (0); // it worked before we tried to add it ...
616                         return -1;
617                 }
618         
619                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
620                         
621                         if (pi->natural_input_streams() == ChanCount::ZERO) {
622                                 /* generator plugin */
623                                 _have_internal_generator = true;
624                         }
625                         
626                 }
627                 
628                 if (_meter) {
629                         // Ensure peak vector sizes before the plugin is activated
630                         ChanCount potential_max_streams = ChanCount::max (processor->input_streams(), processor->output_streams());
631                         _meter->configure_io (potential_max_streams, potential_max_streams);
632                 }
633
634                 // XXX: do we want to emit the signal here ? change call order.
635                 processor->activate ();
636                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
637
638                 _output->set_user_latency (0);
639         }
640         
641         processors_changed (); /* EMIT SIGNAL */
642         
643         return 0;
644 }
645
646 bool
647 Route::add_processor_from_xml (const XMLNode& node, Placement placement)
648 {
649         ProcessorList::iterator loc;
650         if (placement == PreFader) {
651                 /* generic pre-fader: insert immediately before the amp */
652                 loc = find(_processors.begin(), _processors.end(), _amp);
653         } else {
654                 /* generic post-fader: insert at end */
655                 loc = _processors.end();
656         }
657
658         return add_processor_from_xml (node, loc);
659 }
660
661 bool
662 Route::add_processor_from_xml (const XMLNode& node, ProcessorList::iterator iter)
663 {
664         const XMLProperty *prop;
665
666         // legacy sessions use a different node name for sends
667         if (node.name() == "Send") {
668         
669                 try {
670                         boost::shared_ptr<Send> send (new Send (_session, _mute_master, node));
671                         add_processor (send, iter); 
672                         return true;
673                 } 
674                 
675                 catch (failed_constructor &err) {
676                         error << _("Send construction failed") << endmsg;
677                         return false;
678                 }
679                 
680         } else if (node.name() == "Processor") {
681                 
682                 try {
683                         if ((prop = node.property ("type")) != 0) {
684
685
686                                 cerr << _name << " : got processor type " << prop->value() << endl;
687
688                                 boost::shared_ptr<Processor> processor;
689                                 bool have_insert = false;
690
691                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
692                                     prop->value() == "lv2" ||
693                                     prop->value() == "vst" ||
694                                     prop->value() == "audiounit") {
695                                         
696                                         processor.reset (new PluginInsert(_session, node));
697                                         have_insert = true;
698                                         
699                                 } else if (prop->value() == "port") {
700
701                                         processor.reset (new PortInsert (_session, _mute_master, node));
702                                 
703                                 } else if (prop->value() == "send") {
704
705                                         processor.reset (new Send (_session, _mute_master, node));
706                                         have_insert = true;
707                                 
708                                 } else if (prop->value() == "meter") {
709
710                                         processor = _meter;
711                                         processor->set_state (node);
712                                 
713                                 } else if (prop->value() == "amp") {
714                                         
715                                         processor = _amp;
716                                         processor->set_state (node);
717                                         
718                                 } else if (prop->value() == "listen" || prop->value() == "deliver") {
719
720                                         /* XXX need to generalize */
721
722                                         processor = _control_outs;
723                                         processor->set_state (node);
724                                         
725                                 } else if (prop->value() == "main-outs") {
726                                         
727                                         processor = _main_outs;
728                                         processor->set_state (node);
729
730                                 } else {
731
732                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
733                                 }
734                                 
735                                 if (iter == _processors.end() && processor->visible() && !_processors.empty()) {
736                                         /* check for invisible processors stacked at the end and leave them there */
737                                         ProcessorList::iterator p;
738                                         p = _processors.end();
739                                         --p;
740                                         cerr << "Let's check " << (*p)->name() << " vis ? " << (*p)->visible() << endl;
741                                         while (!(*p)->visible() && p != _processors.begin()) {
742                                                 --p;
743                                         }
744                                         ++p;
745                                         iter = p;
746                                 }
747
748                                 return (add_processor (processor, iter) == 0);
749                                 
750                         } else {
751                                 error << _("Processor XML node has no type property") << endmsg;
752                         }
753                 }
754
755                 catch (failed_constructor &err) {
756                         warning << _("processor could not be created. Ignored.") << endmsg;
757                         return false;
758                 }
759         }
760         return false;
761 }
762
763 int
764 Route::add_processors (const ProcessorList& others, Placement placement, ProcessorStreams* err)
765 {
766         ProcessorList::iterator loc;
767         if (placement == PreFader) {
768                 /* generic pre-fader: insert immediately before the amp */
769                 loc = find(_processors.begin(), _processors.end(), _amp);
770         } else {
771                 /* generic post-fader: insert at end */
772                 loc = _processors.end();
773
774                 if (!_processors.empty()) {
775                         /* check for invisible processors stacked at the end and leave them there */
776                         ProcessorList::iterator p;
777                         p = _processors.end();
778                         --p;
779                         cerr << "Let's check " << (*p)->name() << " vis ? " << (*p)->visible() << endl;
780                         while (!(*p)->visible() && p != _processors.begin()) {
781                                 --p;
782                         }
783                         ++p;
784                         loc = p;
785                 }
786         }
787
788         return add_processors (others, loc, err);
789 }
790
791 int
792 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
793 {
794         /* NOTE: this is intended to be used ONLY when copying
795            processors from another Route. Hence the subtle
796            differences between this and ::add_processor()
797         */
798
799         ChanCount old_pms = processor_max_streams;
800
801         if (!_session.engine().connected()) {
802                 return 1;
803         }
804
805         if (others.empty()) {
806                 return 0;
807         }
808
809         {
810                 Glib::RWLock::WriterLock lm (_processor_lock);
811                 ProcessorList::iterator existing_end = _processors.end();
812                 --existing_end;
813
814                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
815
816                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
817                         
818                         // Ensure meter only appears in the list once
819                         if (*i == _meter) {
820                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
821                                 if (m != _processors.end()) {
822                                         _processors.erase(m);
823                                 }
824                         }
825                         
826                         boost::shared_ptr<PluginInsert> pi;
827                         
828                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
829                                 pi->set_count (1);
830                                 
831                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
832                                 if (m > potential_max_streams)
833                                         potential_max_streams = m;
834                         }
835
836                         // Ensure peak vector sizes before the plugin is activated
837                         _meter->configure_io (potential_max_streams, potential_max_streams);
838                         
839                         _processors.insert (iter, *i);
840                         
841                         if (configure_processors_unlocked (err)) {
842                                 ++existing_end;
843                                 _processors.erase (existing_end, _processors.end());
844                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
845                                 return -1;
846                         }
847                         
848                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
849                 }
850
851                 _output->set_user_latency (0);
852         }
853         
854         processors_changed (); /* EMIT SIGNAL */
855
856         return 0;
857 }
858
859 void
860 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
861 {
862         if (p == PreFader) {
863                 start = _processors.begin();
864                 end = find(_processors.begin(), _processors.end(), _amp);
865         } else {
866                 start = find(_processors.begin(), _processors.end(), _amp);
867                 ++start;
868                 end = _processors.end();
869         }
870 }
871
872 /** Turn off all processors with a given placement
873  * @param p Placement of processors to disable
874  */
875 void
876 Route::disable_processors (Placement p)
877 {
878         Glib::RWLock::ReaderLock lm (_processor_lock);
879         
880         ProcessorList::iterator start, end;
881         placement_range(p, start, end);
882         
883         for (ProcessorList::iterator i = start; i != end; ++i) {
884                 (*i)->deactivate ();
885         }
886
887         _session.set_dirty ();
888 }
889
890 /** Turn off all redirects 
891  */
892 void
893 Route::disable_processors ()
894 {
895         Glib::RWLock::ReaderLock lm (_processor_lock);
896         
897         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
898                 (*i)->deactivate ();
899         }
900         
901         _session.set_dirty ();
902 }
903
904 /** Turn off all redirects with a given placement
905  * @param p Placement of redirects to disable
906  */
907 void
908 Route::disable_plugins (Placement p)
909 {
910         Glib::RWLock::ReaderLock lm (_processor_lock);
911         
912         ProcessorList::iterator start, end;
913         placement_range(p, start, end);
914         
915         for (ProcessorList::iterator i = start; i != end; ++i) {
916                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
917                         (*i)->deactivate ();
918                 }
919         }
920         
921         _session.set_dirty ();
922 }
923
924 /** Turn off all plugins
925  */
926 void
927 Route::disable_plugins ()
928 {
929         Glib::RWLock::ReaderLock lm (_processor_lock);
930         
931         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
932                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
933                         (*i)->deactivate ();
934                 }
935         }
936         
937         _session.set_dirty ();
938 }
939
940
941 void
942 Route::ab_plugins (bool forward)
943 {
944         Glib::RWLock::ReaderLock lm (_processor_lock);
945                         
946         if (forward) {
947
948                 /* forward = turn off all active redirects, and mark them so that the next time
949                    we go the other way, we will revert them
950                 */
951
952                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
953                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
954                                 continue;
955                         }
956
957                         if ((*i)->active()) {
958                                 (*i)->deactivate ();
959                                 (*i)->set_next_ab_is_active (true);
960                         } else {
961                                 (*i)->set_next_ab_is_active (false);
962                         }
963                 }
964
965         } else {
966
967                 /* backward = if the redirect was marked to go active on the next ab, do so */
968
969                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
970
971                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
972                                 continue;
973                         }
974
975                         if ((*i)->get_next_ab_is_active()) {
976                                 (*i)->activate ();
977                         } else {
978                                 (*i)->deactivate ();
979                         }
980                 }
981         }
982         
983         _session.set_dirty ();
984 }
985         
986         
987 /* Figure out the streams that will feed into PreFader */
988 ChanCount
989 Route::pre_fader_streams() const
990 {
991         boost::shared_ptr<Processor> processor;
992
993         /* Find the last pre-fader redirect that isn't a send; sends don't affect the number
994          * of streams. */
995         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
996                 if ((*i) == _amp) {
997                         break;
998                 }
999                 if (boost::dynamic_pointer_cast<Send> (*i) == 0) {
1000                         processor = *i;
1001                 }
1002         }
1003         
1004         if (processor) {
1005                 return processor->output_streams();
1006         } else {
1007                 return _input->n_ports ();
1008         }
1009 }
1010
1011
1012 /** Remove processors with a given placement.
1013  * @param p Placement of processors to remove.
1014  */
1015 void
1016 Route::clear_processors (Placement p)
1017 {
1018         const ChanCount old_pms = processor_max_streams;
1019
1020         if (!_session.engine().connected()) {
1021                 return;
1022         }
1023         
1024         bool already_deleting = _session.deletion_in_progress();
1025         if (!already_deleting) {
1026                 _session.set_deletion_in_progress();
1027         }
1028
1029         {
1030                 Glib::RWLock::WriterLock lm (_processor_lock);
1031                 ProcessorList new_list;
1032                 ProcessorStreams err;
1033
1034                 ProcessorList::iterator amp_loc = find(_processors.begin(), _processors.end(), _amp);
1035                 if (p == PreFader) {
1036                         // Get rid of PreFader processors
1037                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1038                                 (*i)->drop_references ();
1039                         }
1040                         // Keep the rest
1041                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1042                                 new_list.push_back (*i);
1043                         }
1044                 } else {
1045                         // Keep PreFader processors
1046                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1047                                 new_list.push_back (*i);
1048                         }
1049                         new_list.push_back (_amp);
1050                         // Get rid of PostFader processors
1051                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1052                                 (*i)->drop_references ();
1053                         }
1054                 }
1055
1056                 _processors = new_list;
1057                 configure_processors_unlocked (&err); // this can't fail
1058         }
1059
1060         processor_max_streams.reset();
1061         _have_internal_generator = false;
1062         processors_changed (); /* EMIT SIGNAL */
1063
1064         if (!already_deleting) {
1065                 _session.clear_deletion_in_progress();
1066         }
1067 }
1068
1069 int
1070 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1071 {
1072         /* these can never be removed */
1073
1074         if (processor == _amp || processor == _meter || processor == _main_outs) {
1075                 return 0;
1076         }
1077
1078         ChanCount old_pms = processor_max_streams;
1079
1080         if (!_session.engine().connected()) {
1081                 return 1;
1082         }
1083
1084         processor_max_streams.reset();
1085
1086         {
1087                 Glib::RWLock::WriterLock lm (_processor_lock);
1088                 ProcessorList::iterator i;
1089                 bool removed = false;
1090
1091                 for (i = _processors.begin(); i != _processors.end(); ) {
1092                         if (*i == processor) {
1093
1094                                 /* move along, see failure case for configure_processors()
1095                                    where we may need to reconfigure the processor.
1096                                 */
1097
1098                                 /* stop redirects that send signals to JACK ports
1099                                    from causing noise as a result of no longer being
1100                                    run.
1101                                 */
1102
1103                                 boost::shared_ptr<IOProcessor> iop;
1104
1105                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1106                                         if (iop->input()) {
1107                                                 iop->input()->disconnect (this);
1108                                         }
1109                                         if (iop->output()) {
1110                                                 iop->output()->disconnect (this);
1111                                         }
1112                                 }
1113
1114                                 i = _processors.erase (i);
1115                                 removed = true;
1116                                 break;
1117
1118                         } else {
1119                                 ++i;
1120                         }
1121
1122                         _output->set_user_latency (0);
1123                 }
1124
1125                 if (!removed) {
1126                         /* what? */
1127                         return 1;
1128                 }
1129
1130                 if (configure_processors_unlocked (err)) {
1131                         /* get back to where we where */
1132                         _processors.insert (i, processor);
1133                         /* we know this will work, because it worked before :) */
1134                         configure_processors_unlocked (0);
1135                         return -1;
1136                 }
1137
1138                 _have_internal_generator = false;
1139
1140                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1141                         boost::shared_ptr<PluginInsert> pi;
1142                         
1143                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1144                                 if (pi->is_generator()) {
1145                                         _have_internal_generator = true;
1146                                         break;
1147                                 }
1148                         }
1149                 }
1150         }
1151
1152         processor->drop_references ();
1153         processors_changed (); /* EMIT SIGNAL */
1154
1155         return 0;
1156 }
1157
1158 int
1159 Route::configure_processors (ProcessorStreams* err)
1160 {
1161         if (!_in_configure_processors) {
1162                 Glib::RWLock::WriterLock lm (_processor_lock);
1163                 return configure_processors_unlocked (err);
1164         }
1165         return 0;
1166 }
1167
1168 /** Configure the input/output configuration of each processor in the processors list.
1169  * Return 0 on success, otherwise configuration is impossible.
1170  */
1171 int
1172 Route::configure_processors_unlocked (ProcessorStreams* err)
1173 {
1174         if (_in_configure_processors) {
1175            return 0;
1176         }
1177
1178         _in_configure_processors = true;
1179
1180         // Check each processor in order to see if we can configure as requested
1181         ChanCount in = _input->n_ports ();
1182         ChanCount out;
1183         list< pair<ChanCount,ChanCount> > configuration;
1184         uint32_t index = 0;
1185         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1186                 if ((*p)->can_support_io_configuration(in, out)) {
1187                         configuration.push_back(make_pair(in, out));
1188                         in = out;
1189                 } else {
1190                         if (err) {
1191                                 err->index = index;
1192                                 err->count = in;
1193                         }
1194                         _in_configure_processors = false;
1195                         return -1;
1196                 }
1197         }
1198         
1199         // We can, so configure everything
1200         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1201         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1202                 (*p)->configure_io(c->first, c->second);
1203                 (*p)->activate();
1204                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1205                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1206                 out = c->second;
1207         }
1208
1209         // Ensure route outputs match last processor's outputs
1210         if (out != _output->n_ports ()) {
1211                 _output->ensure_io (out, false, this);
1212         }
1213
1214         _in_configure_processors = false;
1215         return 0;
1216 }
1217
1218 void
1219 Route::all_processors_flip ()
1220 {
1221         Glib::RWLock::ReaderLock lm (_processor_lock);
1222
1223         if (_processors.empty()) {
1224                 return;
1225         }
1226
1227         bool first_is_on = _processors.front()->active();
1228         
1229         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1230                 if (first_is_on) {
1231                         (*i)->deactivate ();
1232                 } else {
1233                         (*i)->activate ();
1234                 }
1235         }
1236         
1237         _session.set_dirty ();
1238 }
1239
1240 /** Set all processors with a given placement to a given active state.
1241  * @param p Placement of processors to change.
1242  * @param state New active state for those processors.
1243  */
1244 void
1245 Route::all_processors_active (Placement p, bool state)
1246 {
1247         Glib::RWLock::ReaderLock lm (_processor_lock);
1248
1249         if (_processors.empty()) {
1250                 return;
1251         }
1252         ProcessorList::iterator start, end;
1253         placement_range(p, start, end);
1254
1255         bool before_amp = true;
1256         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1257                 if ((*i) == _amp) {
1258                         before_amp = false;
1259                         continue;
1260                 }
1261                 if (p == PreFader && before_amp) {
1262                         if (state) {
1263                                 (*i)->activate ();
1264                         } else {
1265                                 (*i)->deactivate ();
1266                         }
1267                 }
1268         }
1269         
1270         _session.set_dirty ();
1271 }
1272
1273 int
1274 Route::reorder_processors (const ProcessorList& new_order, Placement placement, ProcessorStreams* err)
1275 {
1276         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1277            NOTE: all processors in "new_order" MUST be marked as visible. There maybe additional
1278            processors in the current actual processor list that are hidden. Any visible processors
1279            in the current list but not in "new_order" will be assumed to be deleted.
1280         */
1281
1282         {
1283                 Glib::RWLock::WriterLock lm (_processor_lock);
1284                 ChanCount old_pms = processor_max_streams;
1285                 ProcessorList::iterator oiter;
1286                 ProcessorList::const_iterator niter;
1287                 ProcessorList as_it_was_before = _processors;
1288                 ProcessorList as_it_will_be;
1289                 ProcessorList::iterator start, end;
1290
1291                 placement_range (placement, start, end);
1292
1293                 oiter = start;
1294                 niter = new_order.begin(); 
1295
1296                 while (niter !=  new_order.end()) {
1297                         
1298                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1299                            then append it to the temp list. 
1300
1301                            Otherwise, see if the next processor in the old list is in the new list. if not,
1302                            its been deleted. If its there, append it to the temp list.
1303                         */
1304
1305                         if (oiter == end) {
1306
1307                                 /* no more elements in the old list, so just stick the rest of 
1308                                    the new order onto the temp list.
1309                                 */
1310
1311                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1312                                 while (niter != new_order.end()) {
1313                                         (*niter)->set_placement (placement);
1314                                         ++niter;
1315                                 }
1316                                 break;
1317
1318                         } else {
1319                                 
1320                                 if (!(*oiter)->visible()) {
1321
1322                                         as_it_will_be.push_back (*oiter);
1323                                         (*oiter)->set_placement (placement);
1324
1325                                 } else {
1326
1327                                         /* visible processor: check that its in the new order */
1328
1329                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1330                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1331                                         } else {
1332                                                 /* ignore this one, and add the next item from the new order instead */
1333                                                 as_it_will_be.push_back (*niter);
1334                                                 (*niter)->set_placement (placement);
1335                                                 ++niter;
1336                                         }
1337                                 }
1338                                 
1339                                 /* now remove from old order - its taken care of no matter what */
1340                                 oiter = _processors.erase (oiter);
1341                         }
1342                         
1343                 }
1344
1345                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1346
1347                 if (configure_processors_unlocked (err)) {
1348                         _processors = as_it_was_before;
1349                         processor_max_streams = old_pms;
1350                         return -1;
1351                 } 
1352         } 
1353
1354         processors_changed (); /* EMIT SIGNAL */
1355
1356         return 0;
1357 }
1358
1359 XMLNode&
1360 Route::get_state()
1361 {
1362         return state(true);
1363 }
1364
1365 XMLNode&
1366 Route::get_template()
1367 {
1368         return state(false);
1369 }
1370
1371 XMLNode&
1372 Route::state(bool full_state)
1373 {
1374         XMLNode *node = new XMLNode("Route");
1375         ProcessorList::iterator i;
1376         char buf[32];
1377
1378         node->add_property ("name", _name);
1379         node->add_property("default-type", _default_type.to_string());
1380
1381         if (_flags) {
1382                 node->add_property("flags", enum_2_string (_flags));
1383         }
1384
1385         node->add_property("active", _active?"yes":"no");
1386         node->add_property("phase-invert", _phase_invert?"yes":"no");
1387         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1388         node->add_property("meter-point", enum_2_string (_meter_point));
1389
1390         if (_edit_group) {
1391                 node->add_property("edit-group", _edit_group->name());
1392         }
1393         if (_mix_group) {
1394                 node->add_property("mix-group", _mix_group->name());
1395         }
1396
1397         string order_string;
1398         OrderKeys::iterator x = order_keys.begin(); 
1399
1400         while (x != order_keys.end()) {
1401                 order_string += string ((*x).first);
1402                 order_string += '=';
1403                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1404                 order_string += buf;
1405                 
1406                 ++x;
1407
1408                 if (x == order_keys.end()) {
1409                         break;
1410                 }
1411
1412                 order_string += ':';
1413         }
1414         node->add_property ("order-keys", order_string);
1415
1416         node->add_child_nocopy (_input->state (full_state));
1417         node->add_child_nocopy (_output->state (full_state));
1418         node->add_child_nocopy (_solo_control->get_state ());
1419         node->add_child_nocopy (_mute_master->get_state ());
1420
1421         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1422         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1423         remote_control_node->add_property (X_("id"), buf);
1424         node->add_child_nocopy (*remote_control_node);
1425
1426         if (_comment.length()) {
1427                 XMLNode *cmt = node->add_child ("Comment");
1428                 cmt->add_content (_comment);
1429         }
1430
1431         for (i = _processors.begin(); i != _processors.end(); ++i) {
1432                 node->add_child_nocopy((*i)->state (full_state));
1433         }
1434
1435         if (_extra_xml){
1436                 node->add_child_copy (*_extra_xml);
1437         }
1438         
1439         return *node;
1440 }
1441
1442 int
1443 Route::set_state (const XMLNode& node)
1444 {
1445         return _set_state (node, true);
1446 }
1447
1448 int
1449 Route::_set_state (const XMLNode& node, bool call_base)
1450 {
1451
1452         XMLNodeList nlist;
1453         XMLNodeConstIterator niter;
1454         XMLNode *child;
1455         XMLPropertyList plist;
1456         const XMLProperty *prop;
1457
1458         if (node.name() != "Route"){
1459                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1460                 return -1;
1461         }
1462
1463         if ((prop = node.property (X_("name"))) != 0) {
1464                 Route::set_name (prop->value());
1465         } 
1466
1467         if ((prop = node.property (X_("flags"))) != 0) {
1468                 _flags = Flag (string_2_enum (prop->value(), _flags));
1469         } else {
1470                 _flags = Flag (0);
1471         }
1472         
1473         if ((prop = node.property (X_("phase-invert"))) != 0) {
1474                 set_phase_invert (prop->value()=="yes"?true:false, this);
1475         }
1476
1477         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1478                 set_denormal_protection (prop->value()=="yes"?true:false, this);
1479         }
1480         
1481         if ((prop = node.property (X_("active"))) != 0) {
1482                 bool yn = (prop->value() == "yes");
1483                 _active = !yn; // force switch
1484                 set_active (yn);
1485         }
1486
1487         if ((prop = node.property (X_("soloed"))) != 0) {
1488                 bool yn = (prop->value()=="yes");
1489
1490                 /* XXX force reset of solo status */
1491
1492                 set_solo (yn, this);
1493         }
1494
1495         if ((prop = node.property (X_("meter-point"))) != 0) {
1496                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1497         }
1498         
1499         if ((prop = node.property (X_("edit-group"))) != 0) {
1500                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1501                 if(edit_group == 0) {
1502                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1503                 } else {
1504                         set_edit_group(edit_group, this);
1505                 }
1506         }
1507
1508         if ((prop = node.property (X_("order-keys"))) != 0) {
1509
1510                 long n;
1511
1512                 string::size_type colon, equal;
1513                 string remaining = prop->value();
1514
1515                 while (remaining.length()) {
1516
1517                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1518                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1519                                       << endmsg;
1520                         } else {
1521                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1522                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1523                                               << endmsg;
1524                                 } else {
1525                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1526                                 }
1527                         }
1528
1529                         colon = remaining.find_first_of (':');
1530
1531                         if (colon != string::npos) {
1532                                 remaining = remaining.substr (colon+1);
1533                         } else {
1534                                 break;
1535                         }
1536                 }
1537         }
1538
1539         nlist = node.children();
1540         XMLNode processor_state (X_("processor_state"));
1541
1542         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1543                 
1544                 child = *niter;
1545
1546                 if (child->name() == IO::state_node_name) {
1547                         if ((prop = child->property (X_("direction"))) == 0) {
1548                                 continue;
1549                         }
1550                         
1551                         if (prop->value() == "Input") {
1552                                 _input->set_state (*child);
1553                         } else if (prop->value() == "Output") {
1554                                 _output->set_state (*child);
1555                         }
1556                 }
1557                         
1558                 if (child->name() == X_("Processor")) {
1559                         processor_state.add_child_copy (*child);
1560                 }
1561         }
1562
1563         set_processor_state (processor_state);
1564         
1565         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1566                 child = *niter;
1567
1568                 if (child->name() == X_("Comment")) {
1569
1570                         /* XXX this is a terrible API design in libxml++ */
1571
1572                         XMLNode *cmt = *(child->children().begin());
1573                         _comment = cmt->content();
1574
1575                 } else if (child->name() == X_("Extra")) {
1576
1577                         _extra_xml = new XMLNode (*child);
1578
1579                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1580                         
1581                         if (prop->value() == "solo") {
1582                                 _solo_control->set_state (*child);
1583                                 _session.add_controllable (_solo_control);
1584                         } 
1585
1586                 } else if (child->name() == X_("RemoteControl")) {
1587                         if ((prop = child->property (X_("id"))) != 0) {
1588                                 int32_t x;
1589                                 sscanf (prop->value().c_str(), "%d", &x);
1590                                 set_remote_control_id (x);
1591                         }
1592                 } 
1593         }
1594
1595         if ((prop = node.property (X_("mix-group"))) != 0) {
1596                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1597                 if (mix_group == 0) {
1598                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1599                 }  else {
1600                         set_mix_group(mix_group, this);
1601                 }
1602         }
1603
1604         return 0;
1605 }
1606
1607 XMLNode&
1608 Route::get_processor_state ()
1609 {
1610         XMLNode* root = new XMLNode (X_("redirects"));
1611         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1612                 root->add_child_nocopy ((*i)->state (true));
1613         }
1614
1615         return *root;
1616 }
1617
1618 void
1619 Route::set_processor_state (const XMLNode& node)
1620 {
1621         const XMLNodeList &nlist = node.children();
1622         XMLNodeConstIterator niter;
1623         bool has_meter_processor = false; // legacy sessions don't
1624         ProcessorList::iterator i, o;
1625
1626         cerr << _name << " _set_processor_states\n";
1627
1628         // Iterate through existing processors, remove those which are not in the state list
1629         for (i = _processors.begin(); i != _processors.end(); ) {
1630                 ProcessorList::iterator tmp = i;
1631                 ++tmp;
1632
1633                 bool processorInStateList = false;
1634         
1635                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1636
1637                         XMLProperty* id_prop = (*niter)->property(X_("id"));
1638                         if (id_prop && (*i)->id() == id_prop->value()) {
1639                                 processorInStateList = true;
1640                                 break;
1641                         }
1642                 }
1643                 
1644                 if (!processorInStateList) {
1645                         remove_processor (*i);
1646                 }
1647
1648                 i = tmp;
1649         }
1650
1651         // Iterate through state list and make sure all processors are on the track and in the correct order,
1652         // set the state of existing processors according to the new state on the same go
1653         i = _processors.begin();
1654
1655         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
1656                 
1657                 XMLProperty* prop = (*niter)->property ("type");
1658
1659                 if (prop && prop->value() == "meter")  {
1660                         has_meter_processor = true;
1661                 }
1662
1663                 cerr << _name << " setting up proc state for " << prop->value() << endl;
1664
1665                 o = i;
1666
1667                 if (prop->value() != "meter" && prop->value() != "amp" && prop->value() != "main-outs") {
1668
1669                         // Check whether the next processor in the list 
1670                         
1671                         while (o != _processors.end()) {
1672                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
1673                                 if (id_prop && (*o)->id() == id_prop->value()) {
1674                                         break;
1675                                 }
1676                                 
1677                                 ++o;
1678                         }
1679                 }
1680
1681                 // If the processor (*niter) is not on the route,
1682                 // create it and move it to the correct location
1683                 if (o == _processors.end()) {
1684
1685                         cerr << "\tproc not in list\n";
1686
1687                         if (add_processor_from_xml (**niter, i)) {
1688                                 --i; // move iterator to the newly inserted processor
1689                         } else {
1690                                 cerr << "Error restoring route: unable to restore processor" << endl;
1691                         }
1692
1693                 // Otherwise, the processor already exists; just
1694                 // ensure it is at the location provided in the XML state
1695                 } else {
1696
1697                         cerr << "\tproc in wrong place in list\n";
1698                         
1699                         if (i != o) {
1700                                 boost::shared_ptr<Processor> tmp = (*o);
1701                                 _processors.erase (o); // remove the old copy
1702                                 _processors.insert (i, tmp); // insert the processor at the correct location
1703                                 --i; // move iterator to the correct processor
1704                         }
1705
1706                         cerr << "\tnow reset proc " << (*i)->name() << endl;
1707                         (*i)->set_state (**niter);
1708                 }
1709         }
1710
1711         /* note: there is no configure_processors() call because we figure that
1712            the XML state represents a working signal route.
1713         */
1714
1715         if (!has_meter_processor) {
1716                 set_meter_point (_meter_point, NULL);
1717         }
1718
1719         processors_changed ();
1720 }
1721
1722 void
1723 Route::curve_reallocate ()
1724 {
1725 //      _gain_automation_curve.finish_resize ();
1726 //      _pan_automation_curve.finish_resize ();
1727 }
1728
1729 void
1730 Route::silence (nframes_t nframes)
1731 {
1732         if (!_silent) {
1733
1734                 _output->silence (nframes);
1735                 
1736                 { 
1737                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
1738                         
1739                         if (lm.locked()) {
1740                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1741                                         boost::shared_ptr<PluginInsert> pi;
1742
1743                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1744                                                 // skip plugins, they don't need anything when we're not active
1745                                                 continue;
1746                                         }
1747                                         
1748                                         (*i)->silence (nframes);
1749                                 }
1750
1751                                 if (nframes == _session.get_block_size()) {
1752                                         // _silent = true;
1753                                 }
1754                         }
1755                 }
1756                 
1757         }
1758 }       
1759
1760 boost::shared_ptr<Delivery>
1761 Route::add_listener (boost::shared_ptr<IO> io, const string& listen_name)
1762 {
1763         string name = _name;
1764         name += '[';
1765         name += listen_name;
1766         name += ']';
1767         
1768         boost::shared_ptr<Delivery> listener (new Delivery (_session, _mute_master, name, Delivery::Listen)); 
1769
1770         /* As an IO, our control outs need as many IO outputs as we have outputs
1771          *   (we track the changes in ::output_change_handler()).
1772          * As a processor, the listener is an identity processor
1773          *   (i.e. it does not modify its input buffers whatsoever)
1774          */
1775
1776         if (listener->output()->ensure_io (n_outputs(), true, this)) {
1777                 return boost::shared_ptr<Delivery>();
1778         }
1779         
1780         add_processor (listener, PostFader);
1781
1782         return listener;
1783 }
1784
1785 int
1786 Route::listen_via (boost::shared_ptr<IO> io, const string& listen_name)
1787 {
1788         vector<string> ports;
1789         vector<string>::const_iterator i;
1790
1791         {
1792                 Glib::RWLock::ReaderLock rm (_processor_lock);
1793                 
1794                 for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
1795                         boost::shared_ptr<const Delivery> d = boost::dynamic_pointer_cast<const Delivery>(*x);
1796
1797                         if (d && d->output() == io) {
1798                                 /* already listening via the specified IO: do nothing */
1799                                 return 0;
1800                         }
1801                 }
1802         }
1803
1804         uint32_t ni = io->n_ports().n_total();
1805
1806         for (uint32_t n = 0; n < ni; ++n) {
1807                 ports.push_back (io->nth (n)->name());
1808         }
1809
1810         if (ports.empty()) {
1811                 return 0;
1812         }
1813         
1814         boost::shared_ptr<Delivery> listen_point = add_listener (io, listen_name);
1815         
1816         /* XXX hack for now .... until we can generalize listen points */
1817
1818         _control_outs = listen_point;
1819
1820         /* now connect to the named ports */
1821         
1822         ni = listen_point->output()->n_ports().n_total();
1823         size_t psize = ports.size();
1824
1825         for (size_t n = 0; n < ni; ++n) {
1826                 if (listen_point->output()->connect (listen_point->output()->nth (n), ports[n % psize], this)) {
1827                         error << string_compose (_("could not connect %1 to %2"),
1828                                                  listen_point->output()->nth (n)->name(), ports[n % psize]) << endmsg;
1829                         return -1;
1830                 }
1831         }
1832
1833         
1834         return 0;
1835 }       
1836
1837 void
1838 Route::drop_listen (boost::shared_ptr<IO> io)
1839 {
1840         ProcessorStreams err;
1841         ProcessorList::iterator tmp;
1842
1843         Glib::RWLock::ReaderLock rm (_processor_lock);
1844         
1845         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
1846                 
1847                 tmp = x;
1848                 ++tmp;
1849                 
1850                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*x);
1851                 
1852                 if (d && d->output() == io) {
1853                         /* already listening via the specified IO: do nothing */
1854                         remove_processor (*x, &err);
1855                         
1856                 } 
1857                 
1858                 x = tmp;
1859         }
1860 }
1861
1862 void
1863 Route::set_edit_group (RouteGroup *eg, void *src)
1864
1865 {
1866         if (eg == _edit_group) {
1867                 return;
1868         }
1869
1870         if (_edit_group) {
1871                 _edit_group->remove (this);
1872         }
1873
1874         if ((_edit_group = eg) != 0) {
1875                 _edit_group->add (this);
1876         }
1877
1878         _session.set_dirty ();
1879         edit_group_changed (src); /* EMIT SIGNAL */
1880 }
1881
1882 void
1883 Route::drop_edit_group (void *src)
1884 {
1885         _edit_group = 0;
1886         _session.set_dirty ();
1887         edit_group_changed (src); /* EMIT SIGNAL */
1888 }
1889
1890 void
1891 Route::set_mix_group (RouteGroup *mg, void *src)
1892
1893 {
1894         if (mg == _mix_group) {
1895                 return;
1896         }
1897
1898         if (_mix_group) {
1899                 _mix_group->remove (this);
1900         }
1901
1902         if ((_mix_group = mg) != 0) {
1903                 _mix_group->add (this);
1904         }
1905
1906         _session.set_dirty ();
1907         mix_group_changed (src); /* EMIT SIGNAL */
1908 }
1909
1910 void
1911 Route::drop_mix_group (void *src)
1912 {
1913         _mix_group = 0;
1914         _session.set_dirty ();
1915         mix_group_changed (src); /* EMIT SIGNAL */
1916 }
1917
1918 void
1919 Route::set_comment (string cmt, void *src)
1920 {
1921         _comment = cmt;
1922         comment_changed (src);
1923         _session.set_dirty ();
1924 }
1925
1926 bool
1927 Route::feeds (boost::shared_ptr<IO> other)
1928 {
1929         if (_output->connected_to (other)) {
1930                 return true;
1931         }
1932
1933         /* check IOProcessors which may also interconnect Routes */
1934
1935         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
1936
1937                 boost::shared_ptr<IOProcessor> iop;
1938                 
1939                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
1940                         if (iop->output() && iop->output()->connected_to (other)) {
1941                                 return true;
1942                         }
1943                 }
1944         }
1945
1946         return false;
1947 }
1948
1949 void
1950 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
1951 {
1952         nframes_t now = _session.transport_frame();
1953
1954         {
1955                 Glib::RWLock::ReaderLock lm (_processor_lock);
1956
1957                 if (!did_locate) {
1958                         automation_snapshot (now, true);
1959                 }
1960
1961                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1962                         
1963                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
1964                                 (*i)->deactivate ();
1965                                 (*i)->activate ();
1966                         }
1967                         
1968                         (*i)->transport_stopped (now);
1969                 }
1970         }
1971
1972         _roll_delay = _initial_delay;
1973 }
1974
1975 void
1976 Route::input_change_handler (IOChange change, void *src)
1977 {
1978         if ((change & ConfigurationChanged)) {
1979                 configure_processors (0);
1980         }
1981 }
1982
1983 void
1984 Route::output_change_handler (IOChange change, void *src)
1985 {
1986         if ((change & ConfigurationChanged)) {
1987                 
1988                 /* XXX resize all listeners to match _main_outs? */
1989                 
1990                 // configure_processors (0);
1991         }
1992 }
1993
1994 uint32_t
1995 Route::pans_required () const
1996 {
1997         if (n_outputs().n_audio() < 2) {
1998                 return 0;
1999         }
2000         
2001         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2002 }
2003
2004 int 
2005 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,  
2006                 bool session_state_changing, bool can_record, bool rec_monitors_input)
2007 {
2008         if (n_outputs().n_total() == 0) {
2009                 return 0;
2010         }
2011
2012         if (session_state_changing || !_active || n_inputs() == ChanCount::ZERO)  {
2013                 silence (nframes);
2014                 return 0;
2015         }
2016
2017         _amp->apply_gain_automation (false);
2018         passthru (start_frame, end_frame, nframes, 0);
2019
2020         return 0;
2021 }
2022
2023 nframes_t
2024 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2025 {
2026         if (_roll_delay > nframes) {
2027
2028                 _roll_delay -= nframes;
2029                 silence (nframes);
2030                 /* transport frame is not legal for caller to use */
2031                 return 0;
2032
2033         } else if (_roll_delay > 0) {
2034
2035                 nframes -= _roll_delay;
2036                 silence (_roll_delay);
2037                 /* we've written _roll_delay of samples into the 
2038                    output ports, so make a note of that for
2039                    future reference.
2040                 */
2041                 _main_outs->increment_output_offset (_roll_delay);
2042                 transport_frame += _roll_delay;
2043
2044                 _roll_delay = 0;
2045         }
2046
2047         return nframes;
2048 }
2049
2050 int
2051 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2052              bool can_record, bool rec_monitors_input)
2053 {
2054         {
2055                 // automation snapshot can also be called from the non-rt context
2056                 // and it uses the processor list, so we try to acquire the lock here
2057                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2058
2059                 if (lm.locked()) {
2060                         automation_snapshot (_session.transport_frame(), false);
2061                 }
2062         }
2063
2064         if (n_outputs().n_total() == 0) {
2065                 return 0;
2066         }
2067
2068         if (!_active || n_inputs().n_total() == 0) {
2069                 silence (nframes);
2070                 return 0;
2071         }
2072         
2073         nframes_t unused = 0;
2074
2075         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2076                 return 0;
2077         }
2078
2079         _silent = false;
2080
2081         passthru (start_frame, end_frame, nframes, declick);
2082
2083         return 0;
2084 }
2085
2086 int
2087 Route::silent_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, 
2088                     bool can_record, bool rec_monitors_input)
2089 {
2090         silence (nframes);
2091         return 0;
2092 }
2093
2094 void
2095 Route::toggle_monitor_input ()
2096 {
2097         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2098                 i->ensure_monitor_input( ! i->monitoring_input());
2099         }
2100 }
2101
2102 bool
2103 Route::has_external_redirects () const
2104 {
2105         // FIXME: what about sends? - they don't return a signal back to ardour?
2106
2107         boost::shared_ptr<const PortInsert> pi;
2108         
2109         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2110
2111                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2112
2113                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2114                                 
2115                                 string port_name = port->name();
2116                                 string client_name = port_name.substr (0, port_name.find(':'));
2117
2118                                 /* only say "yes" if the redirect is actually in use */
2119                                 
2120                                 if (client_name != "ardour" && pi->active()) {
2121                                         return true;
2122                                 }
2123                         }
2124                 }
2125         }
2126
2127         return false;
2128 }
2129
2130 void
2131 Route::flush_processors ()
2132 {
2133         /* XXX shouldn't really try to take this lock, since
2134            this is called from the RT audio thread.
2135         */
2136
2137         Glib::RWLock::ReaderLock lm (_processor_lock);
2138
2139         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2140                 (*i)->deactivate ();
2141                 (*i)->activate ();
2142         }
2143 }
2144
2145 void
2146 Route::set_meter_point (MeterPoint p, void *src)
2147 {
2148         if (_meter_point != p) {
2149                 _meter_point = p;
2150
2151                 // Move meter in the processors list
2152                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _meter);
2153                 _processors.erase(loc);
2154                 switch (p) {
2155                 case MeterInput:
2156                         loc = _processors.begin();
2157                         break;
2158                 case MeterPreFader:
2159                         loc = find(_processors.begin(), _processors.end(), _amp);
2160                         break;
2161                 case MeterPostFader:
2162                         loc = _processors.end();
2163                         break;
2164                 }
2165                 _processors.insert(loc, _meter);
2166                 
2167                  meter_change (src); /* EMIT SIGNAL */
2168                 processors_changed (); /* EMIT SIGNAL */
2169                 _session.set_dirty ();
2170         }
2171 }
2172
2173 nframes_t
2174 Route::update_total_latency ()
2175 {
2176         nframes_t old = _output->effective_latency();
2177         nframes_t own_latency = _output->user_latency();
2178
2179         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2180                 if ((*i)->active ()) {
2181                         own_latency += (*i)->signal_latency ();
2182                 }
2183         }
2184
2185 #undef DEBUG_LATENCY
2186 #ifdef DEBUG_LATENCY
2187         cerr << _name << ": internal redirect latency = " << own_latency << endl;
2188 #endif
2189
2190         _output->set_port_latency (own_latency);
2191         
2192         if (_output->user_latency() == 0) {
2193
2194                 /* this (virtual) function is used for pure Routes,
2195                    not derived classes like AudioTrack.  this means
2196                    that the data processed here comes from an input
2197                    port, not prerecorded material, and therefore we
2198                    have to take into account any input latency.
2199                 */
2200                 
2201                 own_latency += _input->signal_latency ();
2202         }
2203
2204         if (old != own_latency) {
2205                 _output->set_latency_delay (own_latency);
2206                 signal_latency_changed (); /* EMIT SIGNAL */
2207         }
2208         
2209 #ifdef DEBUG_LATENCY
2210         cerr << _name << ": input latency = " << _input->signal_latency() << " total = "
2211              << own_latency << endl;
2212 #endif
2213
2214         return _output->effective_latency ();
2215 }
2216
2217 void
2218 Route::set_user_latency (nframes_t nframes)
2219 {
2220         _output->set_user_latency (nframes);
2221         _session.update_latency_compensation (false, false);
2222 }
2223
2224 void
2225 Route::set_latency_delay (nframes_t longest_session_latency)
2226 {
2227         nframes_t old = _initial_delay;
2228
2229         if (_output->effective_latency() < longest_session_latency) {
2230                 _initial_delay = longest_session_latency - _output->effective_latency();
2231         } else {
2232                 _initial_delay = 0;
2233         }
2234
2235         if (_initial_delay != old) {
2236                 initial_delay_changed (); /* EMIT SIGNAL */
2237         }
2238
2239         if (_session.transport_stopped()) {
2240                 _roll_delay = _initial_delay;
2241         }
2242 }
2243
2244 void
2245 Route::automation_snapshot (nframes_t now, bool force)
2246 {
2247         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2248                 (*i)->automation_snapshot (now, force);
2249         }
2250 }
2251
2252 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2253         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation), 
2254                              boost::shared_ptr<AutomationList>(), name)
2255         , route (r)
2256 {
2257         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2258         set_list (gl);
2259 }
2260
2261 void
2262 Route::SoloControllable::set_value (float val)
2263 {
2264         bool bval = ((val >= 0.5f) ? true: false);
2265         
2266         route.set_solo (bval, this);
2267 }
2268
2269 float
2270 Route::SoloControllable::get_value (void) const
2271 {
2272         return route.soloed() ? 1.0f : 0.0f;
2273 }
2274
2275 void 
2276 Route::set_block_size (nframes_t nframes)
2277 {
2278         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2279                 (*i)->set_block_size (nframes);
2280         }
2281         _session.ensure_buffers(processor_max_streams);
2282 }
2283
2284 void
2285 Route::protect_automation ()
2286 {
2287         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2288                 (*i)->protect_automation();
2289 }
2290
2291 void
2292 Route::set_pending_declick (int declick)
2293 {
2294         if (_declickable) {
2295                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2296                 if (declick) {
2297                         _pending_declick = declick;
2298                 }
2299                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2300         } else {
2301                 _pending_declick = 0;
2302         }
2303
2304 }
2305
2306 /** Shift automation forwards from a particular place, thereby inserting time.
2307  *  Adds undo commands for any shifts that are performed.
2308  *
2309  * @param pos Position to start shifting from.
2310  * @param frames Amount to shift forwards by.
2311  */
2312
2313 void
2314 Route::shift (nframes64_t pos, nframes64_t frames)
2315 {
2316 #ifdef THIS_NEEDS_FIXING_FOR_V3
2317
2318         /* gain automation */
2319         XMLNode &before = _gain_control->get_state ();
2320         _gain_control->shift (pos, frames);
2321         XMLNode &after = _gain_control->get_state ();
2322         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2323
2324         /* pan automation */
2325         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2326                 Curve & c = (*i)->automation ();
2327                 XMLNode &before = c.get_state ();
2328                 c.shift (pos, frames);
2329                 XMLNode &after = c.get_state ();
2330                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2331         }
2332
2333         /* redirect automation */
2334         {
2335                 Glib::RWLock::ReaderLock lm (redirect_lock);
2336                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2337                         
2338                         set<uint32_t> a;
2339                         (*i)->what_has_automation (a);
2340                         
2341                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2342                                 AutomationList & al = (*i)->automation_list (*j);
2343                                 XMLNode &before = al.get_state ();
2344                                 al.shift (pos, frames);
2345                                 XMLNode &after = al.get_state ();
2346                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2347                         }
2348                 }
2349         }
2350 #endif
2351
2352 }
2353
2354
2355 int
2356 Route::save_as_template (const string& path, const string& name)
2357 {
2358         XMLNode& node (state (false));
2359         XMLTree tree;
2360         
2361         IO::set_name_in_state (*node.children().front(), name);
2362         
2363         tree.set_root (&node);
2364         return tree.write (path.c_str());
2365 }
2366
2367
2368 bool
2369 Route::set_name (const string& str)
2370 {
2371         bool ret;
2372         string ioproc_name;
2373         
2374         SessionObject::set_name (str);
2375         
2376         ret = (_input->set_name(str) && _output->set_name(str));
2377
2378         if (ret) {
2379                 
2380                 Glib::RWLock::ReaderLock lm (_processor_lock);
2381                 
2382                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2383                         
2384                         /* rename all processors with outputs to reflect our new name */
2385
2386                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
2387
2388                         if (iop) {
2389                                 string iop_name = str;
2390                                 iop_name += '[';
2391                                 iop_name += "XXX FIX ME XXX";
2392                                 iop_name += ']';
2393                                 
2394                                 if (!iop->set_name (iop_name)) {
2395                                         ret = false;
2396                                 }
2397                         }
2398                 }
2399
2400         }
2401
2402         return ret;
2403 }
2404
2405 boost::shared_ptr<Send>
2406 Route::send_for (boost::shared_ptr<const IO> target) const
2407 {
2408         Glib::RWLock::ReaderLock lm (_processor_lock);
2409
2410         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2411                 boost::shared_ptr<Send> send;
2412                 
2413                 if ((send = boost::dynamic_pointer_cast<Send>(*i)) != 0) {
2414                         if (send->output()->connected_to (target)) {
2415                                 return send;
2416                         }
2417                 }
2418         }
2419         
2420         return boost::shared_ptr<Send>();
2421 }
2422
2423 void
2424 Route::set_phase_invert (bool yn, void *src)
2425 {
2426         if (_phase_invert != yn) {
2427                 _phase_invert = yn;
2428                 //  phase_invert_changed (src); /* EMIT SIGNAL */
2429         }
2430 }
2431
2432 bool
2433 Route::phase_invert () const
2434 {
2435         return _phase_invert != 0;
2436 }
2437
2438 void
2439 Route::set_denormal_protection (bool yn, void *src)
2440 {
2441         if (_denormal_protection != yn) {
2442                 _denormal_protection = yn;
2443                 //  denormal_protection_changed (src); /* EMIT SIGNAL */
2444         }
2445 }
2446
2447 bool
2448 Route::denormal_protection () const
2449 {
2450         return _denormal_protection;
2451 }
2452
2453 void
2454 Route::set_active (bool yn)
2455 {
2456         if (_active != yn) {
2457                 _active = yn;
2458                 _input->set_active (yn);
2459                 _output->set_active (yn);
2460                 active_changed (); // EMIT SIGNAL
2461         }
2462 }
2463
2464 void
2465 Route::meter ()
2466 {
2467         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
2468         _meter->meter ();
2469 }
2470
2471 boost::shared_ptr<Panner>
2472 Route::panner() const
2473 {
2474
2475         return _main_outs->panner();
2476 }
2477
2478 boost::shared_ptr<AutomationControl>
2479 Route::gain_control() const
2480 {
2481
2482         return _amp->gain_control();
2483 }
2484
2485 boost::shared_ptr<AutomationControl>
2486 Route::get_control (const Evoral::Parameter& param)
2487 {
2488         /* either we own the control or .... */
2489
2490         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(data().control (param));
2491
2492         if (!c) {
2493
2494                 /* maybe one of our processors does or ... */
2495                 
2496                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
2497                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2498                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->data().control (param))) != 0) {
2499                                 break;
2500                         }
2501                 }
2502         }
2503                 
2504         if (!c) {
2505
2506                 /* nobody does so we'll make a new one */
2507
2508                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
2509                 add_control(c);
2510         }
2511
2512         return c;
2513 }