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