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