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