Display recorded controller data (fix show all/existing automation).
[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_pmo = 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                 _processors.push_back (processor);
831
832                 if (_reset_processor_counts (err)) {
833                         _processors.pop_back ();
834                         _reset_processor_counts (0); // it worked before we tried to add it ...
835                         return -1;
836                 }
837
838                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
839                         
840                         if (pi->natural_input_streams() == ChanCount::ZERO) {
841                                 /* generator plugin */
842                                 _have_internal_generator = true;
843                         }
844                         
845                 }
846                 
847                 _processors.push_back (processor);
848
849                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
850                 // configure redirect ports properly, etc.
851                 if (_reset_processor_counts (err)) {
852                         _processors.pop_back ();
853                         _reset_processor_counts (0); // it worked before we tried to add it ...
854                         return -1;
855                 }
856
857                 // Ensure peak vector sizes before the plugin is activated
858
859                 ChanCount potential_max_streams;
860
861                 potential_max_streams.set (DataType::AUDIO, max (processor->input_streams().n_audio(), 
862                                                                  processor->output_streams().n_audio()));
863                 potential_max_streams.set (DataType::MIDI, max (processor->input_streams().n_midi(), 
864                                                                 processor->output_streams().n_midi()));
865
866                 _meter->configure_io (potential_max_streams, potential_max_streams);
867
868                 processor->activate ();
869                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
870
871                 _user_latency = 0;
872         }
873         
874         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
875                 reset_panner ();
876         }
877
878         processors_changed (); /* EMIT SIGNAL */
879         
880         return 0;
881 }
882
883 int
884 Route::add_processors (const ProcessorList& others, ProcessorStreams* err)
885 {
886         ChanCount old_pmo = processor_max_outs;
887
888         if (!_session.engine().connected()) {
889                 return 1;
890         }
891
892         {
893                 Glib::RWLock::WriterLock lm (_processor_lock);
894
895                 ProcessorList::iterator existing_end = _processors.end();
896                 --existing_end;
897
898                 ChanCount potential_max_streams;
899
900                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
901                         
902                         boost::shared_ptr<PluginInsert> pi;
903                         
904                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
905                                 pi->set_count (1);
906                                 
907                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
908                                 if (m > potential_max_streams)
909                                         potential_max_streams = m;
910                         }
911
912                         // Ensure peak vector sizes before the plugin is activated
913                         _meter->configure_io (potential_max_streams, potential_max_streams);
914
915                         _processors.push_back (*i);
916                         
917                         if (_reset_processor_counts (err)) {
918                                 ++existing_end;
919                                 _processors.erase (existing_end, _processors.end());
920                                 _reset_processor_counts (0); // it worked before we tried to add it ...
921                                 return -1;
922                         }
923                         
924                         (*i)->activate ();
925                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
926                 }
927
928                 _user_latency = 0;
929         }
930         
931         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
932                 reset_panner ();
933         }
934
935         processors_changed (); /* EMIT SIGNAL */
936         return 0;
937 }
938
939 /** Turn off all processors with a given placement
940  * @param p Placement of processors to disable
941  */
942
943 void
944 Route::disable_processors (Placement p)
945 {
946         Glib::RWLock::ReaderLock lm (_processor_lock);
947         
948         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
949                 if ((*i)->placement() == p) {
950                         (*i)->set_active (false);
951                 }
952         }
953
954         _session.set_dirty ();
955 }
956
957 /** Turn off all redirects 
958  */
959
960 void
961 Route::disable_processors ()
962 {
963         Glib::RWLock::ReaderLock lm (_processor_lock);
964         
965         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
966                 (*i)->set_active (false);
967         }
968         
969         _session.set_dirty ();
970 }
971
972 /** Turn off all redirects with a given placement
973  * @param p Placement of redirects to disable
974  */
975
976 void
977 Route::disable_plugins (Placement p)
978 {
979         Glib::RWLock::ReaderLock lm (_processor_lock);
980         
981         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
982                 if (boost::dynamic_pointer_cast<PluginInsert> (*i) && (*i)->placement() == p) {
983                         (*i)->set_active (false);
984                 }
985         }
986         
987         _session.set_dirty ();
988 }
989
990 /** Turn off all plugins
991  */
992
993 void
994 Route::disable_plugins ()
995 {
996         Glib::RWLock::ReaderLock lm (_processor_lock);
997         
998         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
999                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1000                         (*i)->set_active (false);
1001                 }
1002         }
1003         
1004         _session.set_dirty ();
1005 }
1006
1007
1008 void
1009 Route::ab_plugins (bool forward)
1010 {
1011         Glib::RWLock::ReaderLock lm (_processor_lock);
1012                         
1013         if (forward) {
1014
1015                 /* forward = turn off all active redirects, and mark them so that the next time
1016                    we go the other way, we will revert them
1017                 */
1018
1019                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1020                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1021                                 continue;
1022                         }
1023
1024                         if ((*i)->active()) {
1025                                 (*i)->set_active (false);
1026                                 (*i)->set_next_ab_is_active (true);
1027                         } else {
1028                                 (*i)->set_next_ab_is_active (false);
1029                         }
1030                 }
1031
1032         } else {
1033
1034                 /* backward = if the redirect was marked to go active on the next ab, do so */
1035
1036                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1037
1038                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1039                                 continue;
1040                         }
1041
1042                         if ((*i)->get_next_ab_is_active()) {
1043                                 (*i)->set_active (true);
1044                         } else {
1045                                 (*i)->set_active (false);
1046                         }
1047                 }
1048         }
1049         
1050         _session.set_dirty ();
1051 }
1052         
1053         
1054 /* Figure out the streams that will feed into PreFader */
1055 ChanCount
1056 Route::pre_fader_streams() const
1057 {
1058         boost::shared_ptr<Processor> processor;
1059
1060         // Find the last pre-fader redirect
1061         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1062                 if ((*i)->placement() == PreFader) {
1063                         processor = *i;
1064                 }
1065         }
1066         
1067         if (processor) {
1068                 return processor->output_streams();
1069         } else {
1070                 return n_inputs ();
1071         }
1072 }
1073
1074
1075 /** Remove processors with a given placement.
1076  * @param p Placement of processors to remove.
1077  */
1078 void
1079 Route::clear_processors (Placement p)
1080 {
1081         const ChanCount old_pmo = processor_max_outs;
1082
1083         if (!_session.engine().connected()) {
1084                 return;
1085         }
1086
1087         {
1088                 Glib::RWLock::WriterLock lm (_processor_lock);
1089                 ProcessorList new_list;
1090                 
1091                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1092                         if ((*i)->placement() == p) {
1093                                 /* it's the placement we want to get rid of */
1094                                 (*i)->drop_references ();
1095                         } else {
1096                                 /* it's a different placement, so keep it */
1097                                 new_list.push_back (*i);
1098                         }
1099                 }
1100                 
1101                 _processors = new_list;
1102         }
1103
1104         /* FIXME: can't see how this test can ever fire */
1105         if (processor_max_outs != old_pmo) {
1106                 reset_panner ();
1107         }
1108         
1109         processor_max_outs.reset();
1110         _have_internal_generator = false;
1111         processors_changed (); /* EMIT SIGNAL */
1112 }
1113
1114 int
1115 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1116 {
1117         ChanCount old_pmo = processor_max_outs;
1118
1119         if (!_session.engine().connected()) {
1120                 return 1;
1121         }
1122
1123         processor_max_outs.reset();
1124
1125         {
1126                 Glib::RWLock::WriterLock lm (_processor_lock);
1127                 ProcessorList::iterator i;
1128                 bool removed = false;
1129
1130                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1131                         if (*i == processor) {
1132
1133                                 ProcessorList::iterator tmp;
1134
1135                                 /* move along, see failure case for reset_processor_counts()
1136                                    where we may need to reprocessor the processor.
1137                                 */
1138
1139                                 tmp = i;
1140                                 ++tmp;
1141
1142                                 /* stop redirects that send signals to JACK ports
1143                                    from causing noise as a result of no longer being
1144                                    run.
1145                                 */
1146
1147                                 boost::shared_ptr<IOProcessor> redirect;
1148                                 
1149                                 if ((redirect = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1150                                         redirect->io()->disconnect_inputs (this);
1151                                         redirect->io()->disconnect_outputs (this);
1152                                 }
1153
1154                                 _processors.erase (i);
1155
1156                                 i = tmp;
1157                                 removed = true;
1158                                 break;
1159                         }
1160
1161                         _user_latency = 0;
1162                 }
1163
1164                 if (!removed) {
1165                         /* what? */
1166                         return 1;
1167                 }
1168
1169                 if (_reset_processor_counts (err)) {
1170                         /* get back to where we where */
1171                         _processors.insert (i, processor);
1172                         /* we know this will work, because it worked before :) */
1173                         _reset_processor_counts (0);
1174                         return -1;
1175                 }
1176
1177                 _have_internal_generator = false;
1178
1179                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1180                         boost::shared_ptr<PluginInsert> pi;
1181                         
1182                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1183                                 if (pi->is_generator()) {
1184                                         _have_internal_generator = true;
1185                                         break;
1186                                 }
1187                         }
1188                 }
1189         }
1190
1191         if (old_pmo != processor_max_outs) {
1192                 reset_panner ();
1193         }
1194
1195         processor->drop_references ();
1196
1197         processors_changed (); /* EMIT SIGNAL */
1198         return 0;
1199 }
1200
1201 int
1202 Route::reset_processor_counts (ProcessorStreams* err)
1203 {
1204         Glib::RWLock::WriterLock lm (_processor_lock);
1205         return _reset_processor_counts (err);
1206 }
1207
1208
1209 int
1210 Route::_reset_processor_counts (ProcessorStreams* err)
1211 {
1212         ProcessorList::iterator r;
1213         uint32_t insert_cnt = 0;
1214         uint32_t send_cnt = 0;
1215         map<Placement,list<ProcessorCount> > proc_map;
1216         ProcessorList::iterator prev;
1217         ChanCount initial_streams = n_inputs ();
1218         ChanCount previous_initial_streams = n_inputs ();
1219         int ret = -1;
1220         uint32_t max_audio = 0;
1221         uint32_t max_midi = 0;
1222
1223         processor_max_outs.reset ();
1224         
1225         /* Step 1: build a map that links each insert to an in/out channel count 
1226
1227            Divide inserts up by placement so we get the signal flow
1228            properly modelled. we need to do this because the _processors
1229            list is not sorted by placement, and because other reasons may 
1230            exist now or in the future for this separate treatment.
1231         */
1232
1233         /* ... but it should/will be... */
1234         
1235         for (r = _processors.begin(); r != _processors.end(); ++r) {
1236
1237                 boost::shared_ptr<PluginInsert> plugin_insert;
1238                 boost::shared_ptr<PortInsert> port_insert;
1239
1240                 if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert>(*r)) != 0) {
1241
1242                         ++insert_cnt;
1243                         proc_map[(*r)->placement()].push_back (ProcessorCount (*r));
1244
1245                         /* reset plugin counts back to one for now so
1246                            that we have a predictable, controlled
1247                            state to try to configure.
1248                         */
1249
1250                         plugin_insert->set_count (1);
1251
1252                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert>(*r)) != 0) {
1253                         
1254                         ++insert_cnt;
1255                         proc_map[(*r)->placement()].push_back (ProcessorCount (*r));
1256
1257                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1258                         ++send_cnt;
1259                 }
1260         }
1261         
1262         if (insert_cnt == 0) {
1263                 if (send_cnt) {
1264                         goto recompute;
1265                 } else {
1266                         ret = 0;
1267                         goto streamcount;
1268                 }
1269         }
1270
1271         /* Now process each placement in order, checking to see if we 
1272            can really do what has been requested.
1273         */
1274
1275         /* A: PreFader */
1276         
1277         if (check_some_processor_counts (proc_map[PreFader], n_inputs (), err)) {
1278                 goto streamcount;
1279         }
1280
1281         if (!proc_map[PreFader].empty()) {
1282                 previous_initial_streams = n_inputs ();
1283                 for (list<ProcessorCount>::iterator i = proc_map[PreFader].begin(); i != proc_map[PreFader].end(); i++) {
1284                         if (i->processor->can_support_io_configuration (previous_initial_streams, initial_streams) < 0) {
1285                                 goto streamcount;
1286                         }
1287                         previous_initial_streams = initial_streams;
1288                 }
1289         }
1290
1291         /* B: PostFader */
1292
1293         if (check_some_processor_counts (proc_map[PostFader], initial_streams, err)) {
1294                 goto streamcount;
1295         }
1296
1297         if (!proc_map[PostFader].empty()) {
1298                 for (list<ProcessorCount>::iterator i = proc_map[PostFader].begin(); i != proc_map[PostFader].end(); i++) {
1299                         if (i->processor->can_support_io_configuration (previous_initial_streams, initial_streams) < 0) {
1300                                 goto streamcount;
1301                         }
1302                         previous_initial_streams = initial_streams;
1303                 }
1304         }
1305
1306         /* OK, everything can be set up correctly, so lets do it */
1307
1308         apply_some_processor_counts (proc_map[PreFader]);
1309         apply_some_processor_counts (proc_map[PostFader]);
1310
1311         /* recompute max outs of any processor */
1312
1313         ret = 0;
1314
1315   recompute:
1316
1317         processor_max_outs.reset ();
1318         prev = _processors.end();
1319
1320         for (r = _processors.begin(); r != _processors.end(); prev = r, ++r) {
1321                 boost::shared_ptr<Send> s;
1322
1323                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1324                         if (r == _processors.begin()) {
1325                                 s->expect_inputs (n_inputs());
1326                         } else {
1327                                 s->expect_inputs ((*prev)->output_streams());
1328                         }
1329
1330                 } else {
1331                         
1332                         /* don't pay any attention to send output configuration, since it doesn't
1333                            affect the route.
1334                          */
1335                         
1336                         max_audio = max ((*r)->output_streams ().n_audio(), max_audio);
1337                         max_midi = max ((*r)->output_streams ().n_midi(), max_midi);
1338                 }
1339         }
1340
1341         processor_max_outs.set (DataType::AUDIO, max_audio);
1342         processor_max_outs.set (DataType::MIDI, max_midi);
1343                         
1344         /* we're done */
1345         return 0;
1346
1347   streamcount:
1348         for (r = _processors.begin(); r != _processors.end(); ++r) {
1349                 max_audio = max ((*r)->output_streams ().n_audio(), max_audio);
1350                 max_midi = max ((*r)->output_streams ().n_midi(), max_midi);
1351         }
1352
1353         processor_max_outs.set (DataType::AUDIO, max_audio);
1354         processor_max_outs.set (DataType::MIDI, max_midi);
1355
1356         return ret;
1357 }                                  
1358
1359 int32_t
1360 Route::apply_some_processor_counts (list<ProcessorCount>& iclist)
1361 {
1362         list<ProcessorCount>::iterator i;
1363         
1364         for (i = iclist.begin(); i != iclist.end(); ++i) {
1365
1366                 ProcessorCount& pc (*i);
1367
1368                 cerr << "now applying for " << (*i).processor->name() << " in = " << pc.in.n_audio() << " out = " << pc.out.n_audio() << endl;
1369
1370                 if (pc.processor->configure_io (pc.in, pc.out)) {
1371                         return -1;
1372                 }
1373
1374                 /* make sure that however many we have, they are all active */
1375
1376                 pc.processor->activate ();
1377         }
1378
1379         return 0;
1380 }
1381
1382 /** Returns whether \a iclist can be configured and run starting with
1383  * \a required_inputs at the first processor's inputs.
1384  * If false is returned, \a iclist can not be run with \a required_inputs, and \a err is set.
1385  * Otherwise, \a err is set to the output of the list.
1386  */
1387 bool
1388 Route::check_some_processor_counts (list<ProcessorCount>& iclist, ChanCount required_inputs, ProcessorStreams* err)
1389 {
1390         list<ProcessorCount>::iterator i;
1391         size_t index = 0;
1392                         
1393         if (err) {
1394                 err->index = 0;
1395                 err->count = required_inputs;
1396         }
1397
1398         for (i = iclist.begin(); i != iclist.end(); ++i, ++index) {
1399
1400                 cerr << "Checking whether " << (*i).processor->name() << " can support " << required_inputs.n_audio() << " inputs\n";
1401
1402                 if (!(*i).processor->can_support_io_configuration (required_inputs, (*i).out)) {
1403                         if (err) {
1404                                 err->index = index;
1405                                 err->count = required_inputs;
1406                         }
1407                         return false;
1408                 }
1409                 
1410                 (*i).in = required_inputs;
1411                 required_inputs = (*i).out;
1412         }
1413
1414         return true;
1415 }
1416
1417 int
1418 Route::copy_processors (const Route& other, Placement placement, ProcessorStreams* err)
1419 {
1420         ChanCount old_pmo = processor_max_outs;
1421
1422         ProcessorList to_be_deleted;
1423
1424         {
1425                 Glib::RWLock::WriterLock lm (_processor_lock);
1426                 ProcessorList::iterator tmp;
1427                 ProcessorList the_copy;
1428
1429                 the_copy = _processors;
1430                 
1431                 /* remove all relevant processors */
1432
1433                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1434                         tmp = i;
1435                         ++tmp;
1436
1437                         if ((*i)->placement() == placement) {
1438                                 to_be_deleted.push_back (*i);
1439                                 _processors.erase (i);
1440                         }
1441
1442                         i = tmp;
1443                 }
1444
1445                 /* now copy the relevant ones from "other" */
1446                 
1447                 for (ProcessorList::const_iterator i = other._processors.begin(); i != other._processors.end(); ++i) {
1448                         if ((*i)->placement() == placement) {
1449                                 _processors.push_back (IOProcessor::clone (*i));
1450                         }
1451                 }
1452
1453                 /* reset plugin stream handling */
1454
1455                 if (_reset_processor_counts (err)) {
1456
1457                         /* FAILED COPY ATTEMPT: we have to restore order */
1458
1459                         /* delete all cloned processors */
1460
1461                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1462
1463                                 tmp = i;
1464                                 ++tmp;
1465
1466                                 if ((*i)->placement() == placement) {
1467                                         _processors.erase (i);
1468                                 }
1469                                 
1470                                 i = tmp;
1471                         }
1472
1473                         /* restore the natural order */
1474
1475                         _processors = the_copy;
1476                         processor_max_outs = old_pmo;
1477
1478                         /* we failed, even though things are OK again */
1479
1480                         return -1;
1481
1482                 } else {
1483                         
1484                         /* SUCCESSFUL COPY ATTEMPT: delete the processors we removed pre-copy */
1485                         to_be_deleted.clear ();
1486                         _user_latency = 0;
1487                 }
1488         }
1489
1490         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
1491                 reset_panner ();
1492         }
1493
1494         processors_changed (); /* EMIT SIGNAL */
1495         return 0;
1496 }
1497
1498 void
1499 Route::all_processors_flip ()
1500 {
1501         Glib::RWLock::ReaderLock lm (_processor_lock);
1502
1503         if (_processors.empty()) {
1504                 return;
1505         }
1506
1507         bool first_is_on = _processors.front()->active();
1508         
1509         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1510                 (*i)->set_active (!first_is_on);
1511         }
1512         
1513         _session.set_dirty ();
1514 }
1515
1516 /** Set all processors with a given placement to a given active state.
1517  * @param p Placement of processors to change.
1518  * @param state New active state for those processors.
1519  */
1520 void
1521 Route::all_processors_active (Placement p, bool state)
1522 {
1523         Glib::RWLock::ReaderLock lm (_processor_lock);
1524
1525         if (_processors.empty()) {
1526                 return;
1527         }
1528
1529         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1530                 if ((*i)->placement() == p) {
1531                         (*i)->set_active (state);
1532                 }
1533         }
1534         
1535         _session.set_dirty ();
1536 }
1537
1538 struct ProcessorSorter {
1539     bool operator() (boost::shared_ptr<const Processor> a, boost::shared_ptr<const Processor> b) {
1540             return a->sort_key() < b->sort_key();
1541     }
1542 };
1543
1544 int
1545 Route::sort_processors (ProcessorStreams* err)
1546 {
1547         {
1548                 ProcessorSorter comparator;
1549                 Glib::RWLock::WriterLock lm (_processor_lock);
1550                 ChanCount old_pmo = processor_max_outs;
1551
1552                 /* the sweet power of C++ ... */
1553
1554                 ProcessorList as_it_was_before = _processors;
1555
1556                 _processors.sort (comparator);
1557         
1558                 if (_reset_processor_counts (err)) {
1559                         _processors = as_it_was_before;
1560                         processor_max_outs = old_pmo;
1561                         return -1;
1562                 } 
1563         } 
1564
1565         reset_panner ();
1566         processors_changed (); /* EMIT SIGNAL */
1567
1568         return 0;
1569 }
1570
1571 XMLNode&
1572 Route::get_state()
1573 {
1574         return state(true);
1575 }
1576
1577 XMLNode&
1578 Route::get_template()
1579 {
1580         return state(false);
1581 }
1582
1583 XMLNode&
1584 Route::state(bool full_state)
1585 {
1586         XMLNode *node = new XMLNode("Route");
1587         ProcessorList::iterator i;
1588         char buf[32];
1589
1590         if (_flags) {
1591                 node->add_property("flags", enum_2_string (_flags));
1592         }
1593         
1594         node->add_property("default-type", _default_type.to_string());
1595
1596         node->add_property("active", _active?"yes":"no");
1597         node->add_property("muted", _muted?"yes":"no");
1598         node->add_property("soloed", _soloed?"yes":"no");
1599         node->add_property("phase-invert", _phase_invert?"yes":"no");
1600         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1601         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1602         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1603         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1604         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1605
1606         if (_edit_group) {
1607                 node->add_property("edit-group", _edit_group->name());
1608         }
1609         if (_mix_group) {
1610                 node->add_property("mix-group", _mix_group->name());
1611         }
1612
1613         string order_string;
1614         OrderKeys::iterator x = order_keys.begin(); 
1615
1616         while (x != order_keys.end()) {
1617                 order_string += string ((*x).first);
1618                 order_string += '=';
1619                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1620                 order_string += buf;
1621                 
1622                 ++x;
1623
1624                 if (x == order_keys.end()) {
1625                         break;
1626                 }
1627
1628                 order_string += ':';
1629         }
1630         node->add_property ("order-keys", order_string);
1631
1632         node->add_child_nocopy (IO::state (full_state));
1633         node->add_child_nocopy (_solo_control->get_state ());
1634         node->add_child_nocopy (_mute_control->get_state ());
1635
1636         XMLNode* remote_control_node = new XMLNode (X_("remote_control"));
1637         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1638         remote_control_node->add_property (X_("id"), buf);
1639         node->add_child_nocopy (*remote_control_node);
1640
1641         if (_control_outs) {
1642                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1643                 cnode->add_child_nocopy (_control_outs->state (full_state));
1644                 node->add_child_nocopy (*cnode);
1645         }
1646
1647         if (_comment.length()) {
1648                 XMLNode *cmt = node->add_child ("Comment");
1649                 cmt->add_content (_comment);
1650         }
1651
1652         for (i = _processors.begin(); i != _processors.end(); ++i) {
1653                 node->add_child_nocopy((*i)->state (full_state));
1654         }
1655
1656         if (_extra_xml){
1657                 node->add_child_copy (*_extra_xml);
1658         }
1659         
1660         return *node;
1661 }
1662
1663 XMLNode&
1664 Route::get_processor_state ()
1665 {
1666         XMLNode* root = new XMLNode (X_("redirects"));
1667         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1668                 root->add_child_nocopy ((*i)->state (true));
1669         }
1670
1671         return *root;
1672 }
1673
1674 int
1675 Route::set_processor_state (const XMLNode& root)
1676 {
1677         if (root.name() != X_("redirects")) {
1678                 return -1;
1679         }
1680
1681         XMLNodeList nlist;
1682         XMLNodeList nnlist;
1683         XMLNodeConstIterator iter;
1684         XMLNodeConstIterator niter;
1685         Glib::RWLock::ReaderLock lm (_processor_lock);
1686
1687         nlist = root.children();
1688         
1689         for (iter = nlist.begin(); iter != nlist.end(); ++iter){
1690
1691                 /* iter now points to a IOProcessor state node */
1692                 
1693                 nnlist = (*iter)->children ();
1694
1695                 for (niter = nnlist.begin(); niter != nnlist.end(); ++niter) {
1696
1697                         /* find the IO child node, since it contains the ID we need */
1698
1699                         /* XXX OOP encapsulation violation, ugh */
1700
1701                         if ((*niter)->name() == IO::state_node_name) {
1702
1703                                 XMLProperty* prop = (*niter)->property (X_("id"));
1704                                 
1705                                 if (!prop) {
1706                                         warning << _("IOProcessor node has no ID, ignored") << endmsg;
1707                                         break;
1708                                 }
1709
1710                                 ID id = prop->value ();
1711
1712                                 /* now look for a processor with that ID */
1713         
1714                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1715                                         if ((*i)->id() == id) {
1716                                                 (*i)->set_state (**iter);
1717                                                 break;
1718                                         }
1719                                 }
1720                                 
1721                                 break;
1722                                 
1723                         }
1724                 }
1725
1726         }
1727
1728         return 0;
1729 }
1730
1731 void
1732 Route::set_deferred_state ()
1733 {
1734         XMLNodeList nlist;
1735         XMLNodeConstIterator niter;
1736
1737         if (!deferred_state) {
1738                 return;
1739         }
1740
1741         nlist = deferred_state->children();
1742
1743         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1744                 add_processor_from_xml (**niter);
1745         }
1746
1747         delete deferred_state;
1748         deferred_state = 0;
1749 }
1750
1751 void
1752 Route::add_processor_from_xml (const XMLNode& node)
1753 {
1754         const XMLProperty *prop;
1755
1756         // legacy sessions use a different node name for sends
1757         if (node.name() == "Send") {
1758         
1759                 try {
1760                         boost::shared_ptr<Send> send (new Send (_session, node));
1761                         add_processor (send);
1762                 } 
1763                 
1764                 catch (failed_constructor &err) {
1765                         error << _("Send construction failed") << endmsg;
1766                         return;
1767                 }
1768                 
1769         // use "Processor" in XML?
1770         } else if (node.name() == "Processor") {
1771                 
1772                 try {
1773                         if ((prop = node.property ("type")) != 0) {
1774
1775                                 boost::shared_ptr<Processor> processor;
1776                                 bool have_insert = false;
1777
1778                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
1779                                     prop->value() == "lv2" ||
1780                                     prop->value() == "vst" ||
1781                                     prop->value() == "audiounit") {
1782                                         
1783                                         processor.reset (new PluginInsert(_session, node));
1784                                         have_insert = true;
1785                                         
1786                                 } else if (prop->value() == "port") {
1787
1788                                         processor.reset (new PortInsert (_session, node));
1789                                 
1790                                 } else if (prop->value() == "send") {
1791
1792                                         processor.reset (new Send (_session, node));
1793                                         have_insert = true;
1794
1795                                 } else {
1796
1797                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
1798                                 }
1799                                 
1800                                 add_processor (processor);
1801                                 
1802                         } else {
1803                                 error << _("Processor XML node has no type property") << endmsg;
1804                         }
1805                 }
1806
1807                 catch (failed_constructor &err) {
1808                         warning << _("processor could not be created. Ignored.") << endmsg;
1809                         return;
1810                 }
1811         }
1812 }
1813
1814 int
1815 Route::set_state (const XMLNode& node)
1816 {
1817         return _set_state (node, true);
1818 }
1819
1820 int
1821 Route::_set_state (const XMLNode& node, bool call_base)
1822 {
1823         XMLNodeList nlist;
1824         XMLNodeConstIterator niter;
1825         XMLNode *child;
1826         XMLPropertyList plist;
1827         const XMLProperty *prop;
1828
1829         if (node.name() != "Route"){
1830                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1831                 return -1;
1832         }
1833
1834         if ((prop = node.property (X_("flags"))) != 0) {
1835                 _flags = Flag (string_2_enum (prop->value(), _flags));
1836         } else {
1837                 _flags = Flag (0);
1838         }
1839         
1840         if ((prop = node.property (X_("default-type"))) != 0) {
1841                 _default_type = DataType(prop->value());
1842                 assert(_default_type != DataType::NIL);
1843         }
1844
1845         if ((prop = node.property (X_("phase-invert"))) != 0) {
1846                 set_phase_invert (prop->value()=="yes"?true:false, this);
1847         }
1848
1849         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1850                 set_denormal_protection (prop->value()=="yes"?true:false, this);
1851         }
1852         
1853         _active = true;
1854         if ((prop = node.property (X_("active"))) != 0) {
1855                 set_active (prop->value() == "yes");
1856         }
1857
1858         if ((prop = node.property (X_("muted"))) != 0) {
1859                 bool yn = prop->value()=="yes"?true:false; 
1860
1861                 /* force reset of mute status */
1862
1863                 _muted = !yn;
1864                 set_mute(yn, this);
1865                 mute_gain = desired_mute_gain;
1866         }
1867
1868         if ((prop = node.property (X_("soloed"))) != 0) {
1869                 bool yn = prop->value()=="yes"?true:false; 
1870
1871                 /* force reset of solo status */
1872
1873                 _soloed = !yn;
1874                 set_solo (yn, this);
1875                 solo_gain = desired_solo_gain;
1876         }
1877
1878         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1879                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1880         }
1881
1882         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1883                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1884         }
1885
1886         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1887                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1888         }
1889
1890         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1891                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1892         }
1893
1894         if ((prop = node.property (X_("edit-group"))) != 0) {
1895                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1896                 if(edit_group == 0) {
1897                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1898                 } else {
1899                         set_edit_group(edit_group, this);
1900                 }
1901         }
1902
1903         if ((prop = node.property (X_("order-keys"))) != 0) {
1904
1905                 long n;
1906
1907                 string::size_type colon, equal;
1908                 string remaining = prop->value();
1909
1910                 while (remaining.length()) {
1911
1912                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1913                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1914                                       << endmsg;
1915                         } else {
1916                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1917                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1918                                               << endmsg;
1919                                 } else {
1920                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1921                                 }
1922                         }
1923
1924                         colon = remaining.find_first_of (':');
1925
1926                         if (colon != string::npos) {
1927                                 remaining = remaining.substr (colon+1);
1928                         } else {
1929                                 break;
1930                         }
1931                 }
1932         }
1933
1934         nlist = node.children();
1935
1936         if (deferred_state) {
1937                 delete deferred_state;
1938         }
1939
1940         deferred_state = new XMLNode(X_("deferred state"));
1941
1942         /* set parent class properties before anything else */
1943
1944         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1945
1946                 child = *niter;
1947
1948                 if (child->name() == IO::state_node_name && call_base) {
1949
1950                         IO::set_state (*child);
1951                         break;
1952                 }
1953         }
1954
1955         XMLNodeList processor_nodes;
1956                         
1957         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1958
1959                 child = *niter;
1960                         
1961                 if (child->name() == X_("Send") || child->name() == X_("Processor")) {
1962                         processor_nodes.push_back(child);
1963                 }
1964
1965         }
1966
1967         _set_processor_states(processor_nodes);
1968
1969
1970         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1971                 child = *niter;
1972                 // All processors have been applied already
1973
1974                 if (child->name() == X_("Automation")) {
1975                         
1976                         if ((prop = child->property (X_("path"))) != 0)  {
1977                                 load_automation (prop->value());
1978                         }
1979
1980                 } else if (child->name() == X_("ControlOuts")) {
1981                         
1982                         string coutname = _name;
1983                         coutname += _("[control]");
1984
1985                         _control_outs = new IO (_session, coutname);
1986                         _control_outs->set_state (**(child->children().begin()));
1987
1988                 } else if (child->name() == X_("Comment")) {
1989
1990                         /* XXX this is a terrible API design in libxml++ */
1991
1992                         XMLNode *cmt = *(child->children().begin());
1993                         _comment = cmt->content();
1994
1995                 } else if (child->name() == X_("extra")) {
1996
1997                         _extra_xml = new XMLNode (*child);
1998
1999                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
2000                         
2001                         if (prop->value() == "solo") {
2002                                 _solo_control->set_state (*child);
2003                                 _session.add_controllable (_solo_control);
2004                         }
2005                         else if (prop->value() == "mute") {
2006                                 _mute_control->set_state (*child);
2007                                 _session.add_controllable (_mute_control);
2008                         }
2009                 }
2010                 else if (child->name() == X_("remote_control")) {
2011                         if ((prop = child->property (X_("id"))) != 0) {
2012                                 int32_t x;
2013                                 sscanf (prop->value().c_str(), "%d", &x);
2014                                 set_remote_control_id (x);
2015                         }
2016                 }
2017         }
2018
2019         if ((prop = node.property (X_("mix-group"))) != 0) {
2020                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
2021                 if (mix_group == 0) {
2022                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
2023                 }  else {
2024                         set_mix_group(mix_group, this);
2025                 }
2026         }
2027
2028         return 0;
2029 }
2030
2031 void
2032 Route::_set_processor_states(const XMLNodeList &nlist)
2033 {
2034         XMLNodeConstIterator niter;
2035         char buf[64];
2036
2037         ProcessorList::iterator i, o;
2038
2039         // Iterate through existing processors, remove those which are not in the state list
2040         for (i = _processors.begin(); i != _processors.end(); ) {
2041                 ProcessorList::iterator tmp = i;
2042                 ++tmp;
2043
2044                 bool processorInStateList = false;
2045         
2046                 (*i)->id().print (buf, sizeof (buf));
2047
2048
2049                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2050
2051                         // legacy sessions (IOProcessor as a child of Processor, both is-a IO)
2052                         if (strncmp(buf,(*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
2053                                 processorInStateList = true;
2054                                 break;
2055                         } else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
2056                                 processorInStateList = true;
2057                                 break;
2058                         }
2059                 }
2060                 
2061                 if (!processorInStateList) {
2062                         remove_processor (*i);
2063                 }
2064
2065
2066                 i = tmp;
2067         }
2068
2069
2070         // Iterate through state list and make sure all processors are on the track and in the correct order,
2071         // set the state of existing processors according to the new state on the same go
2072         i = _processors.begin();
2073         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
2074
2075                 // Check whether the next processor in the list 
2076                 o = i;
2077
2078                 while (o != _processors.end()) {
2079                         (*o)->id().print (buf, sizeof (buf));
2080                         if ( strncmp(buf, (*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
2081                                 break;
2082                         else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
2083                                 break;
2084                         
2085                         ++o;
2086                 }
2087
2088                 if (o == _processors.end()) {
2089                         // If the processor (*niter) is not on the route, we need to create it
2090                         // and move it to the correct location
2091
2092                         ProcessorList::iterator prev_last = _processors.end();
2093                         --prev_last; // We need this to check whether adding succeeded
2094                         
2095                         add_processor_from_xml (**niter);
2096
2097                         ProcessorList::iterator last = _processors.end();
2098                         --last;
2099
2100                         if (prev_last == last) {
2101                                 cerr << "Could not fully restore state as some processors were not possible to create" << endl;
2102                                 continue;
2103
2104                         }
2105
2106                         boost::shared_ptr<Processor> tmp = (*last);
2107                         // remove the processor from the wrong location
2108                         _processors.erase(last);
2109                         // processor the new processor at the current location
2110                         _processors.insert(i, tmp);
2111
2112                         --i; // move pointer to the newly processored processor
2113                         continue;
2114                 }
2115
2116                 // We found the processor (*niter) on the route, first we must make sure the processor
2117                 // is at the location provided in the XML state
2118                 if (i != o) {
2119                         boost::shared_ptr<Processor> tmp = (*o);
2120                         // remove the old copy
2121                         _processors.erase(o);
2122                         // processor the processor at the correct location
2123                         _processors.insert(i, tmp);
2124
2125                         --i; // move pointer so it points to the right processor
2126                 }
2127
2128                 (*i)->set_state( (**niter) );
2129         }
2130         
2131         processors_changed ();
2132 }
2133
2134 void
2135 Route::curve_reallocate ()
2136 {
2137 //      _gain_automation_curve.finish_resize ();
2138 //      _pan_automation_curve.finish_resize ();
2139 }
2140
2141 void
2142 Route::silence (nframes_t nframes, nframes_t offset)
2143 {
2144         if (!_silent) {
2145
2146                 IO::silence (nframes, offset);
2147
2148                 if (_control_outs) {
2149                         _control_outs->silence (nframes, offset);
2150                 }
2151
2152                 { 
2153                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2154                         
2155                         if (lm.locked()) {
2156                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2157                                         boost::shared_ptr<PluginInsert> pi;
2158                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2159                                                 // skip plugins, they don't need anything when we're not active
2160                                                 continue;
2161                                         }
2162
2163                                         (*i)->silence (nframes, offset);
2164                                 }
2165
2166                                 if (nframes == _session.get_block_size() && offset == 0) {
2167                                         // _silent = true;
2168                                 }
2169                         }
2170                 }
2171                 
2172         }
2173 }       
2174
2175 int
2176 Route::set_control_outs (const vector<string>& ports)
2177 {
2178         Glib::Mutex::Lock lm (_control_outs_lock);
2179         vector<string>::const_iterator i;
2180         size_t limit;
2181         
2182         if (_control_outs) {
2183                 delete _control_outs;
2184                 _control_outs = 0;
2185         }
2186
2187         if (is_control() || is_master()) {
2188                 /* no control outs for these two special busses */
2189                 return 0;
2190         }
2191         
2192         if (ports.empty()) {
2193                 return 0;
2194         }
2195  
2196         string coutname = _name;
2197         coutname += _("[control]");
2198         
2199         _control_outs = new IO (_session, coutname);
2200
2201         /* our control outs need as many outputs as we
2202            have audio outputs. we track the changes in ::output_change_handler().
2203         */
2204         
2205         // XXX its stupid that we have to get this value twice
2206
2207         limit = n_outputs().n_audio();
2208         
2209         if (_control_outs->ensure_io (ChanCount::ZERO, ChanCount (DataType::AUDIO, n_outputs().get (DataType::AUDIO)), true, this)) {
2210                 return -1;
2211         }
2212         
2213         /* now connect to the named ports */
2214         
2215         for (size_t n = 0; n < limit; ++n) {
2216                 if (_control_outs->connect_output (_control_outs->output (n), ports[n % ports.size()], this)) {
2217                         error << string_compose (_("could not connect %1 to %2"), _control_outs->output(n)->name(), ports[n]) << endmsg;
2218                         return -1;
2219                 }
2220         }
2221  
2222         return 0;
2223 }       
2224
2225 void
2226 Route::set_edit_group (RouteGroup *eg, void *src)
2227
2228 {
2229         if (eg == _edit_group) {
2230                 return;
2231         }
2232
2233         if (_edit_group) {
2234                 _edit_group->remove (this);
2235         }
2236
2237         if ((_edit_group = eg) != 0) {
2238                 _edit_group->add (this);
2239         }
2240
2241         _session.set_dirty ();
2242         edit_group_changed (src); /* EMIT SIGNAL */
2243 }
2244
2245 void
2246 Route::drop_edit_group (void *src)
2247 {
2248         _edit_group = 0;
2249         _session.set_dirty ();
2250         edit_group_changed (src); /* EMIT SIGNAL */
2251 }
2252
2253 void
2254 Route::set_mix_group (RouteGroup *mg, void *src)
2255
2256 {
2257         if (mg == _mix_group) {
2258                 return;
2259         }
2260
2261         if (_mix_group) {
2262                 _mix_group->remove (this);
2263         }
2264
2265         if ((_mix_group = mg) != 0) {
2266                 _mix_group->add (this);
2267         }
2268
2269         _session.set_dirty ();
2270         mix_group_changed (src); /* EMIT SIGNAL */
2271 }
2272
2273 void
2274 Route::drop_mix_group (void *src)
2275 {
2276         _mix_group = 0;
2277         _session.set_dirty ();
2278         mix_group_changed (src); /* EMIT SIGNAL */
2279 }
2280
2281 void
2282 Route::set_comment (string cmt, void *src)
2283 {
2284         _comment = cmt;
2285         comment_changed (src);
2286         _session.set_dirty ();
2287 }
2288
2289 bool
2290 Route::feeds (boost::shared_ptr<Route> other)
2291 {
2292         uint32_t i, j;
2293
2294         IO& self = *this;
2295         uint32_t no = self.n_outputs().n_total();
2296         uint32_t ni = other->n_inputs ().n_total();
2297
2298         for (i = 0; i < no; ++i) {
2299                 for (j = 0; j < ni; ++j) {
2300                         if (self.output(i)->connected_to (other->input(j)->name())) {
2301                                 return true;
2302                         }
2303                 }
2304         }
2305
2306         /* check IOProcessors which may also interconnect Routes */
2307
2308         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2309
2310                 boost::shared_ptr<IOProcessor> redirect = boost::dynamic_pointer_cast<IOProcessor>(*r);
2311
2312                 if ( ! redirect)
2313                         continue;
2314
2315                 // TODO: support internal redirects here
2316
2317                 no = redirect->io()->n_outputs().n_total();
2318
2319                 for (i = 0; i < no; ++i) {
2320                         for (j = 0; j < ni; ++j) {
2321                                 if (redirect->io()->output(i)->connected_to (other->input (j)->name())) {
2322                                         return true;
2323                                 }
2324                         }
2325                 }
2326         }
2327
2328         /* check for control room outputs which may also interconnect Routes */
2329
2330         if (_control_outs) {
2331
2332                 no = _control_outs->n_outputs().n_total();
2333                 
2334                 for (i = 0; i < no; ++i) {
2335                         for (j = 0; j < ni; ++j) {
2336                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
2337                                         return true;
2338                                 }
2339                         }
2340                 }
2341         }
2342
2343         return false;
2344 }
2345
2346 void
2347 Route::set_mute_config (mute_type t, bool onoff, void *src)
2348 {
2349         switch (t) {
2350         case PRE_FADER:
2351                 _mute_affects_pre_fader = onoff;
2352                  pre_fader_changed(src); /* EMIT SIGNAL */
2353                 break;
2354
2355         case POST_FADER:
2356                 _mute_affects_post_fader = onoff;
2357                  post_fader_changed(src); /* EMIT SIGNAL */
2358                 break;
2359
2360         case CONTROL_OUTS:
2361                 _mute_affects_control_outs = onoff;
2362                  control_outs_changed(src); /* EMIT SIGNAL */
2363                 break;
2364
2365         case MAIN_OUTS:
2366                 _mute_affects_main_outs = onoff;
2367                  main_outs_changed(src); /* EMIT SIGNAL */
2368                 break;
2369         }
2370 }
2371
2372 bool
2373 Route::get_mute_config (mute_type t)
2374 {
2375         bool onoff = false;
2376         
2377         switch (t){
2378         case PRE_FADER:
2379                 onoff = _mute_affects_pre_fader; 
2380                 break;
2381         case POST_FADER:
2382                 onoff = _mute_affects_post_fader;
2383                 break;
2384         case CONTROL_OUTS:
2385                 onoff = _mute_affects_control_outs;
2386                 break;
2387         case MAIN_OUTS:
2388                 onoff = _mute_affects_main_outs;
2389                 break;
2390         }
2391         
2392         return onoff;
2393 }
2394
2395 void
2396 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
2397 {
2398         nframes_t now = _session.transport_frame();
2399
2400         {
2401                 Glib::RWLock::ReaderLock lm (_processor_lock);
2402
2403                 if (!did_locate) {
2404                         automation_snapshot (now, true);
2405                 }
2406
2407                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2408                         
2409                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2410                                 (*i)->deactivate ();
2411                                 (*i)->activate ();
2412                         }
2413                         
2414                         (*i)->transport_stopped (now);
2415                 }
2416         }
2417
2418         IO::transport_stopped (now);
2419  
2420         _roll_delay = _initial_delay;
2421 }
2422
2423 void
2424 Route::input_change_handler (IOChange change, void *ignored)
2425 {
2426         if (change & ConfigurationChanged) {
2427                 reset_processor_counts (0);
2428         }
2429 }
2430
2431 void
2432 Route::output_change_handler (IOChange change, void *ignored)
2433 {
2434         if (change & ConfigurationChanged) {
2435                 if (_control_outs) {
2436                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().n_audio()), true, this);
2437                 }
2438                 
2439                 reset_processor_counts (0);
2440         }
2441 }
2442
2443 uint32_t
2444 Route::pans_required () const
2445 {
2446         if (n_outputs().n_audio() < 2) {
2447                 return 0;
2448         }
2449         
2450         return max (n_inputs ().n_audio(), processor_max_outs.n_audio());
2451 }
2452
2453 int 
2454 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2455                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2456 {
2457         if (n_outputs().n_total() == 0) {
2458                 return 0;
2459         }
2460
2461         if (session_state_changing || !_active)  {
2462                 silence (nframes, offset);
2463                 return 0;
2464         }
2465
2466         apply_gain_automation = false;
2467         
2468         if (n_inputs().n_total()) {
2469                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2470         } else {
2471                 silence (nframes, offset);
2472         }
2473
2474         return 0;
2475 }
2476
2477 nframes_t
2478 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2479 {
2480         if (_roll_delay > nframes) {
2481
2482                 _roll_delay -= nframes;
2483                 silence (nframes, offset);
2484                 /* transport frame is not legal for caller to use */
2485                 return 0;
2486
2487         } else if (_roll_delay > 0) {
2488
2489                 nframes -= _roll_delay;
2490
2491                 silence (_roll_delay, offset);
2492
2493                 offset += _roll_delay;
2494                 transport_frame += _roll_delay;
2495
2496                 _roll_delay = 0;
2497         }
2498
2499         return nframes;
2500 }
2501
2502 int
2503 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2504              bool can_record, bool rec_monitors_input)
2505 {
2506         {
2507                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2508                 if (lm.locked()) {
2509                         // automation snapshot can also be called from the non-rt context
2510                         // and it uses the processor list, so we take the lock out here
2511                         automation_snapshot (_session.transport_frame(), false);
2512                 }
2513         }
2514
2515         if ((n_outputs().n_total() == 0 && _processors.empty()) || n_inputs().n_total() == 0 || !_active) {
2516                 silence (nframes, offset);
2517                 return 0;
2518         }
2519         
2520         nframes_t unused = 0;
2521
2522         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2523                 return 0;
2524         }
2525
2526         _silent = false;
2527
2528         apply_gain_automation = false;
2529
2530         { 
2531                 Glib::Mutex::Lock am (data().control_lock(), Glib::TRY_LOCK);
2532                 
2533                 if (am.locked() && _session.transport_rolling()) {
2534                         
2535                         if (_gain_control->alist()->automation_playback()) {
2536                                 apply_gain_automation = _gain_control->list()->curve().rt_safe_get_vector (
2537                                                 start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2538                         }
2539                 }
2540         }
2541
2542         passthru (start_frame, end_frame, nframes, offset, declick, false);
2543
2544         return 0;
2545 }
2546
2547 int
2548 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2549                     bool can_record, bool rec_monitors_input)
2550 {
2551         silence (nframes, offset);
2552         return 0;
2553 }
2554
2555 void
2556 Route::toggle_monitor_input ()
2557 {
2558         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2559                 i->ensure_monitor_input( ! i->monitoring_input());
2560         }
2561 }
2562
2563 bool
2564 Route::has_external_redirects () const
2565 {
2566         // FIXME: what about sends?
2567
2568         boost::shared_ptr<const PortInsert> pi;
2569         
2570         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2571                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2572
2573                         for (PortSet::const_iterator port = pi->io()->outputs().begin();
2574                                         port != pi->io()->outputs().end(); ++port) {
2575                                 
2576                                 string port_name = port->name();
2577                                 string client_name = port_name.substr (0, port_name.find(':'));
2578
2579                                 /* only say "yes" if the redirect is actually in use */
2580                                 
2581                                 if (client_name != "ardour" && pi->active()) {
2582                                         return true;
2583                                 }
2584                         }
2585                 }
2586         }
2587
2588         return false;
2589 }
2590
2591 void
2592 Route::flush_processors ()
2593 {
2594         /* XXX shouldn't really try to take this lock, since
2595            this is called from the RT audio thread.
2596         */
2597
2598         Glib::RWLock::ReaderLock lm (_processor_lock);
2599
2600         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2601                 (*i)->deactivate ();
2602                 (*i)->activate ();
2603         }
2604 }
2605
2606 void
2607 Route::set_meter_point (MeterPoint p, void *src)
2608 {
2609         if (_meter_point != p) {
2610                 _meter_point = p;
2611                  meter_change (src); /* EMIT SIGNAL */
2612                 _session.set_dirty ();
2613         }
2614 }
2615
2616 nframes_t
2617 Route::update_total_latency ()
2618 {
2619         nframes_t old = _own_latency;
2620
2621         if (_user_latency) {
2622                 _own_latency = _user_latency;
2623         } else {
2624                 _own_latency = 0;
2625
2626                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2627                         if ((*i)->active ()) {
2628                                 _own_latency += (*i)->signal_latency ();
2629                         }
2630                 }
2631         }
2632
2633 #undef DEBUG_LATENCY
2634 #ifdef DEBUG_LATENCY
2635         cerr << _name << ": internal redirect latency = " << _own_latency << endl;
2636 #endif
2637
2638         set_port_latency (_own_latency);
2639         
2640         if (!_user_latency) {
2641                 /* this (virtual) function is used for pure Routes,
2642                    not derived classes like AudioTrack.  this means
2643                    that the data processed here comes from an input
2644                    port, not prerecorded material, and therefore we
2645                    have to take into account any input latency.
2646                 */
2647
2648
2649                 _own_latency += input_latency ();
2650         }
2651
2652         if (old != _own_latency) {
2653                 signal_latency_changed (); /* EMIT SIGNAL */
2654         }
2655         
2656 #ifdef DEBUG_LATENCY
2657         cerr << _name << ": input latency = " << input_latency() << " total = "
2658              << _own_latency << endl;
2659 #endif
2660
2661         return _own_latency;
2662 }
2663
2664 void
2665 Route::set_user_latency (nframes_t nframes)
2666 {
2667         Latent::set_user_latency (nframes);
2668         _session.update_latency_compensation (false, false);
2669 }
2670
2671 void
2672 Route::set_latency_delay (nframes_t longest_session_latency)
2673 {
2674         nframes_t old = _initial_delay;
2675
2676         if (_own_latency < longest_session_latency) {
2677                 _initial_delay = longest_session_latency - _own_latency;
2678         } else {
2679                 _initial_delay = 0;
2680         }
2681
2682         if (_initial_delay != old) {
2683                 initial_delay_changed (); /* EMIT SIGNAL */
2684         }
2685
2686         if (_session.transport_stopped()) {
2687                 _roll_delay = _initial_delay;
2688         }
2689 }
2690
2691 void
2692 Route::automation_snapshot (nframes_t now, bool force)
2693 {
2694         if (!force && !should_snapshot(now)) {
2695                 return;
2696         }
2697
2698         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2699                 // IO::automation_snapshot (now, force);  ?
2700                 (*i)->automation_snapshot (now, force);
2701         }
2702 }
2703
2704 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2705         : Controllable (name), route (s), type(tp)
2706 {
2707         
2708 }
2709
2710 void
2711 Route::ToggleControllable::set_value (float val)
2712 {
2713         bool bval = ((val >= 0.5f) ? true: false);
2714         
2715         switch (type) {
2716         case MuteControl:
2717                 route.set_mute (bval, this);
2718                 break;
2719         case SoloControl:
2720                 route.set_solo (bval, this);
2721                 break;
2722         default:
2723                 break;
2724         }
2725 }
2726
2727 float
2728 Route::ToggleControllable::get_value (void) const
2729 {
2730         float val = 0.0f;
2731         
2732         switch (type) {
2733         case MuteControl:
2734                 val = route.muted() ? 1.0f : 0.0f;
2735                 break;
2736         case SoloControl:
2737                 val = route.soloed() ? 1.0f : 0.0f;
2738                 break;
2739         default:
2740                 break;
2741         }
2742
2743         return val;
2744 }
2745
2746 void 
2747 Route::set_block_size (nframes_t nframes)
2748 {
2749         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2750                 (*i)->set_block_size (nframes);
2751         }
2752 }
2753
2754 void
2755 Route::protect_automation ()
2756 {
2757         Automatable::protect_automation();
2758         
2759         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2760                 (*i)->protect_automation();
2761 }
2762
2763 void
2764 Route::set_pending_declick (int declick)
2765 {
2766         if (_declickable) {
2767                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2768                 if (declick) {
2769                         _pending_declick = declick;
2770                 }
2771                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2772         } else {
2773                 _pending_declick = 0;
2774         }
2775
2776 }