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