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