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