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