merge with 2.0-ongoing @ rev 3147
[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
24 #include <sigc++/bind.h>
25 #include <pbd/xml++.h>
26 #include <pbd/enumwriter.h>
27
28 #include <ardour/timestamps.h>
29 #include <ardour/audioengine.h>
30 #include <ardour/route.h>
31 #include <ardour/buffer.h>
32 #include <ardour/processor.h>
33 #include <ardour/plugin_insert.h>
34 #include <ardour/port_insert.h>
35 #include <ardour/send.h>
36 #include <ardour/session.h>
37 #include <ardour/utils.h>
38 #include <ardour/configuration.h>
39 #include <ardour/cycle_timer.h>
40 #include <ardour/route_group.h>
41 #include <ardour/port.h>
42 #include <ardour/audio_port.h>
43 #include <ardour/ladspa_plugin.h>
44 #include <ardour/panner.h>
45 #include <ardour/dB.h>
46 #include <ardour/amp.h>
47 #include <ardour/meter.h>
48 #include <ardour/buffer_set.h>
49 #include <ardour/mix.h>
50 #include <ardour/profile.h>
51
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 uint32_t Route::order_key_cnt = 0;
59 sigc::signal<void> Route::SyncOrderKeys;
60
61 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, DataType default_type)
62         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
63           _flags (flg),
64           _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl)),
65           _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
66 {
67         init ();
68 }
69
70 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
71         : IO (sess, *node.child ("IO"), default_type),
72           _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl)),
73           _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
74 {
75         init ();
76         _set_state (node, false);
77 }
78
79 void
80 Route::init ()
81 {
82         processor_max_outs.reset();
83         _muted = false;
84         _soloed = false;
85         _solo_safe = false;
86         _recordable = true;
87         _active = true;
88         _phase_invert = false;
89         _denormal_protection = false;
90         order_keys[strdup (N_("signal"))] = order_key_cnt++;
91         _silent = false;
92         _meter_point = MeterPostFader;
93         _initial_delay = 0;
94         _roll_delay = 0;
95         _own_latency = 0;
96         _user_latency = 0;
97         _have_internal_generator = false;
98         _declickable = false;
99         _pending_declick = true;
100         _remote_control_id = 0;
101         
102         _edit_group = 0;
103         _mix_group = 0;
104
105         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
106         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
107         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
108         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
109         
110         solo_gain = 1.0;
111         desired_solo_gain = 1.0;
112         mute_gain = 1.0;
113         desired_mute_gain = 1.0;
114
115         _control_outs = 0;
116
117         input_changed.connect (mem_fun (this, &Route::input_change_handler));
118         output_changed.connect (mem_fun (this, &Route::output_change_handler));
119 }
120
121 Route::~Route ()
122 {
123         clear_processors (PreFader);
124         clear_processors (PostFader);
125
126         for (OrderKeys::iterator i = order_keys.begin(); i != order_keys.end(); ++i) {
127                 free ((void*)(i->first));
128         }
129
130         if (_control_outs) {
131                 delete _control_outs;
132         }
133 }
134
135 void
136 Route::set_remote_control_id (uint32_t id)
137 {
138         if (id != _remote_control_id) {
139                 _remote_control_id = id;
140                 RemoteControlIDChanged ();
141         }
142 }
143
144 uint32_t
145 Route::remote_control_id() const
146 {
147         return _remote_control_id;
148 }
149
150 long
151 Route::order_key (const char* name) const
152 {
153         OrderKeys::const_iterator i;
154         
155         for (i = order_keys.begin(); i != order_keys.end(); ++i) {
156                 if (!strcmp (name, i->first)) {
157                         return i->second;
158                 }
159         }
160
161         return -1;
162 }
163
164 void
165 Route::set_order_key (const char* name, long n)
166 {
167         order_keys[strdup(name)] = n;
168
169         if (Config->get_sync_all_route_ordering()) {
170                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
171                         x->second = n;
172                 }
173         } 
174
175         _session.set_dirty ();
176 }
177
178 void
179 Route::sync_order_keys ()
180 {
181         uint32_t key;
182         
183         if (order_keys.empty()) {
184                 return;
185         }
186         
187         OrderKeys::iterator x = order_keys.begin();
188         key = x->second;
189         ++x;
190
191         for (; x != order_keys.end(); ++x) {
192                 x->second = key;
193         }
194 }
195
196 string
197 Route::ensure_track_or_route_name(string name, Session &session)
198 {
199         string newname = name;
200
201         while (session.route_by_name (newname)!=NULL)
202         {
203                 newname = bump_name_once (newname);
204         }
205
206         return newname;
207 }
208
209
210 void
211 Route::inc_gain (gain_t fraction, void *src)
212 {
213         IO::inc_gain (fraction, src);
214 }
215
216 void
217 Route::set_gain (gain_t val, void *src)
218 {
219         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
220                 
221                 if (_mix_group->is_relative()) {
222                         
223                         gain_t usable_gain = gain();
224                         if (usable_gain < 0.000001f) {
225                                 usable_gain = 0.000001f;
226                         }
227                                                 
228                         gain_t delta = val;
229                         if (delta < 0.000001f) {
230                                 delta = 0.000001f;
231                         }
232
233                         delta -= usable_gain;
234
235                         if (delta == 0.0f)
236                                 return;
237
238                         gain_t factor = delta / usable_gain;
239
240                         if (factor > 0.0f) {
241                                 factor = _mix_group->get_max_factor(factor);
242                                 if (factor == 0.0f) {
243                                         _gain_control->Changed(); /* EMIT SIGNAL */
244                                         return;
245                                 }
246                         } else {
247                                 factor = _mix_group->get_min_factor(factor);
248                                 if (factor == 0.0f) {
249                                         _gain_control->Changed(); /* EMIT SIGNAL */
250                                         return;
251                                 }
252                         }
253                                         
254                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
255
256                 } else {
257                         
258                         _mix_group->apply (&Route::set_gain, val, _mix_group);
259                 }
260
261                 return;
262         } 
263
264         if (val == gain()) {
265                 return;
266         }
267
268         IO::set_gain (val, src);
269 }
270
271 /** Process this route for one (sub) cycle (process thread)
272  *
273  * @param bufs Scratch buffers to use for the signal path
274  * @param start_frame Initial transport frame 
275  * @param end_frame Final transport frame
276  * @param nframes Number of frames to output (to ports)
277  * @param offset Output offset (of port buffers, for split cycles)
278  *
279  * Note that (end_frame - start_frame) may not be equal to nframes when the
280  * transport speed isn't 1.0 (eg varispeed).
281  */
282 void
283 Route::process_output_buffers (BufferSet& bufs,
284                                nframes_t start_frame, nframes_t end_frame, 
285                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
286                                bool meter)
287 {
288         // This is definitely very audio-only for now
289         assert(_default_type == DataType::AUDIO);
290         
291         ProcessorList::iterator i;
292         bool post_fader_work = false;
293         bool mute_declick_applied = false;
294         gain_t dmg, dsg, dg;
295         IO *co;
296         bool mute_audible;
297         bool solo_audible;
298         bool no_monitor;
299         gain_t* gab = _session.gain_automation_buffer();
300
301         switch (Config->get_monitoring_model()) {
302         case HardwareMonitoring:
303         case ExternalMonitoring:
304                 no_monitor = true;
305                 break;
306         default:
307                 no_monitor = false;
308         }
309
310         declick = _pending_declick;
311
312         {
313                 Glib::Mutex::Lock cm (_control_outs_lock, Glib::TRY_LOCK);
314                 
315                 if (cm.locked()) {
316                         co = _control_outs;
317                 } else {
318                         co = 0;
319                 }
320         }
321         
322         { 
323                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
324                 
325                 if (dm.locked()) {
326                         dmg = desired_mute_gain;
327                         dsg = desired_solo_gain;
328                         dg = _desired_gain;
329                 } else {
330                         dmg = mute_gain;
331                         dsg = solo_gain;
332                         dg = _gain;
333                 }
334         }
335
336         /* ----------------------------------------------------------------------------------------------------
337            GLOBAL DECLICK (for transport changes etc.)
338            -------------------------------------------------------------------------------------------------- */
339
340         if (declick > 0) {
341                 Amp::run_in_place (bufs, nframes, 0.0, 1.0, false);
342                 _pending_declick = 0;
343         } else if (declick < 0) {
344                 Amp::run_in_place (bufs, nframes, 1.0, 0.0, false);
345                 _pending_declick = 0;
346         } else {
347
348                 /* no global declick */
349
350                 if (solo_gain != dsg) {
351                         Amp::run_in_place (bufs, nframes, solo_gain, dsg, false);
352                         solo_gain = dsg;
353                 }
354         }
355
356
357         /* ----------------------------------------------------------------------------------------------------
358            INPUT METERING & MONITORING
359            -------------------------------------------------------------------------------------------------- */
360
361         if (meter && (_meter_point == MeterInput)) {
362                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
363         }
364
365         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
366                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
367                 mute_gain = dmg;
368                 mute_declick_applied = true;
369         }
370
371         if ((_meter_point == MeterInput) && co) {
372                 
373                 solo_audible = dsg > 0;
374                 mute_audible = dmg > 0;// || !_mute_affects_pre_fader;
375                 
376                 if (    // muted by solo of another track
377                         
378                         !solo_audible || 
379                         
380                         // muted by mute of this track 
381                         
382                         !mute_audible ||
383                         
384                         // rec-enabled but not s/w monitoring 
385                         
386                         // TODO: this is probably wrong
387
388                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
389
390                         ) {
391                         
392                         co->silence (nframes, offset);
393                         
394                 } else {
395
396                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
397                         
398                 } 
399         } 
400
401         /* -----------------------------------------------------------------------------------------------------
402            DENORMAL CONTROL
403            -------------------------------------------------------------------------------------------------- */
404
405         if (_denormal_protection || Config->get_denormal_protection()) {
406
407                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
408                         Sample* const sp = i->data();
409                         
410                         for (nframes_t nx = offset; nx < nframes + offset; ++nx) {
411                                 sp[nx] += 1.0e-27f;
412                         }
413                 }
414         }
415
416         /* ----------------------------------------------------------------------------------------------------
417            PRE-FADER REDIRECTS
418            -------------------------------------------------------------------------------------------------- */
419
420         if (with_processors) {
421                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
422                 if (rm.locked()) {
423                         if (mute_gain > 0 || !_mute_affects_pre_fader) {
424                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
425                                         switch ((*i)->placement()) {
426                                         case PreFader:
427                                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
428                                                 break;
429                                         case PostFader:
430                                                 post_fader_work = true;
431                                                 break;
432                                         }
433                                 }
434                         } else {
435                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
436                                         switch ((*i)->placement()) {
437                                         case PreFader:
438                                                 (*i)->silence (nframes, offset);
439                                                 break;
440                                         case PostFader:
441                                                 post_fader_work = true;
442                                                 break;
443                                         }
444                                 }
445                         }
446                 } 
447         }
448
449         // This really should already be true...
450         bufs.set_count(pre_fader_streams());
451         
452         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader) {
453                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
454                 mute_gain = dmg;
455                 mute_declick_applied = true;
456         }
457
458         /* ----------------------------------------------------------------------------------------------------
459            PRE-FADER METERING & MONITORING
460            -------------------------------------------------------------------------------------------------- */
461
462         if (meter && (_meter_point == MeterPreFader)) {
463                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
464         }
465
466         
467         if ((_meter_point == MeterPreFader) && co) {
468                 
469                 solo_audible = dsg > 0;
470                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
471                 
472                 if ( // muted by solo of another track
473                         
474                         !solo_audible || 
475                         
476                         // muted by mute of this track 
477                         
478                         !mute_audible ||
479                         
480                         // rec-enabled but not s/w monitoring 
481                         
482                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
483
484                         ) {
485                         
486                         co->silence (nframes, offset);
487                         
488                 } else {
489
490                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
491                 } 
492         } 
493         
494         /* ----------------------------------------------------------------------------------------------------
495            GAIN STAGE
496            -------------------------------------------------------------------------------------------------- */
497
498         /* if not recording or recording and requiring any monitor signal, then apply gain */
499
500         if ( // not recording 
501
502                 !(record_enabled() && _session.actively_recording()) || 
503                 
504             // OR recording 
505                 
506                  // AND software monitoring required
507
508                 Config->get_monitoring_model() == SoftwareMonitoring) { 
509                 
510                 if (apply_gain_automation) {
511                         
512                         if (_phase_invert) {
513                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
514                                         Sample* const sp = i->data();
515                                         
516                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
517                                                 sp[nx] *= -gab[nx];
518                                         }
519                                 }
520                         } else {
521                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
522                                         Sample* const sp = i->data();
523                                         
524                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
525                                                 sp[nx] *= gab[nx];
526                                         }
527                                 }
528                         }
529                         
530                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
531                                 _effective_gain = gab[nframes-1];
532                         }
533                         
534                 } else {
535                         
536                         /* manual (scalar) gain */
537                         
538                         if (_gain != dg) {
539                                 
540                                 Amp::run_in_place (bufs, nframes, _gain, dg, _phase_invert);
541                                 _gain = dg;
542                                 
543                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
544                                 
545                                 /* no need to interpolate current gain value,
546                                    but its non-unity, so apply it. if the gain
547                                    is zero, do nothing because we'll ship silence
548                                    below.
549                                 */
550
551                                 gain_t this_gain;
552                                 
553                                 if (_phase_invert) {
554                                         this_gain = -_gain;
555                                 } else {
556                                         this_gain = _gain;
557                                 }
558                                 
559                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
560                                         Sample* const sp = i->data();
561                                         apply_gain_to_buffer(sp,nframes,this_gain);
562                                 }
563
564                         } else if (_gain == 0) {
565                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
566                                         i->clear();
567                                 }
568                         }
569                 }
570
571         } else {
572
573                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
574
575         }
576
577         /* ----------------------------------------------------------------------------------------------------
578            POST-FADER REDIRECTS
579            -------------------------------------------------------------------------------------------------- */
580
581         /* note that post_fader_work cannot be true unless with_processors was also true, so don't test both */
582
583         if (post_fader_work) {
584
585                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
586                 if (rm.locked()) {
587                         if (mute_gain > 0 || !_mute_affects_post_fader) {
588                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
589                                         switch ((*i)->placement()) {
590                                         case PreFader:
591                                                 break;
592                                         case PostFader:
593                                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
594                                                 break;
595                                         }
596                                 }
597                         } else {
598                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
599                                         switch ((*i)->placement()) {
600                                         case PreFader:
601                                                 break;
602                                         case PostFader:
603                                                 (*i)->silence (nframes, offset);
604                                                 break;
605                                         }
606                                 }
607                         }
608                 } 
609         }
610
611         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_control_outs) {
612                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
613                 mute_gain = dmg;
614                 mute_declick_applied = true;
615         }
616
617         /* ----------------------------------------------------------------------------------------------------
618            CONTROL OUTPUT STAGE
619            -------------------------------------------------------------------------------------------------- */
620
621         if ((_meter_point == MeterPostFader) && co) {
622                 
623                 solo_audible = solo_gain > 0;
624                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
625
626                 if ( // silent anyway
627
628                         (_gain == 0 && !apply_gain_automation) || 
629                     
630                      // muted by solo of another track
631
632                         !solo_audible || 
633                     
634                      // muted by mute of this track 
635
636                         !mute_audible ||
637
638                     // recording but not s/w monitoring 
639                         
640                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
641
642                         ) {
643                         
644                         co->silence (nframes, offset);
645                         
646                 } else {
647
648                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
649                 } 
650         } 
651
652         /* ----------------------------------------------------------------------
653            GLOBAL MUTE 
654            ----------------------------------------------------------------------*/
655
656         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
657                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
658                 mute_gain = dmg;
659                 mute_declick_applied = true;
660         }
661         
662         /* ----------------------------------------------------------------------------------------------------
663            MAIN OUTPUT STAGE
664            -------------------------------------------------------------------------------------------------- */
665
666         solo_audible = dsg > 0;
667         mute_audible = dmg > 0 || !_mute_affects_main_outs;
668         
669         if (n_outputs().get(_default_type) == 0) {
670             
671             /* relax */
672
673         } else if (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording())) {
674                 
675                 IO::silence (nframes, offset);
676                 
677         } else {
678
679                 if ( // silent anyway
680
681                     (_gain == 0 && !apply_gain_automation) ||
682                     
683                     // muted by solo of another track, but not using control outs for solo
684
685                     (!solo_audible && (Config->get_solo_model() != SoloBus)) ||
686                     
687                     // muted by mute of this track
688
689                     !mute_audible
690
691                         ) {
692
693                         /* don't use Route::silence() here, because that causes
694                            all outputs (sends, port processors, etc. to be silent).
695                         */
696                         
697                         if (_meter_point == MeterPostFader) {
698                                 peak_meter().reset();
699                         }
700
701                         IO::silence (nframes, offset);
702                         
703                 } else {
704                         
705                         deliver_output(bufs, start_frame, end_frame, nframes, offset);
706
707                 }
708
709         }
710
711         /* ----------------------------------------------------------------------------------------------------
712            POST-FADER METERING
713            -------------------------------------------------------------------------------------------------- */
714
715         if (meter && (_meter_point == MeterPostFader)) {
716                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
717                         _meter->reset();
718                 } else {
719                         _meter->run_in_place(output_buffers(), start_frame, end_frame, nframes, offset);
720                 }
721         }
722 }
723
724 ChanCount
725 Route::n_process_buffers ()
726 {
727         return max (n_inputs(), processor_max_outs);
728 }
729
730 void
731 Route::passthru (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter_first)
732 {
733         BufferSet& bufs = _session.get_scratch_buffers(n_process_buffers());
734
735         _silent = false;
736
737         collect_input (bufs, nframes, offset);
738
739         if (meter_first) {
740                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
741                 meter_first = false;
742         }
743                 
744         process_output_buffers (bufs, start_frame, end_frame, nframes, offset, true, declick, meter_first);
745 }
746
747 void
748 Route::passthru_silence (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter)
749 {
750         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, offset, true, declick, meter);
751 }
752
753 void
754 Route::set_solo (bool yn, void *src)
755 {
756         if (_solo_safe) {
757                 return;
758         }
759
760         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
761                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
762                 return;
763         }
764
765         if (_soloed != yn) {
766                 _soloed = yn;
767                 solo_changed (src); /* EMIT SIGNAL */
768                 _solo_control->Changed (); /* EMIT SIGNAL */
769         }
770 }
771
772 void
773 Route::set_solo_mute (bool yn)
774 {
775         Glib::Mutex::Lock lm (declick_lock);
776
777         /* Called by Session in response to another Route being soloed.
778          */
779            
780         desired_solo_gain = (yn?0.0:1.0);
781 }
782
783 void
784 Route::set_solo_safe (bool yn, void *src)
785 {
786         if (_solo_safe != yn) {
787                 _solo_safe = yn;
788                  solo_safe_changed (src); /* EMIT SIGNAL */
789         }
790 }
791
792 void
793 Route::set_mute (bool yn, void *src)
794
795 {
796         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
797                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
798                 return;
799         }
800
801         if (_muted != yn) {
802                 _muted = yn;
803                 mute_changed (src); /* EMIT SIGNAL */
804                 
805                 _mute_control->Changed (); /* EMIT SIGNAL */
806                 
807                 Glib::Mutex::Lock lm (declick_lock);
808                 desired_mute_gain = (yn?0.0f:1.0f);
809         }
810 }
811
812 int
813 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
814 {
815         ChanCount old_rmo = processor_max_outs;
816
817         if (!_session.engine().connected()) {
818                 return 1;
819         }
820
821         {
822                 Glib::RWLock::WriterLock lm (_processor_lock);
823
824                 boost::shared_ptr<PluginInsert> pi;
825                 boost::shared_ptr<PortInsert> porti;
826
827                 //processor->set_default_type(_default_type);
828
829                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
830                         pi->set_count (1);
831                         
832                         if (pi->natural_input_streams() == ChanCount::ZERO) {
833                                 /* generator plugin */
834                                 _have_internal_generator = true;
835                         }
836                         
837                 }
838                 
839                 _processors.push_back (processor);
840
841                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
842                 // configure redirect ports properly, etc.
843                 if (_reset_plugin_counts (err)) {
844                         _processors.pop_back ();
845                         _reset_plugin_counts (0); // it worked before we tried to add it ...
846                         return -1;
847                 }
848
849                 // Ensure peak vector sizes before the plugin is activated
850                 ChanCount potential_max_streams = max(processor->input_streams(), processor->output_streams());
851                 _meter->configure_io(potential_max_streams, potential_max_streams);
852
853                 processor->activate ();
854                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
855
856                 _user_latency = 0;
857         }
858         
859         if (processor_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
860                 reset_panner ();
861         }
862
863         processors_changed (); /* EMIT SIGNAL */
864         
865         return 0;
866 }
867
868 int
869 Route::add_processors (const ProcessorList& others, ProcessorStreams* err)
870 {
871         ChanCount old_rmo = processor_max_outs;
872
873         if (!_session.engine().connected()) {
874                 return 1;
875         }
876
877         {
878                 Glib::RWLock::WriterLock lm (_processor_lock);
879
880                 ProcessorList::iterator existing_end = _processors.end();
881                 --existing_end;
882
883                 ChanCount potential_max_streams;
884
885                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
886                         
887                         boost::shared_ptr<PluginInsert> pi;
888                         
889                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
890                                 pi->set_count (1);
891                                 
892                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
893                                 if (m > potential_max_streams)
894                                         potential_max_streams = m;
895                         }
896
897                         // Ensure peak vector sizes before the plugin is activated
898                         _meter->configure_io(potential_max_streams, potential_max_streams);
899
900                         _processors.push_back (*i);
901                         
902                         if (_reset_plugin_counts (err)) {
903                                 ++existing_end;
904                                 _processors.erase (existing_end, _processors.end());
905                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
906                                 return -1;
907                         }
908                         
909                         (*i)->activate ();
910                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
911                 }
912
913                 _user_latency = 0;
914         }
915         
916         if (processor_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
917                 reset_panner ();
918         }
919
920         processors_changed (); /* EMIT SIGNAL */
921         return 0;
922 }
923
924 /** Turn off all processors with a given placement
925  * @param p Placement of processors to disable
926  */
927
928 void
929 Route::disable_processors (Placement p)
930 {
931         Glib::RWLock::ReaderLock lm (_processor_lock);
932         
933         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
934                 if ((*i)->placement() == p) {
935                         (*i)->set_active (false);
936                 }
937         }
938
939         _session.set_dirty ();
940 }
941
942 /** Turn off all redirects 
943  */
944
945 void
946 Route::disable_processors ()
947 {
948         Glib::RWLock::ReaderLock lm (_processor_lock);
949         
950         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
951                 (*i)->set_active (false);
952         }
953         
954         _session.set_dirty ();
955 }
956
957 /** Turn off all redirects with a given placement
958  * @param p Placement of redirects to disable
959  */
960
961 void
962 Route::disable_plugins (Placement p)
963 {
964         Glib::RWLock::ReaderLock lm (_processor_lock);
965         
966         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
967                 if (boost::dynamic_pointer_cast<PluginInsert> (*i) && (*i)->placement() == p) {
968                         (*i)->set_active (false);
969                 }
970         }
971         
972         _session.set_dirty ();
973 }
974
975 /** Turn off all plugins
976  */
977
978 void
979 Route::disable_plugins ()
980 {
981         Glib::RWLock::ReaderLock lm (_processor_lock);
982         
983         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
984                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
985                         (*i)->set_active (false);
986                 }
987         }
988         
989         _session.set_dirty ();
990 }
991
992
993 void
994 Route::ab_plugins (bool forward)
995 {
996         Glib::RWLock::ReaderLock lm (_processor_lock);
997                         
998         if (forward) {
999
1000                 /* forward = turn off all active redirects, and mark them so that the next time
1001                    we go the other way, we will revert them
1002                 */
1003
1004                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1005                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1006                                 continue;
1007                         }
1008
1009                         if ((*i)->active()) {
1010                                 (*i)->set_active (false);
1011                                 (*i)->set_next_ab_is_active (true);
1012                         } else {
1013                                 (*i)->set_next_ab_is_active (false);
1014                         }
1015                 }
1016
1017         } else {
1018
1019                 /* backward = if the redirect was marked to go active on the next ab, do so */
1020
1021                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1022
1023                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1024                                 continue;
1025                         }
1026
1027                         if ((*i)->get_next_ab_is_active()) {
1028                                 (*i)->set_active (true);
1029                         } else {
1030                                 (*i)->set_active (false);
1031                         }
1032                 }
1033         }
1034         
1035         _session.set_dirty ();
1036 }
1037         
1038         
1039 /* Figure out the streams that will feed into PreFader */
1040 ChanCount
1041 Route::pre_fader_streams() const
1042 {
1043         boost::shared_ptr<Processor> processor;
1044
1045         // Find the last pre-fader redirect
1046         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1047                 if ((*i)->placement() == PreFader) {
1048                         processor = *i;
1049                 }
1050         }
1051         
1052         if (processor) {
1053                 return processor->output_streams();
1054         } else {
1055                 return n_inputs ();
1056         }
1057 }
1058
1059
1060 /** Remove processors with a given placement.
1061  * @param p Placement of processors to remove.
1062  */
1063 void
1064 Route::clear_processors (Placement p)
1065 {
1066         const ChanCount old_rmo = processor_max_outs;
1067
1068         if (!_session.engine().connected()) {
1069                 return;
1070         }
1071
1072         {
1073                 Glib::RWLock::WriterLock lm (_processor_lock);
1074                 ProcessorList new_list;
1075                 
1076                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1077                         if ((*i)->placement() == p) {
1078                                 /* it's the placement we want to get rid of */
1079                                 (*i)->drop_references ();
1080                         } else {
1081                                 /* it's a different placement, so keep it */
1082                                 new_list.push_back (*i);
1083                         }
1084                 }
1085                 
1086                 _processors = new_list;
1087         }
1088
1089         /* FIXME: can't see how this test can ever fire */
1090         if (processor_max_outs != old_rmo) {
1091                 reset_panner ();
1092         }
1093         
1094         processor_max_outs.reset();
1095         _have_internal_generator = false;
1096         processors_changed (); /* EMIT SIGNAL */
1097 }
1098
1099 int
1100 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1101 {
1102         ChanCount old_rmo = processor_max_outs;
1103
1104         if (!_session.engine().connected()) {
1105                 return 1;
1106         }
1107
1108         processor_max_outs.reset();
1109
1110         {
1111                 Glib::RWLock::WriterLock lm (_processor_lock);
1112                 ProcessorList::iterator i;
1113                 bool removed = false;
1114
1115                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1116                         if (*i == processor) {
1117
1118                                 ProcessorList::iterator tmp;
1119
1120                                 /* move along, see failure case for reset_plugin_counts()
1121                                    where we may need to reprocessor the processor.
1122                                 */
1123
1124                                 tmp = i;
1125                                 ++tmp;
1126
1127                                 /* stop redirects that send signals to JACK ports
1128                                    from causing noise as a result of no longer being
1129                                    run.
1130                                 */
1131
1132                                 boost::shared_ptr<IOProcessor> redirect;
1133                                 
1134                                 if ((redirect = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1135                                         redirect->io()->disconnect_inputs (this);
1136                                         redirect->io()->disconnect_outputs (this);
1137                                 }
1138
1139                                 _processors.erase (i);
1140
1141                                 i = tmp;
1142                                 removed = true;
1143                                 break;
1144                         }
1145
1146                         _user_latency = 0;
1147                 }
1148
1149                 if (!removed) {
1150                         /* what? */
1151                         return 1;
1152                 }
1153
1154                 if (_reset_plugin_counts (err)) {
1155                         /* get back to where we where */
1156                         _processors.insert (i, processor);
1157                         /* we know this will work, because it worked before :) */
1158                         _reset_plugin_counts (0);
1159                         return -1;
1160                 }
1161
1162                 bool foo = false;
1163
1164                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1165                         boost::shared_ptr<PluginInsert> pi;
1166                         
1167                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1168                                 if (pi->is_generator()) {
1169                                         foo = true;
1170                                 }
1171                         }
1172                 }
1173
1174                 _have_internal_generator = foo;
1175         }
1176
1177         if (old_rmo != processor_max_outs) {
1178                 reset_panner ();
1179         }
1180
1181         processor->drop_references ();
1182
1183         processors_changed (); /* EMIT SIGNAL */
1184         return 0;
1185 }
1186
1187 int
1188 Route::reset_plugin_counts (ProcessorStreams* err)
1189 {
1190         Glib::RWLock::WriterLock lm (_processor_lock);
1191         return _reset_plugin_counts (err);
1192 }
1193
1194
1195 int
1196 Route::_reset_plugin_counts (ProcessorStreams* err)
1197 {
1198         ProcessorList::iterator r;
1199         map<Placement,list<ProcessorCount> > processor_map;
1200         ChanCount initial_streams;
1201         ChanCount post_fader_input;
1202         int ret = -1;
1203
1204         /* Process each placement in order, checking to see if we 
1205            can really do what has been requested.
1206         */
1207         
1208         /* divide processors up by placement so we get the signal flow
1209            properly modelled. we need to do this because the _processors
1210            list is not sorted by placement, and because other reasons may 
1211            exist now or in the future for this separate treatment.
1212         */
1213
1214         /* ... but it should/will be... */
1215         
1216         for (r = _processors.begin(); r != _processors.end(); ++r) {
1217
1218                 boost::shared_ptr<Processor> processor;
1219
1220                 if ((processor = boost::dynamic_pointer_cast<Processor>(*r)) != 0) {
1221                         processor_map[processor->placement()].push_back (ProcessorCount (processor));
1222                 }
1223         }
1224         
1225         /* A: PreFader */
1226         
1227         if ( ! check_some_plugin_counts (processor_map[PreFader], n_inputs (), err)) {
1228                 goto streamcount;
1229         }
1230
1231         post_fader_input = (err ? err->count : n_inputs());
1232
1233         /* B: PostFader */
1234
1235         if ( ! check_some_plugin_counts (processor_map[PostFader], post_fader_input, err)) {
1236                 goto streamcount;
1237         }
1238
1239         /* OK, everything can be set up correctly, so lets do it */
1240
1241         apply_some_plugin_counts (processor_map[PreFader]);
1242         apply_some_plugin_counts (processor_map[PostFader]);
1243
1244         /* recompute max outs of any processor */
1245
1246         ret = 0;
1247
1248   streamcount:
1249         processor_max_outs.reset();
1250
1251         for (r = _processors.begin(); r != _processors.end(); ++r) {
1252                 processor_max_outs = max ((*r)->output_streams (), processor_max_outs);
1253         }
1254
1255         return 0;
1256 }                                  
1257
1258 int32_t
1259 Route::apply_some_plugin_counts (list<ProcessorCount>& iclist)
1260 {
1261         list<ProcessorCount>::iterator i;
1262
1263         for (i = iclist.begin(); i != iclist.end(); ++i) {
1264                 
1265                 cerr << "now applying for " << (*i).processor->name() << " in = " << (*i).in.n_audio() << " out = " << (*i).out.n_audio() << endl;
1266
1267                 if ((*i).processor->configure_io ((*i).in, (*i).out)) {
1268                         return -1;
1269                 }
1270                 /* make sure that however many we have, they are all active */
1271                 (*i).processor->activate ();
1272         }
1273
1274         return 0;
1275 }
1276
1277 /** Returns whether \a iclist can be configured and run starting with
1278  * \a required_inputs at the first processor's inputs.
1279  * If false is returned, \a iclist can not be run with \a required_inputs, and \a err is set.
1280  * Otherwise, \a err is set to the output of the list.
1281  */
1282 bool
1283 Route::check_some_plugin_counts (list<ProcessorCount>& iclist, ChanCount required_inputs, ProcessorStreams* err)
1284 {
1285         list<ProcessorCount>::iterator i;
1286         size_t index = 0;
1287                         
1288         if (err) {
1289                 err->index = 0;
1290                 err->count = required_inputs;
1291         }
1292
1293         for (i = iclist.begin(); i != iclist.end(); ++i) {
1294
1295
1296                 cerr << "Checking whether " << (*i).processor->name() << " can support " << required_inputs.n_audio() << " inputs\n";
1297
1298                 if ((*i).processor->can_support_input_configuration (required_inputs) < 0) {
1299                         if (err) {
1300                                 err->index = index;
1301                                 err->count = required_inputs;
1302                         }
1303                         return false;
1304                 }
1305                 
1306                 (*i).in = required_inputs;
1307                 (*i).out = (*i).processor->output_for_input_configuration (required_inputs);
1308
1309                 cerr << "config looks like " << (*i).processor->name() << " in = " << (*i).in.n_audio() << " out = " << (*i).out.n_audio() << endl;
1310
1311                 required_inputs = (*i).out;
1312                 
1313                 ++index;
1314         }
1315                         
1316         if (err) {
1317                 if (!iclist.empty()) {
1318                         err->index = index;
1319                         err->count = iclist.back().processor->output_for_input_configuration(required_inputs);
1320                 }
1321         }
1322
1323         return true;
1324 }
1325
1326 int
1327 Route::copy_processors (const Route& other, Placement placement, ProcessorStreams* err)
1328 {
1329         ChanCount old_rmo = processor_max_outs;
1330
1331         ProcessorList to_be_deleted;
1332
1333         {
1334                 Glib::RWLock::WriterLock lm (_processor_lock);
1335                 ProcessorList::iterator tmp;
1336                 ProcessorList the_copy;
1337
1338                 the_copy = _processors;
1339                 
1340                 /* remove all relevant processors */
1341
1342                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1343                         tmp = i;
1344                         ++tmp;
1345
1346                         if ((*i)->placement() == placement) {
1347                                 to_be_deleted.push_back (*i);
1348                                 _processors.erase (i);
1349                         }
1350
1351                         i = tmp;
1352                 }
1353
1354                 /* now copy the relevant ones from "other" */
1355                 
1356                 for (ProcessorList::const_iterator i = other._processors.begin(); i != other._processors.end(); ++i) {
1357                         if ((*i)->placement() == placement) {
1358                                 _processors.push_back (IOProcessor::clone (*i));
1359                         }
1360                 }
1361
1362                 /* reset plugin stream handling */
1363
1364                 if (_reset_plugin_counts (err)) {
1365
1366                         /* FAILED COPY ATTEMPT: we have to restore order */
1367
1368                         /* delete all cloned processors */
1369
1370                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1371
1372                                 tmp = i;
1373                                 ++tmp;
1374
1375                                 if ((*i)->placement() == placement) {
1376                                         _processors.erase (i);
1377                                 }
1378                                 
1379                                 i = tmp;
1380                         }
1381
1382                         /* restore the natural order */
1383
1384                         _processors = the_copy;
1385                         processor_max_outs = old_rmo;
1386
1387                         /* we failed, even though things are OK again */
1388
1389                         return -1;
1390
1391                 } else {
1392                         
1393                         /* SUCCESSFUL COPY ATTEMPT: delete the processors we removed pre-copy */
1394                         to_be_deleted.clear ();
1395                         _user_latency = 0;
1396                 }
1397         }
1398
1399         if (processor_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
1400                 reset_panner ();
1401         }
1402
1403         processors_changed (); /* EMIT SIGNAL */
1404         return 0;
1405 }
1406
1407 void
1408 Route::all_processors_flip ()
1409 {
1410         Glib::RWLock::ReaderLock lm (_processor_lock);
1411
1412         if (_processors.empty()) {
1413                 return;
1414         }
1415
1416         bool first_is_on = _processors.front()->active();
1417         
1418         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1419                 (*i)->set_active (!first_is_on);
1420         }
1421         
1422         _session.set_dirty ();
1423 }
1424
1425 /** Set all processors with a given placement to a given active state.
1426  * @param p Placement of processors to change.
1427  * @param state New active state for those processors.
1428  */
1429 void
1430 Route::all_processors_active (Placement p, bool state)
1431 {
1432         Glib::RWLock::ReaderLock lm (_processor_lock);
1433
1434         if (_processors.empty()) {
1435                 return;
1436         }
1437
1438         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1439                 if ((*i)->placement() == p) {
1440                         (*i)->set_active (state);
1441                 }
1442         }
1443         
1444         _session.set_dirty ();
1445 }
1446
1447 struct ProcessorSorter {
1448     bool operator() (boost::shared_ptr<const Processor> a, boost::shared_ptr<const Processor> b) {
1449             return a->sort_key() < b->sort_key();
1450     }
1451 };
1452
1453 int
1454 Route::sort_processors (ProcessorStreams* err)
1455 {
1456         {
1457                 ProcessorSorter comparator;
1458                 Glib::RWLock::WriterLock lm (_processor_lock);
1459                 ChanCount old_rmo = processor_max_outs;
1460
1461                 /* the sweet power of C++ ... */
1462
1463                 ProcessorList as_it_was_before = _processors;
1464
1465                 _processors.sort (comparator);
1466         
1467                 if (_reset_plugin_counts (err)) {
1468                         _processors = as_it_was_before;
1469                         processor_max_outs = old_rmo;
1470                         return -1;
1471                 } 
1472         } 
1473
1474         reset_panner ();
1475         processors_changed (); /* EMIT SIGNAL */
1476
1477         return 0;
1478 }
1479
1480 XMLNode&
1481 Route::get_state()
1482 {
1483         return state(true);
1484 }
1485
1486 XMLNode&
1487 Route::get_template()
1488 {
1489         return state(false);
1490 }
1491
1492 XMLNode&
1493 Route::state(bool full_state)
1494 {
1495         XMLNode *node = new XMLNode("Route");
1496         ProcessorList::iterator i;
1497         char buf[32];
1498
1499         if (_flags) {
1500                 node->add_property("flags", enum_2_string (_flags));
1501         }
1502         
1503         node->add_property("default-type", _default_type.to_string());
1504
1505         node->add_property("active", _active?"yes":"no");
1506         node->add_property("muted", _muted?"yes":"no");
1507         node->add_property("soloed", _soloed?"yes":"no");
1508         node->add_property("phase-invert", _phase_invert?"yes":"no");
1509         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1510         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1511         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1512         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1513         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1514
1515         if (_edit_group) {
1516                 node->add_property("edit-group", _edit_group->name());
1517         }
1518         if (_mix_group) {
1519                 node->add_property("mix-group", _mix_group->name());
1520         }
1521
1522         string order_string;
1523         OrderKeys::iterator x = order_keys.begin(); 
1524
1525         while (x != order_keys.end()) {
1526                 order_string += string ((*x).first);
1527                 order_string += '=';
1528                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1529                 order_string += buf;
1530                 
1531                 ++x;
1532
1533                 if (x == order_keys.end()) {
1534                         break;
1535                 }
1536
1537                 order_string += ':';
1538         }
1539         node->add_property ("order-keys", order_string);
1540
1541         node->add_child_nocopy (IO::state (full_state));
1542         node->add_child_nocopy (_solo_control->get_state ());
1543         node->add_child_nocopy (_mute_control->get_state ());
1544
1545         XMLNode* remote_control_node = new XMLNode (X_("remote_control"));
1546         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1547         remote_control_node->add_property (X_("id"), buf);
1548         node->add_child_nocopy (*remote_control_node);
1549
1550         if (_control_outs) {
1551                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1552                 cnode->add_child_nocopy (_control_outs->state (full_state));
1553                 node->add_child_nocopy (*cnode);
1554         }
1555
1556         if (_comment.length()) {
1557                 XMLNode *cmt = node->add_child ("Comment");
1558                 cmt->add_content (_comment);
1559         }
1560
1561         for (i = _processors.begin(); i != _processors.end(); ++i) {
1562                 node->add_child_nocopy((*i)->state (full_state));
1563         }
1564
1565         if (_extra_xml){
1566                 node->add_child_copy (*_extra_xml);
1567         }
1568         
1569         return *node;
1570 }
1571
1572 XMLNode&
1573 Route::get_processor_state ()
1574 {
1575         XMLNode* root = new XMLNode (X_("redirects"));
1576         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1577                 root->add_child_nocopy ((*i)->state (true));
1578         }
1579
1580         return *root;
1581 }
1582
1583 int
1584 Route::set_processor_state (const XMLNode& root)
1585 {
1586         if (root.name() != X_("redirects")) {
1587                 return -1;
1588         }
1589
1590         XMLNodeList nlist;
1591         XMLNodeList nnlist;
1592         XMLNodeConstIterator iter;
1593         XMLNodeConstIterator niter;
1594         Glib::RWLock::ReaderLock lm (_processor_lock);
1595
1596         nlist = root.children();
1597         
1598         for (iter = nlist.begin(); iter != nlist.end(); ++iter){
1599
1600                 /* iter now points to a IOProcessor state node */
1601                 
1602                 nnlist = (*iter)->children ();
1603
1604                 for (niter = nnlist.begin(); niter != nnlist.end(); ++niter) {
1605
1606                         /* find the IO child node, since it contains the ID we need */
1607
1608                         /* XXX OOP encapsulation violation, ugh */
1609
1610                         if ((*niter)->name() == IO::state_node_name) {
1611
1612                                 XMLProperty* prop = (*niter)->property (X_("id"));
1613                                 
1614                                 if (!prop) {
1615                                         warning << _("IOProcessor node has no ID, ignored") << endmsg;
1616                                         break;
1617                                 }
1618
1619                                 ID id = prop->value ();
1620
1621                                 /* now look for a processor with that ID */
1622         
1623                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1624                                         if ((*i)->id() == id) {
1625                                                 (*i)->set_state (**iter);
1626                                                 break;
1627                                         }
1628                                 }
1629                                 
1630                                 break;
1631                                 
1632                         }
1633                 }
1634
1635         }
1636
1637         return 0;
1638 }
1639
1640 void
1641 Route::set_deferred_state ()
1642 {
1643         XMLNodeList nlist;
1644         XMLNodeConstIterator niter;
1645
1646         if (!deferred_state) {
1647                 return;
1648         }
1649
1650         nlist = deferred_state->children();
1651
1652         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1653                 add_processor_from_xml (**niter);
1654         }
1655
1656         delete deferred_state;
1657         deferred_state = 0;
1658 }
1659
1660 void
1661 Route::add_processor_from_xml (const XMLNode& node)
1662 {
1663         const XMLProperty *prop;
1664
1665         // legacy sessions use a different node name for sends
1666         if (node.name() == "Send") {
1667         
1668                 try {
1669                         boost::shared_ptr<Send> send (new Send (_session, node));
1670                         add_processor (send);
1671                 } 
1672                 
1673                 catch (failed_constructor &err) {
1674                         error << _("Send construction failed") << endmsg;
1675                         return;
1676                 }
1677                 
1678         // use "Processor" in XML?
1679         } else if (node.name() == "Processor") {
1680                 
1681                 try {
1682                         if ((prop = node.property ("type")) != 0) {
1683
1684                                 boost::shared_ptr<Processor> processor;
1685                                 bool have_insert = false;
1686
1687                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
1688                                     prop->value() == "lv2" ||
1689                                     prop->value() == "vst" ||
1690                                     prop->value() == "audiounit") {
1691                                         
1692                                         processor.reset (new PluginInsert(_session, node));
1693                                         have_insert = true;
1694                                         
1695                                 } else if (prop->value() == "port") {
1696
1697                                         processor.reset (new PortInsert (_session, node));
1698                                 
1699                                 } else if (prop->value() == "send") {
1700
1701                                         processor.reset (new Send (_session, node));
1702                                         have_insert = true;
1703
1704                                 } else {
1705
1706                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
1707                                 }
1708                                 
1709                                 add_processor (processor);
1710                                 
1711                         } else {
1712                                 error << _("Processor XML node has no type property") << endmsg;
1713                         }
1714                 }
1715
1716                 catch (failed_constructor &err) {
1717                         warning << _("processor could not be created. Ignored.") << endmsg;
1718                         return;
1719                 }
1720         }
1721 }
1722
1723 int
1724 Route::set_state (const XMLNode& node)
1725 {
1726         return _set_state (node, true);
1727 }
1728
1729 int
1730 Route::_set_state (const XMLNode& node, bool call_base)
1731 {
1732         XMLNodeList nlist;
1733         XMLNodeConstIterator niter;
1734         XMLNode *child;
1735         XMLPropertyList plist;
1736         const XMLProperty *prop;
1737
1738         if (node.name() != "Route"){
1739                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1740                 return -1;
1741         }
1742
1743         if ((prop = node.property (X_("flags"))) != 0) {
1744                 _flags = Flag (string_2_enum (prop->value(), _flags));
1745         } else {
1746                 _flags = Flag (0);
1747         }
1748         
1749         if ((prop = node.property (X_("default-type"))) != 0) {
1750                 _default_type = DataType(prop->value());
1751                 assert(_default_type != DataType::NIL);
1752         }
1753
1754         if ((prop = node.property (X_("phase-invert"))) != 0) {
1755                 set_phase_invert (prop->value()=="yes"?true:false, this);
1756         }
1757
1758         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1759                 set_denormal_protection (prop->value()=="yes"?true:false, this);
1760         }
1761         
1762         _active = true;
1763         if ((prop = node.property (X_("active"))) != 0) {
1764                 set_active (prop->value() == "yes");
1765         }
1766
1767         if ((prop = node.property (X_("muted"))) != 0) {
1768                 bool yn = prop->value()=="yes"?true:false; 
1769
1770                 /* force reset of mute status */
1771
1772                 _muted = !yn;
1773                 set_mute(yn, this);
1774                 mute_gain = desired_mute_gain;
1775         }
1776
1777         if ((prop = node.property (X_("soloed"))) != 0) {
1778                 bool yn = prop->value()=="yes"?true:false; 
1779
1780                 /* force reset of solo status */
1781
1782                 _soloed = !yn;
1783                 set_solo (yn, this);
1784                 solo_gain = desired_solo_gain;
1785         }
1786
1787         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1788                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1789         }
1790
1791         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1792                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1793         }
1794
1795         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1796                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1797         }
1798
1799         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1800                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1801         }
1802
1803         if ((prop = node.property (X_("edit-group"))) != 0) {
1804                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1805                 if(edit_group == 0) {
1806                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1807                 } else {
1808                         set_edit_group(edit_group, this);
1809                 }
1810         }
1811
1812         if ((prop = node.property (X_("order-keys"))) != 0) {
1813
1814                 long n;
1815
1816                 string::size_type colon, equal;
1817                 string remaining = prop->value();
1818
1819                 while (remaining.length()) {
1820
1821                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1822                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1823                                       << endmsg;
1824                         } else {
1825                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1826                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1827                                               << endmsg;
1828                                 } else {
1829                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1830                                 }
1831                         }
1832
1833                         colon = remaining.find_first_of (':');
1834
1835                         if (colon != string::npos) {
1836                                 remaining = remaining.substr (colon+1);
1837                         } else {
1838                                 break;
1839                         }
1840                 }
1841         }
1842
1843         nlist = node.children();
1844
1845         if (deferred_state) {
1846                 delete deferred_state;
1847         }
1848
1849         deferred_state = new XMLNode(X_("deferred state"));
1850
1851         /* set parent class properties before anything else */
1852
1853         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1854
1855                 child = *niter;
1856
1857                 if (child->name() == IO::state_node_name && call_base) {
1858
1859                         IO::set_state (*child);
1860                         break;
1861                 }
1862         }
1863
1864         XMLNodeList processor_nodes;
1865                         
1866         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1867
1868                 child = *niter;
1869                         
1870                 if (child->name() == X_("Send") || child->name() == X_("Processor")) {
1871                         processor_nodes.push_back(child);
1872                 }
1873
1874         }
1875
1876         _set_processor_states(processor_nodes);
1877
1878
1879         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1880                 child = *niter;
1881                 // All processors have been applied already
1882
1883                 if (child->name() == X_("Automation")) {
1884                         
1885                         if ((prop = child->property (X_("path"))) != 0)  {
1886                                 load_automation (prop->value());
1887                         }
1888
1889                 } else if (child->name() == X_("ControlOuts")) {
1890                         
1891                         string coutname = _name;
1892                         coutname += _("[control]");
1893
1894                         _control_outs = new IO (_session, coutname);
1895                         _control_outs->set_state (**(child->children().begin()));
1896
1897                 } else if (child->name() == X_("Comment")) {
1898
1899                         /* XXX this is a terrible API design in libxml++ */
1900
1901                         XMLNode *cmt = *(child->children().begin());
1902                         _comment = cmt->content();
1903
1904                 } else if (child->name() == X_("extra")) {
1905
1906                         _extra_xml = new XMLNode (*child);
1907
1908                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
1909                         
1910                         if (prop->value() == "solo") {
1911                                 _solo_control->set_state (*child);
1912                                 _session.add_controllable (_solo_control);
1913                         }
1914                         else if (prop->value() == "mute") {
1915                                 _mute_control->set_state (*child);
1916                                 _session.add_controllable (_mute_control);
1917                         }
1918                 }
1919                 else if (child->name() == X_("remote_control")) {
1920                         if ((prop = child->property (X_("id"))) != 0) {
1921                                 int32_t x;
1922                                 sscanf (prop->value().c_str(), "%d", &x);
1923                                 set_remote_control_id (x);
1924                         }
1925                 }
1926         }
1927
1928         if ((prop = node.property (X_("mix-group"))) != 0) {
1929                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1930                 if (mix_group == 0) {
1931                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1932                 }  else {
1933                         set_mix_group(mix_group, this);
1934                 }
1935         }
1936
1937         return 0;
1938 }
1939
1940 void
1941 Route::_set_processor_states(const XMLNodeList &nlist)
1942 {
1943         XMLNodeConstIterator niter;
1944         char buf[64];
1945
1946         ProcessorList::iterator i, o;
1947
1948         // Iterate through existing processors, remove those which are not in the state list
1949         for (i = _processors.begin(); i != _processors.end(); ) {
1950                 ProcessorList::iterator tmp = i;
1951                 ++tmp;
1952
1953                 bool processorInStateList = false;
1954         
1955                 (*i)->id().print (buf, sizeof (buf));
1956
1957
1958                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1959
1960                         // legacy sessions (IOProcessor as a child of Processor, both is-a IO)
1961                         if (strncmp(buf,(*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
1962                                 processorInStateList = true;
1963                                 break;
1964                         } else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
1965                                 processorInStateList = true;
1966                                 break;
1967                         }
1968                 }
1969                 
1970                 if (!processorInStateList) {
1971                         remove_processor (*i);
1972                 }
1973
1974
1975                 i = tmp;
1976         }
1977
1978
1979         // Iterate through state list and make sure all processors are on the track and in the correct order,
1980         // set the state of existing processors according to the new state on the same go
1981         i = _processors.begin();
1982         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
1983
1984                 // Check whether the next processor in the list 
1985                 o = i;
1986
1987                 while (o != _processors.end()) {
1988                         (*o)->id().print (buf, sizeof (buf));
1989                         if ( strncmp(buf, (*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
1990                                 break;
1991                         else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
1992                                 break;
1993                         
1994                         ++o;
1995                 }
1996
1997                 if (o == _processors.end()) {
1998                         // If the processor (*niter) is not on the route, we need to create it
1999                         // and move it to the correct location
2000
2001                         ProcessorList::iterator prev_last = _processors.end();
2002                         --prev_last; // We need this to check whether adding succeeded
2003                         
2004                         add_processor_from_xml (**niter);
2005
2006                         ProcessorList::iterator last = _processors.end();
2007                         --last;
2008
2009                         if (prev_last == last) {
2010                                 cerr << "Could not fully restore state as some processors were not possible to create" << endl;
2011                                 continue;
2012
2013                         }
2014
2015                         boost::shared_ptr<Processor> tmp = (*last);
2016                         // remove the processor from the wrong location
2017                         _processors.erase(last);
2018                         // processor the new processor at the current location
2019                         _processors.insert(i, tmp);
2020
2021                         --i; // move pointer to the newly processored processor
2022                         continue;
2023                 }
2024
2025                 // We found the processor (*niter) on the route, first we must make sure the processor
2026                 // is at the location provided in the XML state
2027                 if (i != o) {
2028                         boost::shared_ptr<Processor> tmp = (*o);
2029                         // remove the old copy
2030                         _processors.erase(o);
2031                         // processor the processor at the correct location
2032                         _processors.insert(i, tmp);
2033
2034                         --i; // move pointer so it points to the right processor
2035                 }
2036
2037                 (*i)->set_state( (**niter) );
2038         }
2039         
2040         processors_changed ();
2041 }
2042
2043 void
2044 Route::curve_reallocate ()
2045 {
2046 //      _gain_automation_curve.finish_resize ();
2047 //      _pan_automation_curve.finish_resize ();
2048 }
2049
2050 void
2051 Route::silence (nframes_t nframes, nframes_t offset)
2052 {
2053         if (!_silent) {
2054
2055                 IO::silence (nframes, offset);
2056
2057                 if (_control_outs) {
2058                         _control_outs->silence (nframes, offset);
2059                 }
2060
2061                 { 
2062                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2063                         
2064                         if (lm.locked()) {
2065                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2066                                         boost::shared_ptr<PluginInsert> pi;
2067                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2068                                                 // skip plugins, they don't need anything when we're not active
2069                                                 continue;
2070                                         }
2071
2072                                         (*i)->silence (nframes, offset);
2073                                 }
2074
2075                                 if (nframes == _session.get_block_size() && offset == 0) {
2076                                         // _silent = true;
2077                                 }
2078                         }
2079                 }
2080                 
2081         }
2082 }       
2083
2084 int
2085 Route::set_control_outs (const vector<string>& ports)
2086 {
2087         Glib::Mutex::Lock lm (_control_outs_lock);
2088         vector<string>::const_iterator i;
2089         size_t limit;
2090         
2091         if (_control_outs) {
2092                 delete _control_outs;
2093                 _control_outs = 0;
2094         }
2095
2096         if (is_control() || is_master()) {
2097                 /* no control outs for these two special busses */
2098                 return 0;
2099         }
2100         
2101         if (ports.empty()) {
2102                 return 0;
2103         }
2104  
2105         string coutname = _name;
2106         coutname += _("[control]");
2107         
2108         _control_outs = new IO (_session, coutname);
2109
2110         /* our control outs need as many outputs as we
2111            have audio outputs. we track the changes in ::output_change_handler().
2112         */
2113         
2114         // XXX its stupid that we have to get this value twice
2115
2116         limit = n_outputs().n_audio();
2117         
2118         if (_control_outs->ensure_io (ChanCount::ZERO, ChanCount (DataType::AUDIO, n_outputs().get (DataType::AUDIO)), true, this)) {
2119                 return -1;
2120         }
2121         
2122         /* now connect to the named ports */
2123         
2124         for (size_t n = 0; n < limit; ++n) {
2125                 if (_control_outs->connect_output (_control_outs->output (n), ports[n % ports.size()], this)) {
2126                         error << string_compose (_("could not connect %1 to %2"), _control_outs->output(n)->name(), ports[n]) << endmsg;
2127                         return -1;
2128                 }
2129         }
2130  
2131         return 0;
2132 }       
2133
2134 void
2135 Route::set_edit_group (RouteGroup *eg, void *src)
2136
2137 {
2138         if (eg == _edit_group) {
2139                 return;
2140         }
2141
2142         if (_edit_group) {
2143                 _edit_group->remove (this);
2144         }
2145
2146         if ((_edit_group = eg) != 0) {
2147                 _edit_group->add (this);
2148         }
2149
2150         _session.set_dirty ();
2151         edit_group_changed (src); /* EMIT SIGNAL */
2152 }
2153
2154 void
2155 Route::drop_edit_group (void *src)
2156 {
2157         _edit_group = 0;
2158         _session.set_dirty ();
2159         edit_group_changed (src); /* EMIT SIGNAL */
2160 }
2161
2162 void
2163 Route::set_mix_group (RouteGroup *mg, void *src)
2164
2165 {
2166         if (mg == _mix_group) {
2167                 return;
2168         }
2169
2170         if (_mix_group) {
2171                 _mix_group->remove (this);
2172         }
2173
2174         if ((_mix_group = mg) != 0) {
2175                 _mix_group->add (this);
2176         }
2177
2178         _session.set_dirty ();
2179         mix_group_changed (src); /* EMIT SIGNAL */
2180 }
2181
2182 void
2183 Route::drop_mix_group (void *src)
2184 {
2185         _mix_group = 0;
2186         _session.set_dirty ();
2187         mix_group_changed (src); /* EMIT SIGNAL */
2188 }
2189
2190 void
2191 Route::set_comment (string cmt, void *src)
2192 {
2193         _comment = cmt;
2194         comment_changed (src);
2195         _session.set_dirty ();
2196 }
2197
2198 bool
2199 Route::feeds (boost::shared_ptr<Route> other)
2200 {
2201         uint32_t i, j;
2202
2203         IO& self = *this;
2204         uint32_t no = self.n_outputs().n_total();
2205         uint32_t ni = other->n_inputs ().n_total();
2206
2207         for (i = 0; i < no; ++i) {
2208                 for (j = 0; j < ni; ++j) {
2209                         if (self.output(i)->connected_to (other->input(j)->name())) {
2210                                 return true;
2211                         }
2212                 }
2213         }
2214
2215         /* check IOProcessors which may also interconnect Routes */
2216
2217         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2218
2219                 boost::shared_ptr<IOProcessor> redirect = boost::dynamic_pointer_cast<IOProcessor>(*r);
2220
2221                 if ( ! redirect)
2222                         continue;
2223
2224                 // TODO: support internal redirects here
2225
2226                 no = redirect->io()->n_outputs().n_total();
2227
2228                 for (i = 0; i < no; ++i) {
2229                         for (j = 0; j < ni; ++j) {
2230                                 if (redirect->io()->output(i)->connected_to (other->input (j)->name())) {
2231                                         return true;
2232                                 }
2233                         }
2234                 }
2235         }
2236
2237         /* check for control room outputs which may also interconnect Routes */
2238
2239         if (_control_outs) {
2240
2241                 no = _control_outs->n_outputs().n_total();
2242                 
2243                 for (i = 0; i < no; ++i) {
2244                         for (j = 0; j < ni; ++j) {
2245                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
2246                                         return true;
2247                                 }
2248                         }
2249                 }
2250         }
2251
2252         return false;
2253 }
2254
2255 void
2256 Route::set_mute_config (mute_type t, bool onoff, void *src)
2257 {
2258         switch (t) {
2259         case PRE_FADER:
2260                 _mute_affects_pre_fader = onoff;
2261                  pre_fader_changed(src); /* EMIT SIGNAL */
2262                 break;
2263
2264         case POST_FADER:
2265                 _mute_affects_post_fader = onoff;
2266                  post_fader_changed(src); /* EMIT SIGNAL */
2267                 break;
2268
2269         case CONTROL_OUTS:
2270                 _mute_affects_control_outs = onoff;
2271                  control_outs_changed(src); /* EMIT SIGNAL */
2272                 break;
2273
2274         case MAIN_OUTS:
2275                 _mute_affects_main_outs = onoff;
2276                  main_outs_changed(src); /* EMIT SIGNAL */
2277                 break;
2278         }
2279 }
2280
2281 bool
2282 Route::get_mute_config (mute_type t)
2283 {
2284         bool onoff = false;
2285         
2286         switch (t){
2287         case PRE_FADER:
2288                 onoff = _mute_affects_pre_fader; 
2289                 break;
2290         case POST_FADER:
2291                 onoff = _mute_affects_post_fader;
2292                 break;
2293         case CONTROL_OUTS:
2294                 onoff = _mute_affects_control_outs;
2295                 break;
2296         case MAIN_OUTS:
2297                 onoff = _mute_affects_main_outs;
2298                 break;
2299         }
2300         
2301         return onoff;
2302 }
2303
2304 void
2305 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
2306 {
2307         nframes_t now = _session.transport_frame();
2308
2309         {
2310                 Glib::RWLock::ReaderLock lm (_processor_lock);
2311
2312                 if (!did_locate) {
2313                         automation_snapshot (now, true);
2314                 }
2315
2316                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2317                         
2318                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2319                                 (*i)->deactivate ();
2320                                 (*i)->activate ();
2321                         }
2322                         
2323                         (*i)->transport_stopped (now);
2324                 }
2325         }
2326
2327         IO::transport_stopped (now);
2328  
2329         _roll_delay = _initial_delay;
2330 }
2331
2332 void
2333 Route::input_change_handler (IOChange change, void *ignored)
2334 {
2335         if (change & ConfigurationChanged) {
2336                 reset_plugin_counts (0);
2337         }
2338 }
2339
2340 void
2341 Route::output_change_handler (IOChange change, void *ignored)
2342 {
2343         if (change & ConfigurationChanged) {
2344                 if (_control_outs) {
2345                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().n_audio()), true, this);
2346                 }
2347                 
2348                 reset_plugin_counts (0);
2349         }
2350 }
2351
2352 uint32_t
2353 Route::pans_required () const
2354 {
2355         if (n_outputs().n_audio() < 2) {
2356                 return 0;
2357         }
2358         
2359         return max (n_inputs ().n_audio(), processor_max_outs.n_audio());
2360 }
2361
2362 int 
2363 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2364                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2365 {
2366         if (n_outputs().n_total() == 0) {
2367                 return 0;
2368         }
2369
2370         if (session_state_changing || !_active)  {
2371                 silence (nframes, offset);
2372                 return 0;
2373         }
2374
2375         apply_gain_automation = false;
2376         
2377         if (n_inputs().n_total()) {
2378                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2379         } else {
2380                 silence (nframes, offset);
2381         }
2382
2383         return 0;
2384 }
2385
2386 nframes_t
2387 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2388 {
2389         if (_roll_delay > nframes) {
2390
2391                 _roll_delay -= nframes;
2392                 silence (nframes, offset);
2393                 /* transport frame is not legal for caller to use */
2394                 return 0;
2395
2396         } else if (_roll_delay > 0) {
2397
2398                 nframes -= _roll_delay;
2399
2400                 silence (_roll_delay, offset);
2401
2402                 offset += _roll_delay;
2403                 transport_frame += _roll_delay;
2404
2405                 _roll_delay = 0;
2406         }
2407
2408         return nframes;
2409 }
2410
2411 int
2412 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2413              bool can_record, bool rec_monitors_input)
2414 {
2415         {
2416                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2417                 if (lm.locked()) {
2418                         // automation snapshot can also be called from the non-rt context
2419                         // and it uses the processor list, so we take the lock out here
2420                         automation_snapshot (_session.transport_frame(), false);
2421                 }
2422         }
2423
2424         if ((n_outputs().n_total() == 0 && _processors.empty()) || n_inputs().n_total() == 0 || !_active) {
2425                 silence (nframes, offset);
2426                 return 0;
2427         }
2428         
2429         nframes_t unused = 0;
2430
2431         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2432                 return 0;
2433         }
2434
2435         _silent = false;
2436
2437         apply_gain_automation = false;
2438
2439         { 
2440                 Glib::Mutex::Lock am (_automation_lock, Glib::TRY_LOCK);
2441                 
2442                 if (am.locked() && _session.transport_rolling()) {
2443                         
2444                         if (_gain_control->list()->automation_playback()) {
2445                                 apply_gain_automation = _gain_control->list()->curve().rt_safe_get_vector (
2446                                                 start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2447                         }
2448                 }
2449         }
2450
2451         passthru (start_frame, end_frame, nframes, offset, declick, false);
2452
2453         return 0;
2454 }
2455
2456 int
2457 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2458                     bool can_record, bool rec_monitors_input)
2459 {
2460         silence (nframes, offset);
2461         return 0;
2462 }
2463
2464 void
2465 Route::toggle_monitor_input ()
2466 {
2467         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2468                 i->ensure_monitor_input( ! i->monitoring_input());
2469         }
2470 }
2471
2472 bool
2473 Route::has_external_redirects () const
2474 {
2475         // FIXME: what about sends?
2476
2477         boost::shared_ptr<const PortInsert> pi;
2478         
2479         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2480                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2481
2482                         for (PortSet::const_iterator port = pi->io()->outputs().begin();
2483                                         port != pi->io()->outputs().end(); ++port) {
2484                                 
2485                                 string port_name = port->name();
2486                                 string client_name = port_name.substr (0, port_name.find(':'));
2487
2488                                 /* only say "yes" if the redirect is actually in use */
2489                                 
2490                                 if (client_name != "ardour" && pi->active()) {
2491                                         return true;
2492                                 }
2493                         }
2494                 }
2495         }
2496
2497         return false;
2498 }
2499
2500 void
2501 Route::flush_processors ()
2502 {
2503         /* XXX shouldn't really try to take this lock, since
2504            this is called from the RT audio thread.
2505         */
2506
2507         Glib::RWLock::ReaderLock lm (_processor_lock);
2508
2509         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2510                 (*i)->deactivate ();
2511                 (*i)->activate ();
2512         }
2513 }
2514
2515 void
2516 Route::set_meter_point (MeterPoint p, void *src)
2517 {
2518         if (_meter_point != p) {
2519                 _meter_point = p;
2520                  meter_change (src); /* EMIT SIGNAL */
2521                 _session.set_dirty ();
2522         }
2523 }
2524
2525 nframes_t
2526 Route::update_total_latency ()
2527 {
2528         nframes_t old = _own_latency;
2529
2530         if (_user_latency) {
2531                 _own_latency = _user_latency;
2532         } else {
2533                 _own_latency = 0;
2534
2535                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2536                         if ((*i)->active ()) {
2537                                 _own_latency += (*i)->signal_latency ();
2538                         }
2539                 }
2540         }
2541
2542         set_port_latency (_own_latency);
2543         
2544         if (!_user_latency) {
2545                 /* this (virtual) function is used for pure Routes,
2546                    not derived classes like AudioTrack.  this means
2547                    that the data processed here comes from an input
2548                    port, not prerecorded material, and therefore we
2549                    have to take into account any input latency.
2550                 */
2551
2552
2553                 _own_latency += input_latency ();
2554         }
2555
2556         if (old != _own_latency) {
2557                 signal_latency_changed (); /* EMIT SIGNAL */
2558         }
2559         
2560         return _own_latency;
2561 }
2562
2563 void
2564 Route::set_user_latency (nframes_t nframes)
2565 {
2566         Latent::set_user_latency (nframes);
2567         _session.update_latency_compensation (false, false);
2568 }
2569
2570 void
2571 Route::set_latency_delay (nframes_t longest_session_latency)
2572 {
2573         nframes_t old = _initial_delay;
2574
2575         if (_own_latency < longest_session_latency) {
2576                 _initial_delay = longest_session_latency - _own_latency;
2577         } else {
2578                 _initial_delay = 0;
2579         }
2580
2581         if (_initial_delay != old) {
2582                 initial_delay_changed (); /* EMIT SIGNAL */
2583         }
2584
2585         if (_session.transport_stopped()) {
2586                 _roll_delay = _initial_delay;
2587         }
2588 }
2589
2590 void
2591 Route::automation_snapshot (nframes_t now, bool force)
2592 {
2593         if (!force && !should_snapshot(now)) {
2594                 return;
2595         }
2596
2597         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2598                 // IO::automation_snapshot (now, force);  ?
2599                 (*i)->automation_snapshot (now, force);
2600         }
2601 }
2602
2603 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2604         : Controllable (name), route (s), type(tp)
2605 {
2606         
2607 }
2608
2609 void
2610 Route::ToggleControllable::set_value (float val)
2611 {
2612         bool bval = ((val >= 0.5f) ? true: false);
2613         
2614         switch (type) {
2615         case MuteControl:
2616                 route.set_mute (bval, this);
2617                 break;
2618         case SoloControl:
2619                 route.set_solo (bval, this);
2620                 break;
2621         default:
2622                 break;
2623         }
2624 }
2625
2626 float
2627 Route::ToggleControllable::get_value (void) const
2628 {
2629         float val = 0.0f;
2630         
2631         switch (type) {
2632         case MuteControl:
2633                 val = route.muted() ? 1.0f : 0.0f;
2634                 break;
2635         case SoloControl:
2636                 val = route.soloed() ? 1.0f : 0.0f;
2637                 break;
2638         default:
2639                 break;
2640         }
2641
2642         return val;
2643 }
2644
2645 void 
2646 Route::set_block_size (nframes_t nframes)
2647 {
2648         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2649                 (*i)->set_block_size (nframes);
2650         }
2651 }
2652
2653 void
2654 Route::protect_automation ()
2655 {
2656         Automatable::protect_automation();
2657         
2658         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2659                 (*i)->protect_automation();
2660 }
2661
2662 void
2663 Route::set_pending_declick (int declick)
2664 {
2665         if (_declickable) {
2666                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2667                 if (declick) {
2668                         _pending_declick = declick;
2669                 }
2670                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2671         } else {
2672                 _pending_declick = 0;
2673         }
2674
2675 }