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