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