nick m's fix for markers etc ; several tweaks for mute/solo ; rename run_in_place...
[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         node->add_property ("name", _name);
1392         node->add_property("default-type", _default_type.to_string());
1393
1394         if (_flags) {
1395                 node->add_property("flags", enum_2_string (_flags));
1396         }
1397
1398         node->add_property("active", _active?"yes":"no");
1399         node->add_property("phase-invert", _phase_invert?"yes":"no");
1400         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1401         node->add_property("meter-point", enum_2_string (_meter_point));
1402
1403         if (_edit_group) {
1404                 node->add_property("edit-group", _edit_group->name());
1405         }
1406         if (_mix_group) {
1407                 node->add_property("mix-group", _mix_group->name());
1408         }
1409
1410         string order_string;
1411         OrderKeys::iterator x = order_keys.begin(); 
1412
1413         while (x != order_keys.end()) {
1414                 order_string += string ((*x).first);
1415                 order_string += '=';
1416                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1417                 order_string += buf;
1418                 
1419                 ++x;
1420
1421                 if (x == order_keys.end()) {
1422                         break;
1423                 }
1424
1425                 order_string += ':';
1426         }
1427         node->add_property ("order-keys", order_string);
1428
1429         node->add_child_nocopy (_input->state (full_state));
1430         node->add_child_nocopy (_output->state (full_state));
1431         node->add_child_nocopy (_solo_control->get_state ());
1432         node->add_child_nocopy (_mute_master->get_state ());
1433
1434         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1435         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1436         remote_control_node->add_property (X_("id"), buf);
1437         node->add_child_nocopy (*remote_control_node);
1438
1439         if (_comment.length()) {
1440                 XMLNode *cmt = node->add_child ("Comment");
1441                 cmt->add_content (_comment);
1442         }
1443
1444         for (i = _processors.begin(); i != _processors.end(); ++i) {
1445                 node->add_child_nocopy((*i)->state (full_state));
1446         }
1447
1448         if (_extra_xml){
1449                 node->add_child_copy (*_extra_xml);
1450         }
1451         
1452         return *node;
1453 }
1454
1455 int
1456 Route::set_state (const XMLNode& node)
1457 {
1458         return _set_state (node, true);
1459 }
1460
1461 int
1462 Route::_set_state (const XMLNode& node, bool call_base)
1463 {
1464
1465         XMLNodeList nlist;
1466         XMLNodeConstIterator niter;
1467         XMLNode *child;
1468         XMLPropertyList plist;
1469         const XMLProperty *prop;
1470
1471         if (node.name() != "Route"){
1472                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1473                 return -1;
1474         }
1475
1476         if ((prop = node.property (X_("name"))) != 0) {
1477                 Route::set_name (prop->value());
1478         } 
1479
1480         if ((prop = node.property (X_("flags"))) != 0) {
1481                 _flags = Flag (string_2_enum (prop->value(), _flags));
1482         } else {
1483                 _flags = Flag (0);
1484         }
1485         
1486         if ((prop = node.property (X_("phase-invert"))) != 0) {
1487                 set_phase_invert (prop->value()=="yes"?true:false);
1488         }
1489
1490         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1491                 set_denormal_protection (prop->value()=="yes"?true:false);
1492         }
1493         
1494         if ((prop = node.property (X_("active"))) != 0) {
1495                 bool yn = (prop->value() == "yes");
1496                 _active = !yn; // force switch
1497                 set_active (yn);
1498         }
1499
1500         if ((prop = node.property (X_("soloed"))) != 0) {
1501                 bool yn = (prop->value()=="yes");
1502
1503                 /* XXX force reset of solo status */
1504
1505                 set_solo (yn, this);
1506         }
1507
1508         if ((prop = node.property (X_("meter-point"))) != 0) {
1509                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1510         }
1511         
1512         if ((prop = node.property (X_("edit-group"))) != 0) {
1513                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1514                 if(edit_group == 0) {
1515                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1516                 } else {
1517                         set_edit_group(edit_group, this);
1518                 }
1519         }
1520
1521         if ((prop = node.property (X_("order-keys"))) != 0) {
1522
1523                 long n;
1524
1525                 string::size_type colon, equal;
1526                 string remaining = prop->value();
1527
1528                 while (remaining.length()) {
1529
1530                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1531                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1532                                       << endmsg;
1533                         } else {
1534                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1535                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1536                                               << endmsg;
1537                                 } else {
1538                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1539                                 }
1540                         }
1541
1542                         colon = remaining.find_first_of (':');
1543
1544                         if (colon != string::npos) {
1545                                 remaining = remaining.substr (colon+1);
1546                         } else {
1547                                 break;
1548                         }
1549                 }
1550         }
1551
1552         nlist = node.children();
1553         XMLNode processor_state (X_("processor_state"));
1554
1555         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1556                 
1557                 child = *niter;
1558
1559                 if (child->name() == IO::state_node_name) {
1560                         if ((prop = child->property (X_("direction"))) == 0) {
1561                                 continue;
1562                         }
1563                         
1564                         if (prop->value() == "Input") {
1565                                 _input->set_state (*child);
1566                         } else if (prop->value() == "Output") {
1567                                 _output->set_state (*child);
1568                         }
1569                 }
1570                         
1571                 if (child->name() == X_("Processor")) {
1572                         processor_state.add_child_copy (*child);
1573                 }
1574         }
1575
1576         set_processor_state (processor_state);
1577         
1578         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1579                 child = *niter;
1580
1581                 if (child->name() == X_("Comment")) {
1582
1583                         /* XXX this is a terrible API design in libxml++ */
1584
1585                         XMLNode *cmt = *(child->children().begin());
1586                         _comment = cmt->content();
1587
1588                 } else if (child->name() == X_("Extra")) {
1589
1590                         _extra_xml = new XMLNode (*child);
1591
1592                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1593                         
1594                         if (prop->value() == "solo") {
1595                                 _solo_control->set_state (*child);
1596                                 _session.add_controllable (_solo_control);
1597                         } 
1598
1599                 } else if (child->name() == X_("RemoteControl")) {
1600                         if ((prop = child->property (X_("id"))) != 0) {
1601                                 int32_t x;
1602                                 sscanf (prop->value().c_str(), "%d", &x);
1603                                 set_remote_control_id (x);
1604                         }
1605
1606                 } else if (child->name() == X_("MuteMaster")) {
1607                         _mute_master->set_state (*child);
1608                 }
1609         }
1610
1611         if ((prop = node.property (X_("mix-group"))) != 0) {
1612                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1613                 if (mix_group == 0) {
1614                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1615                 }  else {
1616                         set_mix_group(mix_group, this);
1617                 }
1618         }
1619
1620         return 0;
1621 }
1622
1623 XMLNode&
1624 Route::get_processor_state ()
1625 {
1626         XMLNode* root = new XMLNode (X_("redirects"));
1627         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1628                 root->add_child_nocopy ((*i)->state (true));
1629         }
1630
1631         return *root;
1632 }
1633
1634 void
1635 Route::set_processor_state (const XMLNode& node)
1636 {
1637         const XMLNodeList &nlist = node.children();
1638         XMLNodeConstIterator niter;
1639         bool has_meter_processor = false; // legacy sessions don't
1640         ProcessorList::iterator i, o;
1641
1642         cerr << _name << " _set_processor_states\n";
1643
1644         // Iterate through existing processors, remove those which are not in the state list
1645         for (i = _processors.begin(); i != _processors.end(); ) {
1646                 ProcessorList::iterator tmp = i;
1647                 ++tmp;
1648
1649                 bool processorInStateList = false;
1650         
1651                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1652
1653                         XMLProperty* id_prop = (*niter)->property(X_("id"));
1654                         if (id_prop && (*i)->id() == id_prop->value()) {
1655                                 processorInStateList = true;
1656                                 break;
1657                         }
1658                 }
1659                 
1660                 if (!processorInStateList) {
1661                         remove_processor (*i);
1662                 }
1663
1664                 i = tmp;
1665         }
1666
1667         // Iterate through state list and make sure all processors are on the track and in the correct order,
1668         // set the state of existing processors according to the new state on the same go
1669         i = _processors.begin();
1670
1671         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
1672                 
1673                 XMLProperty* prop = (*niter)->property ("type");
1674
1675                 if (prop && prop->value() == "meter")  {
1676                         has_meter_processor = true;
1677                 }
1678
1679                 o = i;
1680
1681                 if (prop->value() != "meter" && prop->value() != "amp" && prop->value() != "main-outs") {
1682
1683                         // Check whether the next processor in the list 
1684                         
1685                         while (o != _processors.end()) {
1686                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
1687                                 if (id_prop && (*o)->id() == id_prop->value()) {
1688                                         break;
1689                                 }
1690                                 
1691                                 ++o;
1692                         }
1693                 }
1694
1695                 // If the processor (*niter) is not on the route,
1696                 // create it and move it to the correct location
1697                 if (o == _processors.end()) {
1698
1699                         if (add_processor_from_xml (**niter, i)) {
1700                                 --i; // move iterator to the newly inserted processor
1701                         } else {
1702                                 cerr << "Error restoring route: unable to restore processor" << endl;
1703                         }
1704
1705                 // Otherwise, the processor already exists; just
1706                 // ensure it is at the location provided in the XML state
1707                 } else {
1708
1709                         if (i != o) {
1710                                 boost::shared_ptr<Processor> tmp = (*o);
1711                                 _processors.erase (o); // remove the old copy
1712                                 _processors.insert (i, tmp); // insert the processor at the correct location
1713                                 --i; // move iterator to the correct processor
1714                         }
1715
1716                         (*i)->set_state (**niter);
1717                 }
1718         }
1719
1720         /* note: there is no configure_processors() call because we figure that
1721            the XML state represents a working signal route.
1722         */
1723
1724         if (!has_meter_processor) {
1725                 set_meter_point (_meter_point, NULL);
1726         }
1727
1728         processors_changed ();
1729 }
1730
1731 void
1732 Route::curve_reallocate ()
1733 {
1734 //      _gain_automation_curve.finish_resize ();
1735 //      _pan_automation_curve.finish_resize ();
1736 }
1737
1738 void
1739 Route::silence (nframes_t nframes)
1740 {
1741         if (!_silent) {
1742
1743                 _output->silence (nframes);
1744                 
1745                 { 
1746                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
1747                         
1748                         if (lm.locked()) {
1749                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1750                                         boost::shared_ptr<PluginInsert> pi;
1751
1752                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1753                                                 // skip plugins, they don't need anything when we're not active
1754                                                 continue;
1755                                         }
1756                                         
1757                                         (*i)->silence (nframes);
1758                                 }
1759
1760                                 if (nframes == _session.get_block_size()) {
1761                                         // _silent = true;
1762                                 }
1763                         }
1764                 }
1765                 
1766         }
1767 }       
1768
1769 boost::shared_ptr<Delivery>
1770 Route::add_listener (boost::shared_ptr<IO> io, const string& listen_name)
1771 {
1772         string name = _name;
1773         name += '[';
1774         name += listen_name;
1775         name += ']';
1776         
1777         boost::shared_ptr<Delivery> listener (new Delivery (_session, _mute_master, name, Delivery::Listen)); 
1778
1779         /* As an IO, our control outs need as many IO outputs as we have outputs
1780          *   (we track the changes in ::output_change_handler()).
1781          * As a processor, the listener is an identity processor
1782          *   (i.e. it does not modify its input buffers whatsoever)
1783          */
1784
1785         if (listener->output()->ensure_io (n_outputs(), true, this)) {
1786                 return boost::shared_ptr<Delivery>();
1787         }
1788         
1789         add_processor (listener, PostFader);
1790
1791         return listener;
1792 }
1793
1794 int
1795 Route::listen_via (boost::shared_ptr<IO> io, const string& listen_name)
1796 {
1797         vector<string> ports;
1798         vector<string>::const_iterator i;
1799
1800         {
1801                 Glib::RWLock::ReaderLock rm (_processor_lock);
1802                 
1803                 for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
1804                         boost::shared_ptr<const Delivery> d = boost::dynamic_pointer_cast<const Delivery>(*x);
1805
1806                         if (d && d->output() == io) {
1807                                 /* already listening via the specified IO: do nothing */
1808                                 return 0;
1809                         }
1810                 }
1811         }
1812
1813         uint32_t ni = io->n_ports().n_total();
1814
1815         for (uint32_t n = 0; n < ni; ++n) {
1816                 ports.push_back (io->nth (n)->name());
1817         }
1818
1819         if (ports.empty()) {
1820                 return 0;
1821         }
1822         
1823         boost::shared_ptr<Delivery> listen_point = add_listener (io, listen_name);
1824         
1825         /* XXX hack for now .... until we can generalize listen points */
1826
1827         _control_outs = listen_point;
1828
1829         /* now connect to the named ports */
1830         
1831         ni = listen_point->output()->n_ports().n_total();
1832         size_t psize = ports.size();
1833
1834         for (size_t n = 0; n < ni; ++n) {
1835                 if (listen_point->output()->connect (listen_point->output()->nth (n), ports[n % psize], this)) {
1836                         error << string_compose (_("could not connect %1 to %2"),
1837                                                  listen_point->output()->nth (n)->name(), ports[n % psize]) << endmsg;
1838                         return -1;
1839                 }
1840         }
1841
1842         
1843         return 0;
1844 }       
1845
1846 void
1847 Route::drop_listen (boost::shared_ptr<IO> io)
1848 {
1849         ProcessorStreams err;
1850         ProcessorList::iterator tmp;
1851
1852         Glib::RWLock::ReaderLock rm (_processor_lock);
1853         
1854         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
1855                 
1856                 tmp = x;
1857                 ++tmp;
1858                 
1859                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*x);
1860                 
1861                 if (d && d->output() == io) {
1862                         /* already listening via the specified IO: do nothing */
1863                         remove_processor (*x, &err);
1864                         
1865                 } 
1866                 
1867                 x = tmp;
1868         }
1869 }
1870
1871 void
1872 Route::set_edit_group (RouteGroup *eg, void *src)
1873
1874 {
1875         if (eg == _edit_group) {
1876                 return;
1877         }
1878
1879         if (_edit_group) {
1880                 _edit_group->remove (this);
1881         }
1882
1883         if ((_edit_group = eg) != 0) {
1884                 _edit_group->add (this);
1885         }
1886
1887         _session.set_dirty ();
1888         edit_group_changed (src); /* EMIT SIGNAL */
1889 }
1890
1891 void
1892 Route::drop_edit_group (void *src)
1893 {
1894         _edit_group = 0;
1895         _session.set_dirty ();
1896         edit_group_changed (src); /* EMIT SIGNAL */
1897 }
1898
1899 void
1900 Route::set_mix_group (RouteGroup *mg, void *src)
1901
1902 {
1903         if (mg == _mix_group) {
1904                 return;
1905         }
1906
1907         if (_mix_group) {
1908                 _mix_group->remove (this);
1909         }
1910
1911         if ((_mix_group = mg) != 0) {
1912                 _mix_group->add (this);
1913         }
1914
1915         _session.set_dirty ();
1916         mix_group_changed (src); /* EMIT SIGNAL */
1917 }
1918
1919 void
1920 Route::drop_mix_group (void *src)
1921 {
1922         _mix_group = 0;
1923         _session.set_dirty ();
1924         mix_group_changed (src); /* EMIT SIGNAL */
1925 }
1926
1927 void
1928 Route::set_comment (string cmt, void *src)
1929 {
1930         _comment = cmt;
1931         comment_changed (src);
1932         _session.set_dirty ();
1933 }
1934
1935 bool
1936 Route::feeds (boost::shared_ptr<IO> other)
1937 {
1938         if (_output->connected_to (other)) {
1939                 return true;
1940         }
1941
1942         /* check IOProcessors which may also interconnect Routes */
1943
1944         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
1945
1946                 boost::shared_ptr<IOProcessor> iop;
1947                 
1948                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
1949                         if (iop->output() && iop->output()->connected_to (other)) {
1950                                 return true;
1951                         }
1952                 }
1953         }
1954
1955         return false;
1956 }
1957
1958 void
1959 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
1960 {
1961         nframes_t now = _session.transport_frame();
1962
1963         {
1964                 Glib::RWLock::ReaderLock lm (_processor_lock);
1965
1966                 if (!did_locate) {
1967                         automation_snapshot (now, true);
1968                 }
1969
1970                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1971                         
1972                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
1973                                 (*i)->deactivate ();
1974                                 (*i)->activate ();
1975                         }
1976                         
1977                         (*i)->transport_stopped (now);
1978                 }
1979         }
1980
1981         _roll_delay = _initial_delay;
1982 }
1983
1984 void
1985 Route::input_change_handler (IOChange change, void *src)
1986 {
1987         if ((change & ConfigurationChanged)) {
1988                 configure_processors (0);
1989         }
1990 }
1991
1992 void
1993 Route::output_change_handler (IOChange change, void *src)
1994 {
1995         if ((change & ConfigurationChanged)) {
1996                 
1997                 /* XXX resize all listeners to match _main_outs? */
1998                 
1999                 // configure_processors (0);
2000         }
2001 }
2002
2003 uint32_t
2004 Route::pans_required () const
2005 {
2006         if (n_outputs().n_audio() < 2) {
2007                 return 0;
2008         }
2009         
2010         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2011 }
2012
2013 int 
2014 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,  
2015                 bool session_state_changing, bool can_record, bool rec_monitors_input)
2016 {
2017         if (n_outputs().n_total() == 0) {
2018                 return 0;
2019         }
2020
2021         if (session_state_changing || !_active || n_inputs() == ChanCount::ZERO)  {
2022                 silence (nframes);
2023                 return 0;
2024         }
2025
2026         _amp->apply_gain_automation (false);
2027         passthru (start_frame, end_frame, nframes, 0);
2028
2029         return 0;
2030 }
2031
2032 nframes_t
2033 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2034 {
2035         if (_roll_delay > nframes) {
2036
2037                 _roll_delay -= nframes;
2038                 silence (nframes);
2039                 /* transport frame is not legal for caller to use */
2040                 return 0;
2041
2042         } else if (_roll_delay > 0) {
2043
2044                 nframes -= _roll_delay;
2045                 silence (_roll_delay);
2046                 /* we've written _roll_delay of samples into the 
2047                    output ports, so make a note of that for
2048                    future reference.
2049                 */
2050                 _main_outs->increment_output_offset (_roll_delay);
2051                 transport_frame += _roll_delay;
2052
2053                 _roll_delay = 0;
2054         }
2055
2056         return nframes;
2057 }
2058
2059 int
2060 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2061              bool can_record, bool rec_monitors_input)
2062 {
2063         {
2064                 // automation snapshot can also be called from the non-rt context
2065                 // and it uses the processor list, so we try to acquire the lock here
2066                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2067
2068                 if (lm.locked()) {
2069                         automation_snapshot (_session.transport_frame(), false);
2070                 }
2071         }
2072
2073         if (n_outputs().n_total() == 0) {
2074                 return 0;
2075         }
2076
2077         if (!_active || n_inputs().n_total() == 0) {
2078                 silence (nframes);
2079                 return 0;
2080         }
2081         
2082         nframes_t unused = 0;
2083
2084         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2085                 return 0;
2086         }
2087
2088         _silent = false;
2089
2090         passthru (start_frame, end_frame, nframes, declick);
2091
2092         return 0;
2093 }
2094
2095 int
2096 Route::silent_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, 
2097                     bool can_record, bool rec_monitors_input)
2098 {
2099         silence (nframes);
2100         return 0;
2101 }
2102
2103 void
2104 Route::toggle_monitor_input ()
2105 {
2106         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2107                 i->ensure_monitor_input( ! i->monitoring_input());
2108         }
2109 }
2110
2111 bool
2112 Route::has_external_redirects () const
2113 {
2114         // FIXME: what about sends? - they don't return a signal back to ardour?
2115
2116         boost::shared_ptr<const PortInsert> pi;
2117         
2118         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2119
2120                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2121
2122                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2123                                 
2124                                 string port_name = port->name();
2125                                 string client_name = port_name.substr (0, port_name.find(':'));
2126
2127                                 /* only say "yes" if the redirect is actually in use */
2128                                 
2129                                 if (client_name != "ardour" && pi->active()) {
2130                                         return true;
2131                                 }
2132                         }
2133                 }
2134         }
2135
2136         return false;
2137 }
2138
2139 void
2140 Route::flush_processors ()
2141 {
2142         /* XXX shouldn't really try to take this lock, since
2143            this is called from the RT audio thread.
2144         */
2145
2146         Glib::RWLock::ReaderLock lm (_processor_lock);
2147
2148         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2149                 (*i)->deactivate ();
2150                 (*i)->activate ();
2151         }
2152 }
2153
2154 void
2155 Route::set_meter_point (MeterPoint p, void *src)
2156 {
2157         if (_meter_point != p) {
2158                 _meter_point = p;
2159
2160                 // Move meter in the processors list
2161                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _meter);
2162                 _processors.erase(loc);
2163                 switch (p) {
2164                 case MeterInput:
2165                         loc = _processors.begin();
2166                         break;
2167                 case MeterPreFader:
2168                         loc = find(_processors.begin(), _processors.end(), _amp);
2169                         break;
2170                 case MeterPostFader:
2171                         loc = _processors.end();
2172                         break;
2173                 }
2174                 _processors.insert(loc, _meter);
2175                 
2176                  meter_change (src); /* EMIT SIGNAL */
2177                 processors_changed (); /* EMIT SIGNAL */
2178                 _session.set_dirty ();
2179         }
2180 }
2181
2182 nframes_t
2183 Route::update_total_latency ()
2184 {
2185         nframes_t old = _output->effective_latency();
2186         nframes_t own_latency = _output->user_latency();
2187
2188         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2189                 if ((*i)->active ()) {
2190                         own_latency += (*i)->signal_latency ();
2191                 }
2192         }
2193
2194 #undef DEBUG_LATENCY
2195 #ifdef DEBUG_LATENCY
2196         cerr << _name << ": internal redirect latency = " << own_latency << endl;
2197 #endif
2198
2199         _output->set_port_latency (own_latency);
2200         
2201         if (_output->user_latency() == 0) {
2202
2203                 /* this (virtual) function is used for pure Routes,
2204                    not derived classes like AudioTrack.  this means
2205                    that the data processed here comes from an input
2206                    port, not prerecorded material, and therefore we
2207                    have to take into account any input latency.
2208                 */
2209                 
2210                 own_latency += _input->signal_latency ();
2211         }
2212
2213         if (old != own_latency) {
2214                 _output->set_latency_delay (own_latency);
2215                 signal_latency_changed (); /* EMIT SIGNAL */
2216         }
2217         
2218 #ifdef DEBUG_LATENCY
2219         cerr << _name << ": input latency = " << _input->signal_latency() << " total = "
2220              << own_latency << endl;
2221 #endif
2222
2223         return _output->effective_latency ();
2224 }
2225
2226 void
2227 Route::set_user_latency (nframes_t nframes)
2228 {
2229         _output->set_user_latency (nframes);
2230         _session.update_latency_compensation (false, false);
2231 }
2232
2233 void
2234 Route::set_latency_delay (nframes_t longest_session_latency)
2235 {
2236         nframes_t old = _initial_delay;
2237
2238         if (_output->effective_latency() < longest_session_latency) {
2239                 _initial_delay = longest_session_latency - _output->effective_latency();
2240         } else {
2241                 _initial_delay = 0;
2242         }
2243
2244         if (_initial_delay != old) {
2245                 initial_delay_changed (); /* EMIT SIGNAL */
2246         }
2247
2248         if (_session.transport_stopped()) {
2249                 _roll_delay = _initial_delay;
2250         }
2251 }
2252
2253 void
2254 Route::automation_snapshot (nframes_t now, bool force)
2255 {
2256         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2257                 (*i)->automation_snapshot (now, force);
2258         }
2259 }
2260
2261 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2262         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation), 
2263                              boost::shared_ptr<AutomationList>(), name)
2264         , route (r)
2265 {
2266         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2267         set_list (gl);
2268 }
2269
2270 void
2271 Route::SoloControllable::set_value (float val)
2272 {
2273         bool bval = ((val >= 0.5f) ? true: false);
2274         
2275         route.set_solo (bval, this);
2276 }
2277
2278 float
2279 Route::SoloControllable::get_value (void) const
2280 {
2281         return route.soloed() ? 1.0f : 0.0f;
2282 }
2283
2284 void 
2285 Route::set_block_size (nframes_t nframes)
2286 {
2287         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2288                 (*i)->set_block_size (nframes);
2289         }
2290         _session.ensure_buffers(processor_max_streams);
2291 }
2292
2293 void
2294 Route::protect_automation ()
2295 {
2296         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2297                 (*i)->protect_automation();
2298 }
2299
2300 void
2301 Route::set_pending_declick (int declick)
2302 {
2303         if (_declickable) {
2304                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2305                 if (declick) {
2306                         _pending_declick = declick;
2307                 }
2308                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2309         } else {
2310                 _pending_declick = 0;
2311         }
2312
2313 }
2314
2315 /** Shift automation forwards from a particular place, thereby inserting time.
2316  *  Adds undo commands for any shifts that are performed.
2317  *
2318  * @param pos Position to start shifting from.
2319  * @param frames Amount to shift forwards by.
2320  */
2321
2322 void
2323 Route::shift (nframes64_t pos, nframes64_t frames)
2324 {
2325 #ifdef THIS_NEEDS_FIXING_FOR_V3
2326
2327         /* gain automation */
2328         XMLNode &before = _gain_control->get_state ();
2329         _gain_control->shift (pos, frames);
2330         XMLNode &after = _gain_control->get_state ();
2331         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2332
2333         /* pan automation */
2334         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2335                 Curve & c = (*i)->automation ();
2336                 XMLNode &before = c.get_state ();
2337                 c.shift (pos, frames);
2338                 XMLNode &after = c.get_state ();
2339                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2340         }
2341
2342         /* redirect automation */
2343         {
2344                 Glib::RWLock::ReaderLock lm (redirect_lock);
2345                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2346                         
2347                         set<uint32_t> a;
2348                         (*i)->what_has_automation (a);
2349                         
2350                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2351                                 AutomationList & al = (*i)->automation_list (*j);
2352                                 XMLNode &before = al.get_state ();
2353                                 al.shift (pos, frames);
2354                                 XMLNode &after = al.get_state ();
2355                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2356                         }
2357                 }
2358         }
2359 #endif
2360
2361 }
2362
2363
2364 int
2365 Route::save_as_template (const string& path, const string& name)
2366 {
2367         XMLNode& node (state (false));
2368         XMLTree tree;
2369         
2370         IO::set_name_in_state (*node.children().front(), name);
2371         
2372         tree.set_root (&node);
2373         return tree.write (path.c_str());
2374 }
2375
2376
2377 bool
2378 Route::set_name (const string& str)
2379 {
2380         bool ret;
2381         string ioproc_name;
2382         
2383         SessionObject::set_name (str);
2384         
2385         ret = (_input->set_name(str) && _output->set_name(str));
2386
2387         if (ret) {
2388                 
2389                 Glib::RWLock::ReaderLock lm (_processor_lock);
2390                 
2391                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2392                         
2393                         /* rename all processors with outputs to reflect our new name */
2394
2395                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
2396
2397                         if (iop) {
2398                                 string iop_name = str;
2399                                 iop_name += '[';
2400                                 iop_name += "XXX FIX ME XXX";
2401                                 iop_name += ']';
2402                                 
2403                                 if (!iop->set_name (iop_name)) {
2404                                         ret = false;
2405                                 }
2406                         }
2407                 }
2408
2409         }
2410
2411         return ret;
2412 }
2413
2414 boost::shared_ptr<Send>
2415 Route::send_for (boost::shared_ptr<const IO> target) const
2416 {
2417         Glib::RWLock::ReaderLock lm (_processor_lock);
2418
2419         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2420                 boost::shared_ptr<Send> send;
2421                 
2422                 if ((send = boost::dynamic_pointer_cast<Send>(*i)) != 0) {
2423                         if (send->output()->connected_to (target)) {
2424                                 return send;
2425                         }
2426                 }
2427         }
2428         
2429         return boost::shared_ptr<Send>();
2430 }
2431
2432 void
2433 Route::set_phase_invert (bool yn)
2434 {
2435         if (_phase_invert != yn) {
2436                 _phase_invert = 0xffff; // XXX all channels
2437                 phase_invert_changed (); /* EMIT SIGNAL */
2438         }
2439 }
2440
2441 bool
2442 Route::phase_invert () const
2443 {
2444         return _phase_invert != 0;
2445 }
2446
2447 void
2448 Route::set_denormal_protection (bool yn)
2449 {
2450         if (_denormal_protection != yn) {
2451                 _denormal_protection = yn;
2452                 denormal_protection_changed (); /* EMIT SIGNAL */
2453         }
2454 }
2455
2456 bool
2457 Route::denormal_protection () const
2458 {
2459         return _denormal_protection;
2460 }
2461
2462 void
2463 Route::set_active (bool yn)
2464 {
2465         if (_active != yn) {
2466                 _active = yn;
2467                 _input->set_active (yn);
2468                 _output->set_active (yn);
2469                 active_changed (); // EMIT SIGNAL
2470         }
2471 }
2472
2473 void
2474 Route::meter ()
2475 {
2476         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
2477         _meter->meter ();
2478 }
2479
2480 boost::shared_ptr<Panner>
2481 Route::panner() const
2482 {
2483
2484         return _main_outs->panner();
2485 }
2486
2487 boost::shared_ptr<AutomationControl>
2488 Route::gain_control() const
2489 {
2490
2491         return _amp->gain_control();
2492 }
2493
2494 boost::shared_ptr<AutomationControl>
2495 Route::get_control (const Evoral::Parameter& param)
2496 {
2497         /* either we own the control or .... */
2498
2499         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(data().control (param));
2500
2501         if (!c) {
2502
2503                 /* maybe one of our processors does or ... */
2504                 
2505                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
2506                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2507                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->data().control (param))) != 0) {
2508                                 break;
2509                         }
2510                 }
2511         }
2512                 
2513         if (!c) {
2514
2515                 /* nobody does so we'll make a new one */
2516
2517                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
2518                 add_control(c);
2519         }
2520
2521         return c;
2522 }