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