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