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