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