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