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