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