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