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