dramatic change in logic and naming for operations related to adding a MIDI region...
[ardour.git] / libs / ardour / session.cc
1 /*
2     Copyright (C) 1999-2010 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 <stdint.h>
21
22 #include <algorithm>
23 #include <string>
24 #include <vector>
25 #include <sstream>
26 #include <fstream>
27 #include <cstdio> /* sprintf(3) ... grrr */
28 #include <cmath>
29 #include <cerrno>
30 #include <unistd.h>
31 #include <limits.h>
32
33 #include <glibmm/threads.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
36
37 #include <boost/algorithm/string/erase.hpp>
38
39 #include "pbd/error.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/strsplit.h"
48 #include "pbd/unwind.h"
49
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/midi_ui.h"
73 #include "ardour/operations.h"
74 #include "ardour/playlist.h"
75 #include "ardour/plugin.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/rc_configuration.h"
79 #include "ardour/recent_sessions.h"
80 #include "ardour/region.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/route_graph.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_playlists.h"
88 #include "ardour/smf_source.h"
89 #include "ardour/source_factory.h"
90 #include "ardour/speakers.h"
91 #include "ardour/track.h"
92 #include "ardour/utils.h"
93
94 #include "midi++/port.h"
95 #include "midi++/mmc.h"
96
97 #include "i18n.h"
98
99 namespace ARDOUR {
100 class MidiSource;
101 class Processor;
102 class Speakers;
103 }
104
105 using namespace std;
106 using namespace ARDOUR;
107 using namespace PBD;
108
109 bool Session::_disable_all_loaded_plugins = false;
110
111 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
112 PBD::Signal1<void,std::string> Session::Dialog;
113 PBD::Signal0<int> Session::AskAboutPendingState;
114 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
115 PBD::Signal0<void> Session::SendFeedback;
116 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
117
118 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
119 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
120 PBD::Signal2<void,std::string, std::string> Session::Exported;
121 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
122 PBD::Signal0<void> Session::Quit;
123 PBD::Signal0<void> Session::FeedbackDetected;
124 PBD::Signal0<void> Session::SuccessfulGraphSort;
125 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
126
127 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
128 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
129
130 /** @param snapshot_name Snapshot name, without .ardour suffix */
131 Session::Session (AudioEngine &eng,
132                   const string& fullpath,
133                   const string& snapshot_name,
134                   BusProfile* bus_profile,
135                   string mix_template)
136         : playlists (new SessionPlaylists)
137         , _engine (eng)
138         , process_function (&Session::process_with_events)
139         , waiting_for_sync_offset (false)
140         , _base_frame_rate (0)
141         , _current_frame_rate (0)
142         , _nominal_frame_rate (0)
143         , transport_sub_state (0)
144         , _record_status (Disabled)
145         , _transport_frame (0)
146         , _session_range_location (0)
147         , _slave (0)
148         , _silent (false)
149         , _transport_speed (0)
150         , _default_transport_speed (1.0)
151         , _last_transport_speed (0)
152         , _target_transport_speed (0.0)
153         , auto_play_legal (false)
154         , _last_slave_transport_frame (0)
155         , maximum_output_latency (0)
156         , _requested_return_frame (-1)
157         , current_block_size (0)
158         , _worst_output_latency (0)
159         , _worst_input_latency (0)
160         , _worst_track_latency (0)
161         , _have_captured (false)
162         , _meter_hold (0)
163         , _meter_falloff (0)
164         , _non_soloed_outs_muted (false)
165         , _listen_cnt (0)
166         , _solo_isolated_cnt (0)
167         , _writable (false)
168         , _was_seamless (Config->get_seamless_loop ())
169         , _under_nsm_control (false)
170         , delta_accumulator_cnt (0)
171         , average_slave_delta (1800) // !!! why 1800 ???
172         , average_dir (0)
173         , have_first_delta_accumulator (false)
174         , _slave_state (Stopped)
175         , post_export_sync (false)
176         , post_export_position (0)
177         , _exporting (false)
178         , _export_started (false)
179         , _export_rolling (false)
180         , _pre_export_mmc_enabled (false)
181         , _name (snapshot_name)
182         , _is_new (true)
183         , _send_qf_mtc (false)
184         , _pframes_since_last_mtc (0)
185         , session_midi_feedback (0)
186         , play_loop (false)
187         , loop_changing (false)
188         , last_loopend (0)
189         , _session_dir (new SessionDirectory (fullpath))
190         , _current_snapshot_name (snapshot_name)          
191         , state_tree (0)
192         , state_was_pending (false)
193         , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
194         , _last_roll_location (0)
195         , _last_roll_or_reversal_location (0)
196         , _last_record_location (0)
197         , pending_locate_roll (false)
198         , pending_locate_frame (0)
199         , pending_locate_flush (false)
200         , pending_abort (false)
201         , pending_auto_loop (false)
202         , _butler (new Butler (*this))
203         , _post_transport_work (0)
204         ,  cumulative_rf_motion (0)
205         , rf_scale (1.0)
206         , _locations (new Locations (*this))
207         , step_speed (0)
208         , outbound_mtc_timecode_frame (0)
209         , next_quarter_frame_to_send (-1)
210         , _frames_per_timecode_frame (0)
211         , _frames_per_hour (0)
212         , _timecode_frames_per_hour (0)
213         , last_timecode_valid (false)
214         , last_timecode_when (0)
215         , _send_timecode_update (false)
216         , ltc_encoder (0)
217         , ltc_enc_buf(0)
218         , ltc_buf_off (0)
219         , ltc_buf_len (0)
220         , ltc_speed (0)
221         , ltc_enc_byte (0)
222         , ltc_enc_pos (0)
223         , ltc_enc_cnt (0)
224         , ltc_enc_off (0)
225         , restarting (false)
226         , ltc_prev_cycle (0)
227         , ltc_timecode_offset (0)
228         , ltc_timecode_negative_offset (false)
229         , midi_control_ui (0)
230         , _tempo_map (0)
231         , _all_route_group (new RouteGroup (*this, "all"))
232         , routes (new RouteList)
233         , _adding_routes_in_progress (false)
234         , destructive_index (0)
235         , solo_update_disabled (false)
236         , default_fade_steepness (0)
237         , default_fade_msecs (0)
238         , _total_free_4k_blocks (0)
239         , _total_free_4k_blocks_uncertain (false)
240         , no_questions_about_missing_files (false)
241         , _playback_load (0)
242         , _capture_load (0)
243         , _bundles (new BundleList)
244         , _bundle_xml_node (0)
245         , _current_trans (0)
246         , _clicking (false)
247         , click_data (0)
248         , click_emphasis_data (0)
249         , click_length (0)
250         , click_emphasis_length (0)
251         , _clicks_cleared (0)
252         , _play_range (false)
253         , main_outs (0)
254         , first_file_data_format_reset (true)
255         , first_file_header_format_reset (true)
256         , have_looped (false)
257         , _have_rec_enabled_track (false)
258         , _step_editors (0)
259         , _suspend_timecode_transmission (0)
260         ,  _speakers (new Speakers)
261         , _order_hint (0)
262         , ignore_route_processor_changes (false)
263         , _midi_ports (0)
264         , _mmc (0)
265 {
266         uint32_t sr = 0;
267
268         pre_engine_init (fullpath);
269         
270         if (_is_new) {
271                 if (ensure_engine (sr)) {
272                         destroy ();
273                         throw failed_constructor ();
274                 }
275
276                 if (create (mix_template, bus_profile)) {
277                         destroy ();
278                         throw failed_constructor ();
279                 }
280
281                 /* if a mix template was provided, then ::create() will
282                  * have copied it into the session and we need to load it
283                  * so that we have the state ready for ::set_state()
284                  * after the engine is started.
285                  *
286                  * Note that we do NOT try to get the sample rate from
287                  * the template at this time, though doing so would
288                  * be easy if we decided this was an appropriate part
289                  * of a template.
290                  */
291
292                 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
293                         throw failed_constructor ();
294                 }
295
296         } else {
297
298                 if (load_state (_current_snapshot_name)) {
299                         throw failed_constructor ();
300                 }
301         
302                 /* try to get sample rate from XML state so that we
303                  * can influence the SR if we set up the audio
304                  * engine.
305                  */
306
307                 if (state_tree) {
308                         const XMLProperty* prop;
309                         if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {           
310                                 sr = atoi (prop->value());
311                         }
312                 }
313
314                 if (ensure_engine (sr)) {
315                         destroy ();
316                         throw failed_constructor ();
317                 }
318         }
319
320         if (post_engine_init ()) {
321                 destroy ();
322                 throw failed_constructor ();
323         }
324
325         store_recent_sessions (_name, _path);
326
327         bool was_dirty = dirty();
328
329         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
330
331         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
332         config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
333
334         if (was_dirty) {
335                 DirtyChanged (); /* EMIT SIGNAL */
336         }
337
338         StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
339         EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
340
341         _is_new = false;
342
343         /* hook us up to the engine since we are now completely constructed */
344
345         BootMessage (_("Connect to engine"));
346
347         _engine.set_session (this);
348         _engine.reset_timebase ();
349
350         BootMessage (_("Session loading complete"));
351
352 }
353
354 Session::~Session ()
355 {
356 #ifdef PT_TIMING        
357         ST.dump ("ST.dump");
358 #endif  
359         destroy ();
360 }
361
362 int
363 Session::ensure_engine (uint32_t desired_sample_rate)
364 {
365         if (_engine.current_backend() == 0) {
366                 /* backend is unknown ... */
367                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
368                 if (r.get_value_or (-1) != 0) {
369                         return -1;
370                 }
371         } else if (_engine.setup_required()) {
372                 /* backend is known, but setup is needed */
373                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
374                 if (r.get_value_or (-1) != 0) {
375                         return -1;
376                 }
377         } else if (!_engine.running()) {
378                 if (_engine.start()) {
379                         return -1;
380                 }
381         }
382
383         /* at this point the engine should be running
384         */
385
386         if (!_engine.running()) {
387                 return -1;
388         }
389
390         return immediately_post_engine ();
391
392 }
393
394 int
395 Session::immediately_post_engine ()
396 {
397         /* Do various initializations that should take place directly after we
398          * know that the engine is running, but before we either create a
399          * session or set state for an existing one.
400          */
401          
402         if (how_many_dsp_threads () > 1) {
403                 /* For now, only create the graph if we are using >1 DSP threads, as
404                    it is a bit slower than the old code with 1 thread.
405                 */
406                 _process_graph.reset (new Graph (*this));
407         }
408
409         /* every time we reconnect, recompute worst case output latencies */
410
411         _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
412
413         if (synced_to_engine()) {
414                 _engine.transport_stop ();
415         }
416
417         if (config.get_jack_time_master()) {
418                 _engine.transport_locate (_transport_frame);
419         }
420
421         try {
422                 BootMessage (_("Set up LTC"));
423                 setup_ltc ();
424                 BootMessage (_("Set up Click"));
425                 setup_click ();
426                 BootMessage (_("Set up standard connections"));
427                 setup_bundles ();
428         }
429
430         catch (failed_constructor& err) {
431                 return -1;
432         }
433
434         return 0;
435 }
436
437 void
438 Session::destroy ()
439 {
440         vector<void*> debug_pointers;
441
442         /* if we got to here, leaving pending capture state around
443            is a mistake.
444         */
445
446         remove_pending_capture_state ();
447
448         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
449
450         /* disconnect from any and all signals that we are connected to */
451
452         drop_connections ();
453
454         _engine.remove_session ();
455
456         /* deregister all ports - there will be no process or any other
457          * callbacks from the engine any more.
458          */
459
460         Port::PortDrop (); /* EMIT SIGNAL */
461
462         ltc_tx_cleanup();
463
464         /* clear history so that no references to objects are held any more */
465
466         _history.clear ();
467
468         /* clear state tree so that no references to objects are held any more */
469
470         delete state_tree;
471
472         /* reset dynamic state version back to default */
473
474         Stateful::loading_state_version = 0;
475
476         _butler->drop_references ();
477         delete _butler;
478         _butler = 0;
479         
480         delete midi_control_ui;
481         delete _all_route_group;
482
483         if (click_data != default_click) {
484                 delete [] click_data;
485         }
486
487         if (click_emphasis_data != default_click_emphasis) {
488                 delete [] click_emphasis_data;
489         }
490
491         clear_clicks ();
492
493         /* clear out any pending dead wood from RCU managed objects */
494
495         routes.flush ();
496         _bundles.flush ();
497
498         AudioDiskstream::free_working_buffers();
499
500         /* tell everyone who is still standing that we're about to die */
501         drop_references ();
502
503         /* tell everyone to drop references and delete objects as we go */
504
505         DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
506         RegionFactory::delete_all_regions ();
507
508         DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
509
510         /* reset these three references to special routes before we do the usual route delete thing */
511
512         auditioner.reset ();
513         _master_out.reset ();
514         _monitor_out.reset ();
515
516         {
517                 RCUWriter<RouteList> writer (routes);
518                 boost::shared_ptr<RouteList> r = writer.get_copy ();
519
520                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
521                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
522                         (*i)->drop_references ();
523                 }
524
525                 r->clear ();
526                 /* writer goes out of scope and updates master */
527         }
528         routes.flush ();
529
530         {
531                 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
532                 Glib::Threads::Mutex::Lock lm (source_lock);
533                 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
534                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
535                         i->second->drop_references ();
536                 }
537
538                 sources.clear ();
539         }
540
541         DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
542         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
543
544                 delete *i;
545         }
546
547         /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
548         playlists.reset ();
549
550         delete _mmc; _mmc = 0;
551         delete _midi_ports; _midi_ports = 0;
552         delete _locations; _locations = 0;
553
554         DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
555
556 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
557         boost_debug_list_ptrs ();
558 #endif
559 }
560
561 void
562 Session::setup_ltc ()
563 {
564         XMLNode* child = 0;
565         
566         _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
567         _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
568         
569         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
570                 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
571         } else {
572                 {
573                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
574                         _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
575                 }
576                 reconnect_ltc_input ();
577         }
578         
579         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
580                 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
581         } else {
582                 {
583                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
584                         _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
585                 }
586                 reconnect_ltc_output ();
587         }
588         
589         /* fix up names of LTC ports because we don't want the normal
590          * IO style of NAME/TYPE-{in,out}N
591          */
592         
593         _ltc_input->nth (0)->set_name (X_("LTC-in"));
594         _ltc_output->nth (0)->set_name (X_("LTC-out"));
595 }
596
597 void
598 Session::setup_click ()
599 {
600         _clicking = false;
601         _click_io.reset (new ClickIO (*this, X_("Click")));
602         _click_gain.reset (new Amp (*this));
603         _click_gain->activate ();
604         if (state_tree) {
605                 setup_click_state (state_tree->root());
606         } else {
607                 setup_click_state (0);
608         }
609 }
610
611 void
612 Session::setup_click_state (const XMLNode* node)
613 {       
614         const XMLNode* child = 0;
615         
616         if (node && (child = find_named_node (*node, "Click")) != 0) {
617                 
618                 /* existing state for Click */
619                 int c = 0;
620
621                 if (Stateful::loading_state_version < 3000) {
622                         c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
623                 } else {
624                         const XMLNodeList& children (child->children());
625                         XMLNodeList::const_iterator i = children.begin();
626                         if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
627                                 ++i;
628                                 if (i != children.end()) {
629                                         c = _click_gain->set_state (**i, Stateful::loading_state_version);
630                                 }
631                         }
632                 }
633                         
634                 if (c == 0) {
635                         _clicking = Config->get_clicking ();
636
637                 } else {
638
639                         error << _("could not setup Click I/O") << endmsg;
640                         _clicking = false;
641                 }
642
643
644         } else {
645
646                 /* default state for Click: dual-mono to first 2 physical outputs */
647
648                 vector<string> outs;
649                 _engine.get_physical_outputs (DataType::AUDIO, outs);
650
651                 for (uint32_t physport = 0; physport < 2; ++physport) {
652                         if (outs.size() > physport) {
653                                 if (_click_io->add_port (outs[physport], this)) {
654                                         // relax, even though its an error
655                                 }
656                         }
657                 }
658
659                 if (_click_io->n_ports () > ChanCount::ZERO) {
660                         _clicking = Config->get_clicking ();
661                 }
662         }
663 }
664
665 void
666 Session::setup_bundles ()
667 {
668         vector<string> inputs[DataType::num_types];
669         vector<string> outputs[DataType::num_types];
670         for (uint32_t i = 0; i < DataType::num_types; ++i) {
671                 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
672                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
673         }
674
675         /* Create a set of Bundle objects that map
676            to the physical I/O currently available.  We create both
677            mono and stereo bundles, so that the common cases of mono
678            and stereo tracks get bundles to put in their mixer strip
679            in / out menus.  There may be a nicer way of achieving that;
680            it doesn't really scale that well to higher channel counts
681         */
682
683         /* mono output bundles */
684
685         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
686                 char buf[32];
687                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
688
689                 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
690                 c->add_channel (_("mono"), DataType::AUDIO);
691                 c->set_port (0, outputs[DataType::AUDIO][np]);
692
693                 add_bundle (c);
694         }
695
696         /* stereo output bundles */
697
698         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
699                 if (np + 1 < outputs[DataType::AUDIO].size()) {
700                         char buf[32];
701                         snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
702                         boost::shared_ptr<Bundle> c (new Bundle (buf, true));
703                         c->add_channel (_("L"), DataType::AUDIO);
704                         c->set_port (0, outputs[DataType::AUDIO][np]);
705                         c->add_channel (_("R"), DataType::AUDIO);
706                         c->set_port (1, outputs[DataType::AUDIO][np + 1]);
707
708                         add_bundle (c);
709                 }
710         }
711
712         /* mono input bundles */
713
714         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
715                 char buf[32];
716                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
717
718                 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
719                 c->add_channel (_("mono"), DataType::AUDIO);
720                 c->set_port (0, inputs[DataType::AUDIO][np]);
721
722                 add_bundle (c);
723         }
724
725         /* stereo input bundles */
726
727         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
728                 if (np + 1 < inputs[DataType::AUDIO].size()) {
729                         char buf[32];
730                         snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
731
732                         boost::shared_ptr<Bundle> c (new Bundle (buf, false));
733                         c->add_channel (_("L"), DataType::AUDIO);
734                         c->set_port (0, inputs[DataType::AUDIO][np]);
735                         c->add_channel (_("R"), DataType::AUDIO);
736                         c->set_port (1, inputs[DataType::AUDIO][np + 1]);
737
738                         add_bundle (c);
739                 }
740         }
741
742         /* MIDI input bundles */
743
744         for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
745                 string n = inputs[DataType::MIDI][np];
746                 boost::erase_first (n, X_("alsa_pcm:"));
747
748                 boost::shared_ptr<Bundle> c (new Bundle (n, false));
749                 c->add_channel ("", DataType::MIDI);
750                 c->set_port (0, inputs[DataType::MIDI][np]);
751                 add_bundle (c);
752         }
753
754         /* MIDI output bundles */
755
756         for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
757                 string n = outputs[DataType::MIDI][np];
758                 boost::erase_first (n, X_("alsa_pcm:"));
759
760                 boost::shared_ptr<Bundle> c (new Bundle (n, true));
761                 c->add_channel ("", DataType::MIDI);
762                 c->set_port (0, outputs[DataType::MIDI][np]);
763                 add_bundle (c);
764         }
765
766 }
767
768 void
769 Session::auto_connect_master_bus ()
770 {
771         if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
772                 return;
773         }
774                 
775         /* if requested auto-connect the outputs to the first N physical ports.
776          */
777         
778         uint32_t limit = _master_out->n_outputs().n_total();
779         vector<string> outputs[DataType::num_types];
780         
781         for (uint32_t i = 0; i < DataType::num_types; ++i) {
782                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
783         }
784         
785         for (uint32_t n = 0; n < limit; ++n) {
786                 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
787                 string connect_to;
788                 if (outputs[p->type()].size() > n) {
789                         connect_to = outputs[p->type()][n];
790                 }
791                 
792                 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
793                         if (_master_out->output()->connect (p, connect_to, this)) {
794                                 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
795                                       << endmsg;
796                                 break;
797                         }
798                 }
799         }
800 }
801
802 void
803 Session::remove_monitor_section ()
804 {
805         if (!_monitor_out) {
806                 return;
807         }
808
809         /* force reversion to Solo-In-Place */
810         Config->set_solo_control_is_listen_control (false);
811
812         /* if we are auditioning, cancel it ... this is a workaround
813            to a problem (auditioning does not execute the process graph,
814            which is needed to remove routes when using >1 core for processing)
815         */
816         cancel_audition ();
817
818         {
819                 /* Hold process lock while doing this so that we don't hear bits and
820                  * pieces of audio as we work on each route.
821                  */
822                 
823                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
824                 
825                 /* Connect tracks to monitor section. Note that in an
826                    existing session, the internal sends will already exist, but we want the
827                    routes to notice that they connect to the control out specifically.
828                 */
829                 
830                 
831                 boost::shared_ptr<RouteList> r = routes.reader ();
832                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
833                 
834                 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
835                         
836                         if ((*x)->is_monitor()) {
837                                 /* relax */
838                         } else if ((*x)->is_master()) {
839                                 /* relax */
840                         } else {
841                                 (*x)->remove_aux_or_listen (_monitor_out);
842                         }
843                 }
844         }
845
846         remove_route (_monitor_out);
847         auto_connect_master_bus ();
848
849         if (auditioner) {
850                 auditioner->connect ();
851         }
852 }
853
854 void
855 Session::add_monitor_section ()
856 {
857         RouteList rl;
858
859         if (_monitor_out || !_master_out) {
860                 return;
861         }
862
863         boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
864
865         if (r->init ()) {
866                 return;
867         }
868
869 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
870         // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
871 #endif
872         {
873                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
874                 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
875                 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
876         }
877
878         rl.push_back (r);
879         add_routes (rl, false, false, false);
880         
881         assert (_monitor_out);
882
883         /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
884            are undefined, at best.
885         */
886         
887         uint32_t limit = _monitor_out->n_inputs().n_audio();
888         
889         if (_master_out) {
890                 
891                 /* connect the inputs to the master bus outputs. this
892                  * represents a separate data feed from the internal sends from
893                  * each route. as of jan 2011, it allows the monitor section to
894                  * conditionally ignore either the internal sends or the normal
895                  * input feed, but we should really find a better way to do
896                  * this, i think.
897                  */
898
899                 _master_out->output()->disconnect (this);
900
901                 for (uint32_t n = 0; n < limit; ++n) {
902                         boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
903                         boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
904                         
905                         if (o) {
906                                 string connect_to = o->name();
907                                 if (_monitor_out->input()->connect (p, connect_to, this)) {
908                                         error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
909                                               << endmsg;
910                                         break;
911                                 }
912                         }
913                 }
914         }
915         
916         /* if monitor section is not connected, connect it to physical outs
917          */
918         
919         if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
920                 
921                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
922                         
923                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
924                         
925                         if (b) {
926                                 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
927                         } else {
928                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
929                                                            Config->get_monitor_bus_preferred_bundle())
930                                         << endmsg;
931                         }
932                         
933                 } else {
934                         
935                         /* Monitor bus is audio only */
936
937                         vector<string> outputs[DataType::num_types];
938
939                         for (uint32_t i = 0; i < DataType::num_types; ++i) {
940                                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
941                         }
942
943                         uint32_t mod = outputs[DataType::AUDIO].size();
944                         uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
945                         
946                         if (mod != 0) {
947                                 
948                                 for (uint32_t n = 0; n < limit; ++n) {
949                                         
950                                         boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
951                                         string connect_to;
952                                         if (outputs[DataType::AUDIO].size() > (n % mod)) {
953                                                 connect_to = outputs[DataType::AUDIO][n % mod];
954                                         }
955                                         
956                                         if (!connect_to.empty()) {
957                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
958                                                         error << string_compose (
959                                                                 _("cannot connect control output %1 to %2"),
960                                                                 n, connect_to)
961                                                               << endmsg;
962                                                         break;
963                                                 }
964                                         }
965                                 }
966                         }
967                 }
968         }
969
970         /* Hold process lock while doing this so that we don't hear bits and
971          * pieces of audio as we work on each route.
972          */
973          
974         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
975
976         /* Connect tracks to monitor section. Note that in an
977            existing session, the internal sends will already exist, but we want the
978            routes to notice that they connect to the control out specifically.
979         */
980
981
982         boost::shared_ptr<RouteList> rls = routes.reader ();
983
984         PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
985
986         for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
987                 
988                 if ((*x)->is_monitor()) {
989                         /* relax */
990                 } else if ((*x)->is_master()) {
991                         /* relax */
992                 } else {
993                         (*x)->enable_monitor_send ();
994                 }
995         }
996
997         if (auditioner) {
998                 auditioner->connect ();
999         }
1000 }
1001
1002 void
1003 Session::hookup_io ()
1004 {
1005         /* stop graph reordering notifications from
1006            causing resorts, etc.
1007         */
1008
1009         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1010
1011         if (!auditioner) {
1012
1013                 /* we delay creating the auditioner till now because
1014                    it makes its own connections to ports.
1015                 */
1016
1017                 try {
1018                         boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1019                         if (a->init()) {
1020                                 throw failed_constructor ();
1021                         }
1022                         a->use_new_diskstream ();
1023                         auditioner = a;
1024                 }
1025
1026                 catch (failed_constructor& err) {
1027                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1028                 }
1029         }
1030
1031         /* load bundles, which we may have postponed earlier on */
1032         if (_bundle_xml_node) {
1033                 load_bundles (*_bundle_xml_node);
1034                 delete _bundle_xml_node;
1035         }
1036
1037         /* Tell all IO objects to connect themselves together */
1038
1039         IO::enable_connecting ();
1040
1041         /* Now tell all "floating" ports to connect to whatever
1042            they should be connected to.
1043         */
1044
1045         AudioEngine::instance()->reconnect_ports ();
1046
1047         /* Anyone who cares about input state, wake up and do something */
1048
1049         IOConnectionsComplete (); /* EMIT SIGNAL */
1050
1051         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1052
1053         /* now handle the whole enchilada as if it was one
1054            graph reorder event.
1055         */
1056
1057         graph_reordered ();
1058
1059         /* update the full solo state, which can't be
1060            correctly determined on a per-route basis, but
1061            needs the global overview that only the session
1062            has.
1063         */
1064
1065         update_route_solo_state ();
1066 }
1067
1068 void
1069 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1070 {
1071         boost::shared_ptr<Track> track = wp.lock ();
1072         if (!track) {
1073                 return;
1074         }
1075
1076         boost::shared_ptr<Playlist> playlist;
1077
1078         if ((playlist = track->playlist()) != 0) {
1079                 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1080                 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1081                 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1082         }
1083 }
1084
1085 bool
1086 Session::record_enabling_legal () const
1087 {
1088         /* this used to be in here, but survey says.... we don't need to restrict it */
1089         // if (record_status() == Recording) {
1090         //      return false;
1091         // }
1092
1093         if (Config->get_all_safe()) {
1094                 return false;
1095         }
1096         return true;
1097 }
1098
1099 void
1100 Session::set_track_monitor_input_status (bool yn)
1101 {
1102         boost::shared_ptr<RouteList> rl = routes.reader ();
1103         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1104                 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1105                 if (tr && tr->record_enabled ()) {
1106                         //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1107                         tr->request_input_monitoring (yn);
1108                 }
1109         }
1110 }
1111
1112 void
1113 Session::auto_punch_start_changed (Location* location)
1114 {
1115         replace_event (SessionEvent::PunchIn, location->start());
1116
1117         if (get_record_enabled() && config.get_punch_in()) {
1118                 /* capture start has been changed, so save new pending state */
1119                 save_state ("", true);
1120         }
1121 }
1122
1123 void
1124 Session::auto_punch_end_changed (Location* location)
1125 {
1126         framepos_t when_to_stop = location->end();
1127         // when_to_stop += _worst_output_latency + _worst_input_latency;
1128         replace_event (SessionEvent::PunchOut, when_to_stop);
1129 }
1130
1131 void
1132 Session::auto_punch_changed (Location* location)
1133 {
1134         framepos_t when_to_stop = location->end();
1135
1136         replace_event (SessionEvent::PunchIn, location->start());
1137         //when_to_stop += _worst_output_latency + _worst_input_latency;
1138         replace_event (SessionEvent::PunchOut, when_to_stop);
1139 }
1140
1141 /** @param loc A loop location.
1142  *  @param pos Filled in with the start time of the required fade-out (in session frames).
1143  *  @param length Filled in with the length of the required fade-out.
1144  */
1145 void
1146 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1147 {
1148         pos = max (loc->start(), loc->end() - 64);
1149         length = loc->end() - pos;
1150 }
1151
1152 void
1153 Session::auto_loop_changed (Location* location)
1154 {
1155         replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1156         framepos_t dcp;
1157         framecnt_t dcl;
1158         auto_loop_declick_range (location, dcp, dcl);
1159         replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1160
1161         if (transport_rolling() && play_loop) {
1162
1163
1164                 // if (_transport_frame > location->end()) {
1165
1166                 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1167                         // relocate to beginning of loop
1168                         clear_events (SessionEvent::LocateRoll);
1169
1170                         request_locate (location->start(), true);
1171
1172                 }
1173                 else if (Config->get_seamless_loop() && !loop_changing) {
1174
1175                         // schedule a locate-roll to refill the diskstreams at the
1176                         // previous loop end
1177                         loop_changing = true;
1178
1179                         if (location->end() > last_loopend) {
1180                                 clear_events (SessionEvent::LocateRoll);
1181                                 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1182                                 queue_event (ev);
1183                         }
1184
1185                 }
1186         }
1187
1188         last_loopend = location->end();
1189 }
1190
1191 void
1192 Session::set_auto_punch_location (Location* location)
1193 {
1194         Location* existing;
1195
1196         if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1197                 punch_connections.drop_connections();
1198                 existing->set_auto_punch (false, this);
1199                 remove_event (existing->start(), SessionEvent::PunchIn);
1200                 clear_events (SessionEvent::PunchOut);
1201                 auto_punch_location_changed (0);
1202         }
1203
1204         set_dirty();
1205
1206         if (location == 0) {
1207                 return;
1208         }
1209
1210         if (location->end() <= location->start()) {
1211                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1212                 return;
1213         }
1214
1215         punch_connections.drop_connections ();
1216
1217         location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1218         location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1219         location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1220
1221         location->set_auto_punch (true, this);
1222
1223         auto_punch_changed (location);
1224
1225         auto_punch_location_changed (location);
1226 }
1227
1228 void
1229 Session::set_auto_loop_location (Location* location)
1230 {
1231         Location* existing;
1232
1233         if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1234                 loop_connections.drop_connections ();
1235                 existing->set_auto_loop (false, this);
1236                 remove_event (existing->end(), SessionEvent::AutoLoop);
1237                 framepos_t dcp;
1238                 framecnt_t dcl;
1239                 auto_loop_declick_range (existing, dcp, dcl);
1240                 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1241                 auto_loop_location_changed (0);
1242         }
1243
1244         set_dirty();
1245
1246         if (location == 0) {
1247                 return;
1248         }
1249
1250         if (location->end() <= location->start()) {
1251                 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1252                 return;
1253         }
1254
1255         last_loopend = location->end();
1256
1257         loop_connections.drop_connections ();
1258
1259         location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1260         location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1261         location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1262
1263         location->set_auto_loop (true, this);
1264
1265         /* take care of our stuff first */
1266
1267         auto_loop_changed (location);
1268
1269         /* now tell everyone else */
1270
1271         auto_loop_location_changed (location);
1272 }
1273
1274 void
1275 Session::locations_added (Location *)
1276 {
1277         set_dirty ();
1278 }
1279
1280 void
1281 Session::locations_changed ()
1282 {
1283         _locations->apply (*this, &Session::handle_locations_changed);
1284 }
1285
1286 void
1287 Session::handle_locations_changed (Locations::LocationList& locations)
1288 {
1289         Locations::LocationList::iterator i;
1290         Location* location;
1291         bool set_loop = false;
1292         bool set_punch = false;
1293
1294         for (i = locations.begin(); i != locations.end(); ++i) {
1295
1296                 location =* i;
1297
1298                 if (location->is_auto_punch()) {
1299                         set_auto_punch_location (location);
1300                         set_punch = true;
1301                 }
1302                 if (location->is_auto_loop()) {
1303                         set_auto_loop_location (location);
1304                         set_loop = true;
1305                 }
1306
1307                 if (location->is_session_range()) {
1308                         _session_range_location = location;
1309                 }
1310         }
1311
1312         if (!set_loop) {
1313                 set_auto_loop_location (0);
1314         }
1315         if (!set_punch) {
1316                 set_auto_punch_location (0);
1317         }
1318
1319         set_dirty();
1320 }
1321
1322 void
1323 Session::enable_record ()
1324 {
1325         if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1326                 /* no recording at anything except normal speed */
1327                 return;
1328         }
1329
1330         while (1) {
1331                 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1332
1333                 if (rs == Recording) {
1334                         break;
1335                 }
1336                 
1337                 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1338
1339                         _last_record_location = _transport_frame;
1340                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1341
1342                         if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1343                                 set_track_monitor_input_status (true);
1344                         }
1345
1346                         RecordStateChanged ();
1347                         break;
1348                 }
1349         }
1350 }
1351
1352 void
1353 Session::disable_record (bool rt_context, bool force)
1354 {
1355         RecordState rs;
1356
1357         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1358
1359                 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1360                         g_atomic_int_set (&_record_status, Disabled);
1361                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1362                 } else {
1363                         if (rs == Recording) {
1364                                 g_atomic_int_set (&_record_status, Enabled);
1365                         }
1366                 }
1367
1368                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1369                         set_track_monitor_input_status (false);
1370                 }
1371
1372                 RecordStateChanged (); /* emit signal */
1373
1374                 if (!rt_context) {
1375                         remove_pending_capture_state ();
1376                 }
1377         }
1378 }
1379
1380 void
1381 Session::step_back_from_record ()
1382 {
1383         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1384
1385                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1386                         set_track_monitor_input_status (false);
1387                 }
1388
1389                 RecordStateChanged (); /* emit signal */
1390         }
1391 }
1392
1393 void
1394 Session::maybe_enable_record ()
1395 {
1396         if (_step_editors > 0) {
1397                 return;
1398         }
1399
1400         g_atomic_int_set (&_record_status, Enabled);
1401
1402         /* This function is currently called from somewhere other than an RT thread.
1403            This save_state() call therefore doesn't impact anything.  Doing it here
1404            means that we save pending state of which sources the next record will use,
1405            which gives us some chance of recovering from a crash during the record.
1406         */
1407
1408         save_state ("", true);
1409
1410         if (_transport_speed) {
1411                 if (!config.get_punch_in()) {
1412                         enable_record ();
1413                 }
1414         } else {
1415                 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1416                 RecordStateChanged (); /* EMIT SIGNAL */
1417         }
1418
1419         set_dirty();
1420 }
1421
1422 framepos_t
1423 Session::audible_frame () const
1424 {
1425         framepos_t ret;
1426         framepos_t tf;
1427         framecnt_t offset;
1428
1429         /* the first of these two possible settings for "offset"
1430            mean that the audible frame is stationary until
1431            audio emerges from the latency compensation
1432            "pseudo-pipeline".
1433
1434            the second means that the audible frame is stationary
1435            until audio would emerge from a physical port
1436            in the absence of any plugin latency compensation
1437         */
1438
1439         offset = worst_playback_latency ();
1440
1441         if (offset > current_block_size) {
1442                 offset -= current_block_size;
1443         } else {
1444                 /* XXX is this correct? if we have no external
1445                    physical connections and everything is internal
1446                    then surely this is zero? still, how
1447                    likely is that anyway?
1448                 */
1449                 offset = current_block_size;
1450         }
1451
1452         if (synced_to_engine()) {
1453                 tf = _engine.transport_frame();
1454         } else {
1455                 tf = _transport_frame;
1456         }
1457
1458         ret = tf;
1459
1460         if (!non_realtime_work_pending()) {
1461
1462                 /* MOVING */
1463
1464                 /* Check to see if we have passed the first guaranteed
1465                    audible frame past our last start position. if not,
1466                    return that last start point because in terms
1467                    of audible frames, we have not moved yet.
1468
1469                    `Start position' in this context means the time we last
1470                    either started, located, or changed transport direction.
1471                 */
1472
1473                 if (_transport_speed > 0.0f) {
1474
1475                         if (!play_loop || !have_looped) {
1476                                 if (tf < _last_roll_or_reversal_location + offset) {
1477                                         return _last_roll_or_reversal_location;
1478                                 }
1479                         }
1480
1481
1482                         /* forwards */
1483                         ret -= offset;
1484
1485                 } else if (_transport_speed < 0.0f) {
1486
1487                         /* XXX wot? no backward looping? */
1488
1489                         if (tf > _last_roll_or_reversal_location - offset) {
1490                                 return _last_roll_or_reversal_location;
1491                         } else {
1492                                 /* backwards */
1493                                 ret += offset;
1494                         }
1495                 }
1496         }
1497
1498         return ret;
1499 }
1500
1501 void
1502 Session::set_frame_rate (framecnt_t frames_per_second)
1503 {
1504         /** \fn void Session::set_frame_size(framecnt_t)
1505                 the AudioEngine object that calls this guarantees
1506                 that it will not be called while we are also in
1507                 ::process(). Its fine to do things that block
1508                 here.
1509         */
1510
1511         _base_frame_rate = frames_per_second;
1512         _nominal_frame_rate = frames_per_second;
1513
1514         sync_time_vars();
1515
1516         clear_clicks ();
1517
1518         // XXX we need some equivalent to this, somehow
1519         // SndFileSource::setup_standard_crossfades (frames_per_second);
1520
1521         set_dirty();
1522
1523         /* XXX need to reset/reinstantiate all LADSPA plugins */
1524 }
1525
1526 void
1527 Session::set_block_size (pframes_t nframes)
1528 {
1529         /* the AudioEngine guarantees
1530            that it will not be called while we are also in
1531            ::process(). It is therefore fine to do things that block
1532            here.
1533         */
1534         
1535         {
1536                 current_block_size = nframes;
1537
1538                 ensure_buffers ();
1539
1540                 boost::shared_ptr<RouteList> r = routes.reader ();
1541
1542                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1543                         (*i)->set_block_size (nframes);
1544                 }
1545
1546                 boost::shared_ptr<RouteList> rl = routes.reader ();
1547                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1548                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1549                         if (tr) {
1550                                 tr->set_block_size (nframes);
1551                         }
1552                 }
1553
1554                 set_worst_io_latencies ();
1555         }
1556 }
1557
1558
1559 static void
1560 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1561 {
1562         boost::shared_ptr<Route> r2;
1563
1564         if (r1->feeds (rbase) && rbase->feeds (r1)) {
1565                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1566                 return;
1567         }
1568
1569         /* make a copy of the existing list of routes that feed r1 */
1570
1571         Route::FedBy existing (r1->fed_by());
1572
1573         /* for each route that feeds r1, recurse, marking it as feeding
1574            rbase as well.
1575         */
1576
1577         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1578                 if (!(r2 = i->r.lock ())) {
1579                         /* (*i) went away, ignore it */
1580                         continue;
1581                 }
1582
1583                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1584                    base as being fed by r2
1585                 */
1586
1587                 rbase->add_fed_by (r2, i->sends_only);
1588
1589                 if (r2 != rbase) {
1590
1591                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1592                            stop here.
1593                         */
1594
1595                         if (r1->feeds (r2) && r2->feeds (r1)) {
1596                                 continue;
1597                         }
1598
1599                         /* now recurse, so that we can mark base as being fed by
1600                            all routes that feed r2
1601                         */
1602
1603                         trace_terminal (r2, rbase);
1604                 }
1605
1606         }
1607 }
1608
1609 void
1610 Session::resort_routes ()
1611 {
1612         /* don't do anything here with signals emitted
1613            by Routes during initial setup or while we
1614            are being destroyed.
1615         */
1616
1617         if (_state_of_the_state & (InitialConnecting | Deletion)) {
1618                 return;
1619         }
1620
1621         {
1622                 RCUWriter<RouteList> writer (routes);
1623                 boost::shared_ptr<RouteList> r = writer.get_copy ();
1624                 resort_routes_using (r);
1625                 /* writer goes out of scope and forces update */
1626         }
1627
1628 #ifndef NDEBUG
1629         boost::shared_ptr<RouteList> rl = routes.reader ();
1630         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1631                 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1632
1633                 const Route::FedBy& fb ((*i)->fed_by());
1634
1635                 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1636                         boost::shared_ptr<Route> sf = f->r.lock();
1637                         if (sf) {
1638                                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1639                         }
1640                 }
1641         }
1642 #endif
1643
1644 }
1645
1646 /** This is called whenever we need to rebuild the graph of how we will process
1647  *  routes.
1648  *  @param r List of routes, in any order.
1649  */
1650
1651 void
1652 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1653 {
1654         /* We are going to build a directed graph of our routes;
1655            this is where the edges of that graph are put.
1656         */
1657         
1658         GraphEdges edges;
1659
1660         /* Go through all routes doing two things:
1661          *
1662          * 1. Collect the edges of the route graph.  Each of these edges
1663          *    is a pair of routes, one of which directly feeds the other
1664          *    either by a JACK connection or by an internal send.
1665          *
1666          * 2. Begin the process of making routes aware of which other
1667          *    routes directly or indirectly feed them.  This information
1668          *    is used by the solo code.
1669          */
1670            
1671         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1672
1673                 /* Clear out the route's list of direct or indirect feeds */
1674                 (*i)->clear_fed_by ();
1675
1676                 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1677
1678                         bool via_sends_only;
1679
1680                         /* See if this *j feeds *i according to the current state of the JACK
1681                            connections and internal sends.
1682                         */
1683                         if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1684                                 /* add the edge to the graph (part #1) */
1685                                 edges.add (*j, *i, via_sends_only);
1686                                 /* tell the route (for part #2) */
1687                                 (*i)->add_fed_by (*j, via_sends_only);
1688                         }
1689                 }
1690         }
1691
1692         /* Attempt a topological sort of the route graph */
1693         boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1694         
1695         if (sorted_routes) {
1696                 /* We got a satisfactory topological sort, so there is no feedback;
1697                    use this new graph.
1698
1699                    Note: the process graph rechain does not require a
1700                    topologically-sorted list, but hey ho.
1701                 */
1702                 if (_process_graph) {
1703                         _process_graph->rechain (sorted_routes, edges);
1704                 }
1705                 
1706                 _current_route_graph = edges;
1707
1708                 /* Complete the building of the routes' lists of what directly
1709                    or indirectly feeds them.
1710                 */
1711                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1712                         trace_terminal (*i, *i);
1713                 }
1714
1715                 *r = *sorted_routes;
1716
1717 #ifndef NDEBUG
1718                 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1719                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1720                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1721                                                                    (*i)->name(), (*i)->order_key ()));
1722                 }
1723 #endif
1724
1725                 SuccessfulGraphSort (); /* EMIT SIGNAL */
1726
1727         } else {
1728                 /* The topological sort failed, so we have a problem.  Tell everyone
1729                    and stick to the old graph; this will continue to be processed, so
1730                    until the feedback is fixed, what is played back will not quite
1731                    reflect what is actually connected.  Note also that we do not
1732                    do trace_terminal here, as it would fail due to an endless recursion,
1733                    so the solo code will think that everything is still connected
1734                    as it was before.
1735                 */
1736                 
1737                 FeedbackDetected (); /* EMIT SIGNAL */
1738         }
1739
1740 }
1741
1742 /** Find a route name starting with \a base, maybe followed by the
1743  *  lowest \a id.  \a id will always be added if \a definitely_add_number
1744  *  is true on entry; otherwise it will only be added if required
1745  *  to make the name unique.
1746  *
1747  *  Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1748  *  The available route name with the lowest ID will be used, and \a id
1749  *  will be set to the ID.
1750  *
1751  *  \return false if a route name could not be found, and \a track_name
1752  *  and \a id do not reflect a free route name.
1753  */
1754 bool
1755 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1756 {
1757         if (!definitely_add_number && route_by_name (base) == 0) {
1758                 /* juse use the base */
1759                 snprintf (name, name_len, "%s", base.c_str());
1760                 return true;
1761         }
1762
1763         do {
1764                 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1765
1766                 if (route_by_name (name) == 0) {
1767                         return true;
1768                 }
1769
1770                 ++id;
1771                 
1772         } while (id < (UINT_MAX-1));
1773
1774         return false;
1775 }
1776
1777 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1778 void
1779 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1780 {
1781         in  = ChanCount::ZERO;
1782         out = ChanCount::ZERO;
1783
1784         boost::shared_ptr<RouteList> r = routes.reader ();
1785
1786         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1787                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1788                 if (tr && !tr->is_auditioner()) {
1789                         in  += tr->n_inputs();
1790                         out += tr->n_outputs();
1791                 }
1792         }
1793 }
1794
1795 /** Caller must not hold process lock
1796  *  @param name_template string to use for the start of the name, or "" to use "MIDI".
1797  *  @param instrument plugin info for the instrument to insert pre-fader, if any
1798  */
1799 list<boost::shared_ptr<MidiTrack> >
1800 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument, 
1801                          TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1802 {
1803         char track_name[32];
1804         uint32_t track_id = 0;
1805         string port;
1806         RouteList new_routes;
1807         list<boost::shared_ptr<MidiTrack> > ret;
1808
1809         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1810
1811         while (how_many) {
1812                 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1813                         error << "cannot find name for new midi track" << endmsg;
1814                         goto failed;
1815                 }
1816
1817                 boost::shared_ptr<MidiTrack> track;
1818
1819                 try {
1820                         track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1821
1822                         if (track->init ()) {
1823                                 goto failed;
1824                         }
1825
1826                         track->use_new_diskstream();
1827
1828 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1829                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1830 #endif
1831                         {
1832                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1833                                 if (track->input()->ensure_io (input, false, this)) {
1834                                         error << "cannot configure " << input << " out configuration for new midi track" << endmsg;     
1835                                         goto failed;
1836                                 }
1837
1838                                 if (track->output()->ensure_io (output, false, this)) {
1839                                         error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1840                                         goto failed;
1841                                 }
1842                         }
1843
1844                         track->non_realtime_input_change();
1845
1846                         if (route_group) {
1847                                 route_group->add (track);
1848                         }
1849
1850                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1851
1852                         if (Config->get_remote_model() == UserOrdered) {
1853                                 track->set_remote_control_id (next_control_id());
1854                         }
1855
1856                         new_routes.push_back (track);
1857                         ret.push_back (track);
1858                 }
1859
1860                 catch (failed_constructor &err) {
1861                         error << _("Session: could not create new midi track.") << endmsg;
1862                         goto failed;
1863                 }
1864
1865                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1866
1867                         error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
1868                         goto failed;
1869                 }
1870
1871                 --how_many;
1872         }
1873
1874   failed:
1875         if (!new_routes.empty()) {
1876                 add_routes (new_routes, true, true, true);
1877
1878                 if (instrument) {
1879                         for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1880                                 PluginPtr plugin = instrument->load (*this);
1881                                 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1882                                 (*r)->add_processor (p, PreFader);
1883                                 
1884                         }
1885                 }
1886         }
1887
1888         return ret;
1889 }
1890
1891 void
1892 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1893 {
1894         boost::shared_ptr<Route> midi_track (wmt.lock());
1895
1896         if (!midi_track) {
1897                 return;
1898         }
1899
1900         if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1901
1902                 if (change.after.n_audio() <= change.before.n_audio()) {
1903                         return;
1904                 }
1905
1906                 /* new audio ports: make sure the audio goes somewhere useful,
1907                    unless the user has no-auto-connect selected.
1908
1909                    The existing ChanCounts don't matter for this call as they are only
1910                    to do with matching input and output indices, and we are only changing
1911                    outputs here.
1912                 */
1913
1914                 ChanCount dummy;
1915
1916                 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1917         }
1918 }
1919
1920 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1921  *  @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1922  *  @param output_start As \a input_start, but for outputs.
1923  */
1924 void
1925 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1926                              bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1927 {
1928         if (!IO::connecting_legal) {
1929                 return;
1930         }
1931
1932         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1933
1934         if (with_lock) {
1935                 lm.acquire ();
1936         }
1937
1938         /* If both inputs and outputs are auto-connected to physical ports,
1939            use the max of input and output offsets to ensure auto-connected
1940            port numbers always match up (e.g. the first audio input and the
1941            first audio output of the route will have the same physical
1942            port number).  Otherwise just use the lowest input or output
1943            offset possible.
1944         */
1945
1946         DEBUG_TRACE (DEBUG::Graph,
1947                      string_compose("Auto-connect: existing in = %1 out = %2\n",
1948                                     existing_inputs, existing_outputs));
1949
1950         const bool in_out_physical =
1951                 (Config->get_input_auto_connect() & AutoConnectPhysical)
1952                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1953                 && connect_inputs;
1954
1955         const ChanCount in_offset = in_out_physical
1956                 ? ChanCount::max(existing_inputs, existing_outputs)
1957                 : existing_inputs;
1958
1959         const ChanCount out_offset = in_out_physical
1960                 ? ChanCount::max(existing_inputs, existing_outputs)
1961                 : existing_outputs;
1962
1963         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1964                 vector<string> physinputs;
1965                 vector<string> physoutputs;
1966
1967                 _engine.get_physical_outputs (*t, physoutputs);
1968                 _engine.get_physical_inputs (*t, physinputs);
1969
1970                 if (!physinputs.empty() && connect_inputs) {
1971                         uint32_t nphysical_in = physinputs.size();
1972
1973                         DEBUG_TRACE (DEBUG::Graph,
1974                                      string_compose("There are %1 physical inputs of type %2\n",
1975                                                     nphysical_in, *t));
1976
1977                         for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1978                                 string port;
1979
1980                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1981                                         DEBUG_TRACE (DEBUG::Graph,
1982                                                      string_compose("Get index %1 + %2 % %3 = %4\n",
1983                                                                     in_offset.get(*t), i, nphysical_in,
1984                                                                     (in_offset.get(*t) + i) % nphysical_in));
1985                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1986                                 }
1987
1988                                 DEBUG_TRACE (DEBUG::Graph,
1989                                              string_compose("Connect route %1 IN to %2\n",
1990                                                             route->name(), port));
1991
1992                                 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1993                                         break;
1994                                 }
1995
1996                                 ChanCount one_added (*t, 1);
1997                                 existing_inputs += one_added;
1998                         }
1999                 }
2000
2001                 if (!physoutputs.empty()) {
2002                         uint32_t nphysical_out = physoutputs.size();
2003                         for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2004                                 string port;
2005
2006                                 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2007                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2008                                 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2009                                         /* master bus is audio only */
2010                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2011                                                 port = _master_out->input()->ports().port(*t,
2012                                                                 i % _master_out->input()->n_ports().get(*t))->name();
2013                                         }
2014                                 }
2015
2016                                 DEBUG_TRACE (DEBUG::Graph,
2017                                              string_compose("Connect route %1 OUT to %2\n",
2018                                                             route->name(), port));
2019
2020                                 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2021                                         break;
2022                                 }
2023
2024                                 ChanCount one_added (*t, 1);
2025                                 existing_outputs += one_added;
2026                         }
2027                 }
2028         }
2029 }
2030
2031 /** Caller must not hold process lock
2032  *  @param name_template string to use for the start of the name, or "" to use "Audio".
2033  */
2034 list< boost::shared_ptr<AudioTrack> >
2035 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, 
2036                           uint32_t how_many, string name_template)
2037 {
2038         char track_name[32];
2039         uint32_t track_id = 0;
2040         string port;
2041         RouteList new_routes;
2042         list<boost::shared_ptr<AudioTrack> > ret;
2043
2044         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2045
2046         while (how_many) {
2047                 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2048                         error << "cannot find name for new audio track" << endmsg;
2049                         goto failed;
2050                 }
2051
2052                 boost::shared_ptr<AudioTrack> track;
2053
2054                 try {
2055                         track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2056
2057                         if (track->init ()) {
2058                                 goto failed;
2059                         }
2060
2061                         track->use_new_diskstream();
2062
2063 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2064                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2065 #endif
2066                         {
2067                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2068
2069                                 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2070                                         error << string_compose (
2071                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2072                                                 input_channels, output_channels)
2073                                               << endmsg;
2074                                         goto failed;
2075                                 }
2076
2077                                 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2078                                         error << string_compose (
2079                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2080                                                 input_channels, output_channels)
2081                                               << endmsg;
2082                                         goto failed;
2083                                 }
2084                         }
2085
2086                         if (route_group) {
2087                                 route_group->add (track);
2088                         }
2089
2090                         track->non_realtime_input_change();
2091
2092                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2093                         if (Config->get_remote_model() == UserOrdered) {
2094                                 track->set_remote_control_id (next_control_id());
2095                         }
2096
2097                         new_routes.push_back (track);
2098                         ret.push_back (track);
2099                 }
2100
2101                 catch (failed_constructor &err) {
2102                         error << _("Session: could not create new audio track.") << endmsg;
2103                         goto failed;
2104                 }
2105
2106                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2107
2108                         error << pfe.what() << endmsg;
2109                         goto failed;
2110                 }
2111
2112                 --how_many;
2113         }
2114
2115   failed:
2116         if (!new_routes.empty()) {
2117                 add_routes (new_routes, true, true, true);
2118         }
2119
2120         return ret;
2121 }
2122
2123 /** Caller must not hold process lock.
2124  *  @param name_template string to use for the start of the name, or "" to use "Bus".
2125  */
2126 RouteList
2127 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2128 {
2129         char bus_name[32];
2130         uint32_t bus_id = 0;
2131         string port;
2132         RouteList ret;
2133
2134         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2135         
2136         while (how_many) {
2137                 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2138                         error << "cannot find name for new audio bus" << endmsg;
2139                         goto failure;
2140                 }
2141
2142                 try {
2143                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2144
2145                         if (bus->init ()) {
2146                                 goto failure;
2147                         }
2148
2149 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2150                         // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2151 #endif
2152                         {
2153                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2154
2155                                 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2156                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2157                                                                  input_channels, output_channels)
2158                                               << endmsg;
2159                                         goto failure;
2160                                 }
2161
2162
2163                                 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2164                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2165                                                                  input_channels, output_channels)
2166                                               << endmsg;
2167                                         goto failure;
2168                                 }
2169                         }
2170
2171                         if (route_group) {
2172                                 route_group->add (bus);
2173                         }
2174                         if (Config->get_remote_model() == UserOrdered) {
2175                                 bus->set_remote_control_id (next_control_id());
2176                         }
2177
2178                         bus->add_internal_return ();
2179
2180                         ret.push_back (bus);
2181                         
2182                         ARDOUR::GUIIdle ();
2183                 }
2184
2185
2186                 catch (failed_constructor &err) {
2187                         error << _("Session: could not create new audio route.") << endmsg;
2188                         goto failure;
2189                 }
2190
2191                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2192                         error << pfe.what() << endmsg;
2193                         goto failure;
2194                 }
2195
2196
2197                 --how_many;
2198         }
2199
2200   failure:
2201         if (!ret.empty()) {
2202                 add_routes (ret, false, true, true); // autoconnect outputs only
2203         }
2204
2205         return ret;
2206
2207 }
2208
2209 RouteList
2210 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2211 {
2212         RouteList ret;
2213         uint32_t control_id;
2214         XMLTree tree;
2215         uint32_t number = 0;
2216         const uint32_t being_added = how_many;
2217
2218         if (!tree.read (template_path.c_str())) {
2219                 return ret;
2220         }
2221
2222         XMLNode* node = tree.root();
2223
2224         IO::disable_connecting ();
2225
2226         control_id = next_control_id ();
2227
2228         while (how_many) {
2229
2230                 XMLNode node_copy (*node);
2231
2232                 /* Remove IDs of everything so that new ones are used */
2233                 node_copy.remove_property_recursively (X_("id"));
2234
2235                 try {
2236                         char name[32];
2237
2238                         if (!name_base.empty()) {
2239
2240                                 /* if we're adding more than one routes, force
2241                                  * all the names of the new routes to be
2242                                  * numbered, via the final parameter.
2243                                  */
2244
2245                                 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2246                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2247                                         /*NOTREACHDE*/
2248                                 }
2249
2250                         } else {
2251
2252                                 string const route_name  = node_copy.property(X_("name"))->value ();
2253                         
2254                                 /* generate a new name by adding a number to the end of the template name */
2255                                 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2256                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2257                                         /*NOTREACHED*/
2258                                 }
2259                         }
2260
2261                         /* set this name in the XML description that we are about to use */
2262                         Route::set_name_in_state (node_copy, name);
2263
2264                         /* trim bitslots from listen sends so that new ones are used */
2265                         XMLNodeList children = node_copy.children ();
2266                         for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2267                                 if ((*i)->name() == X_("Processor")) {
2268                                         XMLProperty* role = (*i)->property (X_("role"));
2269                                         if (role && role->value() == X_("Listen")) {
2270                                                 (*i)->remove_property (X_("bitslot"));
2271                                         }
2272                                 }
2273                         }
2274                         
2275                         boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2276
2277                         if (route == 0) {
2278                                 error << _("Session: cannot create track/bus from template description") << endmsg;
2279                                 goto out;
2280                         }
2281
2282                         if (boost::dynamic_pointer_cast<Track>(route)) {
2283                                 /* force input/output change signals so that the new diskstream
2284                                    picks up the configuration of the route. During session
2285                                    loading this normally happens in a different way.
2286                                 */
2287
2288                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2289
2290                                 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2291                                 change.after = route->input()->n_ports();
2292                                 route->input()->changed (change, this);
2293                                 change.after = route->output()->n_ports();
2294                                 route->output()->changed (change, this);
2295                         }
2296
2297                         route->set_remote_control_id (control_id);
2298                         ++control_id;
2299
2300                         ret.push_back (route);
2301                 }
2302
2303                 catch (failed_constructor &err) {
2304                         error << _("Session: could not create new route from template") << endmsg;
2305                         goto out;
2306                 }
2307
2308                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2309                         error << pfe.what() << endmsg;
2310                         goto out;
2311                 }
2312
2313                 --how_many;
2314         }
2315
2316   out:
2317         if (!ret.empty()) {
2318                 add_routes (ret, true, true, true);
2319                 IO::enable_connecting ();
2320         }
2321
2322         return ret;
2323 }
2324
2325 void
2326 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2327 {
2328         try {
2329                 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2330                 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2331
2332         } catch (...) {
2333                 error << _("Adding new tracks/busses failed") << endmsg;
2334         }
2335
2336         graph_reordered ();
2337
2338         update_latency (true);
2339         update_latency (false);
2340                 
2341         set_dirty();
2342         
2343         if (save) {
2344                 save_state (_current_snapshot_name);
2345         }
2346         
2347         RouteAdded (new_routes); /* EMIT SIGNAL */
2348 }
2349
2350 void
2351 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2352 {
2353         ChanCount existing_inputs;
2354         ChanCount existing_outputs;
2355         uint32_t order = next_control_id();
2356
2357         if (_order_hint != 0) {
2358                 order = _order_hint;
2359                 _order_hint = 0;
2360         }
2361
2362         count_existing_track_channels (existing_inputs, existing_outputs);
2363
2364         {
2365                 RCUWriter<RouteList> writer (routes);
2366                 boost::shared_ptr<RouteList> r = writer.get_copy ();
2367                 r->insert (r->end(), new_routes.begin(), new_routes.end());
2368
2369                 /* if there is no control out and we're not in the middle of loading,
2370                    resort the graph here. if there is a control out, we will resort
2371                    toward the end of this method. if we are in the middle of loading,
2372                    we will resort when done.
2373                 */
2374
2375                 if (!_monitor_out && IO::connecting_legal) {
2376                         resort_routes_using (r);
2377                 }
2378         }
2379
2380         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2381
2382                 boost::weak_ptr<Route> wpr (*x);
2383                 boost::shared_ptr<Route> r (*x);
2384
2385                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2386                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2387                 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2388                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2389                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2390                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2391
2392                 if (r->is_master()) {
2393                         _master_out = r;
2394                 }
2395
2396                 if (r->is_monitor()) {
2397                         _monitor_out = r;
2398                 }
2399
2400                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2401                 if (tr) {
2402                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2403                         track_playlist_changed (boost::weak_ptr<Track> (tr));
2404                         tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2405
2406                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2407                         if (mt) {
2408                                 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2409                                 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2410                         }
2411                 }
2412
2413
2414                 if (input_auto_connect || output_auto_connect) {
2415                         auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2416                 }
2417
2418                 /* order keys are a GUI responsibility but we need to set up
2419                    reasonable defaults because they also affect the remote control
2420                    ID in most situations.
2421                 */
2422
2423                 if (!r->has_order_key ()) {
2424                         if (r->is_auditioner()) {
2425                                 /* use an arbitrarily high value */
2426                                 r->set_order_key (UINT_MAX);
2427                         } else {
2428                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2429                                 r->set_order_key (order);
2430                                 order++;
2431                         }
2432                 }
2433
2434                 ARDOUR::GUIIdle ();
2435         }
2436
2437         if (_monitor_out && IO::connecting_legal) {
2438                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());         
2439                 
2440                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2441                         if ((*x)->is_monitor()) {
2442                                 /* relax */
2443                         } else if ((*x)->is_master()) {
2444                                         /* relax */
2445                         } else {
2446                                 (*x)->enable_monitor_send ();
2447                         }
2448                 }
2449         }
2450 }
2451
2452 void
2453 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2454 {
2455         boost::shared_ptr<RouteList> r = routes.reader ();
2456         boost::shared_ptr<Send> s;
2457
2458         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2459                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2460                         s->amp()->gain_control()->set_value (0.0);
2461                 }
2462         }
2463 }
2464
2465 void
2466 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2467 {
2468         boost::shared_ptr<RouteList> r = routes.reader ();
2469         boost::shared_ptr<Send> s;
2470
2471         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2472                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2473                         s->amp()->gain_control()->set_value (1.0);
2474                 }
2475         }
2476 }
2477
2478 void
2479 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2480 {
2481         boost::shared_ptr<RouteList> r = routes.reader ();
2482         boost::shared_ptr<Send> s;
2483
2484         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2485                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2486                         s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2487                 }
2488         }
2489 }
2490
2491 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2492 void
2493 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2494 {
2495         boost::shared_ptr<RouteList> r = routes.reader ();
2496         boost::shared_ptr<RouteList> t (new RouteList);
2497
2498         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2499                 /* no MIDI sends because there are no MIDI busses yet */
2500                 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2501                         t->push_back (*i);
2502                 }
2503         }
2504
2505         add_internal_sends (dest, p, t);
2506 }
2507
2508 void
2509 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2510 {
2511         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2512                 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2513         }
2514 }
2515
2516 void
2517 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2518 {
2519         add_internal_send (dest, sender->before_processor_for_index (index), sender);
2520 }
2521
2522 void
2523 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2524 {
2525         if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2526                 return;
2527         }
2528
2529         if (!dest->internal_return()) {
2530                 dest->add_internal_return ();
2531         }
2532
2533         sender->add_aux_send (dest, before);
2534
2535         graph_reordered ();
2536 }
2537
2538 void
2539 Session::remove_route (boost::shared_ptr<Route> route)
2540 {
2541         if (route == _master_out) {
2542                 return;
2543         }
2544
2545         route->set_solo (false, this);
2546
2547         {
2548                 RCUWriter<RouteList> writer (routes);
2549                 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2550
2551                 rs->remove (route);
2552
2553                 /* deleting the master out seems like a dumb
2554                    idea, but its more of a UI policy issue
2555                    than our concern.
2556                 */
2557
2558                 if (route == _master_out) {
2559                         _master_out = boost::shared_ptr<Route> ();
2560                 }
2561
2562                 if (route == _monitor_out) {
2563                         _monitor_out.reset ();
2564                 }
2565
2566                 /* writer goes out of scope, forces route list update */
2567         }
2568
2569         update_route_solo_state ();
2570
2571         // We need to disconnect the route's inputs and outputs
2572
2573         route->input()->disconnect (0);
2574         route->output()->disconnect (0);
2575
2576         /* if the route had internal sends sending to it, remove them */
2577         if (route->internal_return()) {
2578
2579                 boost::shared_ptr<RouteList> r = routes.reader ();
2580                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2581                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2582                         if (s) {
2583                                 (*i)->remove_processor (s);
2584                         }
2585                 }
2586         }
2587
2588         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2589         if (mt && mt->step_editing()) {
2590                 if (_step_editors > 0) {
2591                         _step_editors--;
2592                 }
2593         }
2594
2595         update_latency_compensation ();
2596         set_dirty();
2597
2598         /* Re-sort routes to remove the graph's current references to the one that is
2599          * going away, then flush old references out of the graph.
2600          */
2601
2602         resort_routes ();
2603         if (_process_graph) {
2604                 _process_graph->clear_other_chain ();
2605         }
2606
2607         /* get rid of it from the dead wood collection in the route list manager */
2608
2609         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2610
2611         routes.flush ();
2612
2613         /* try to cause everyone to drop their references */
2614
2615         route->drop_references ();
2616
2617         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2618
2619         /* save the new state of the world */
2620
2621         if (save_state (_current_snapshot_name)) {
2622                 save_history (_current_snapshot_name);
2623         }
2624 }
2625
2626 void
2627 Session::route_mute_changed (void* /*src*/)
2628 {
2629         set_dirty ();
2630 }
2631
2632 void
2633 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2634 {
2635         boost::shared_ptr<Route> route = wpr.lock();
2636         if (!route) {
2637                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2638                 return;
2639         }
2640
2641         if (route->listening_via_monitor ()) {
2642
2643                 if (Config->get_exclusive_solo()) {
2644                         /* new listen: disable all other listen */
2645                         boost::shared_ptr<RouteList> r = routes.reader ();
2646                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2647                                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2648                                         continue;
2649                                 }
2650                                 (*i)->set_listen (false, this);
2651                         }
2652                 }
2653
2654                 _listen_cnt++;
2655
2656         } else if (_listen_cnt > 0) {
2657
2658                 _listen_cnt--;
2659         }
2660
2661         update_route_solo_state ();
2662 }
2663 void
2664 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2665 {
2666         boost::shared_ptr<Route> route = wpr.lock ();
2667
2668         if (!route) {
2669                 /* should not happen */
2670                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2671                 return;
2672         }
2673
2674         bool send_changed = false;
2675
2676         if (route->solo_isolated()) {
2677                 if (_solo_isolated_cnt == 0) {
2678                         send_changed = true;
2679                 }
2680                 _solo_isolated_cnt++;
2681         } else if (_solo_isolated_cnt > 0) {
2682                 _solo_isolated_cnt--;
2683                 if (_solo_isolated_cnt == 0) {
2684                         send_changed = true;
2685                 }
2686         }
2687
2688         if (send_changed) {
2689                 IsolatedChanged (); /* EMIT SIGNAL */
2690         }
2691 }
2692
2693 void
2694 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2695 {
2696         DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2697
2698         if (!self_solo_change) {
2699                 // session doesn't care about changes to soloed-by-others
2700                 return;
2701         }
2702
2703         if (solo_update_disabled) {
2704                 // We know already
2705                 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2706                 return;
2707         }
2708
2709         boost::shared_ptr<Route> route = wpr.lock ();
2710         assert (route);
2711
2712         boost::shared_ptr<RouteList> r = routes.reader ();
2713         int32_t delta;
2714
2715         if (route->self_soloed()) {
2716                 delta = 1;
2717         } else {
2718                 delta = -1;
2719         }
2720
2721         RouteGroup* rg = route->route_group ();
2722         bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2723
2724         if (delta == 1 && Config->get_exclusive_solo()) {
2725                 
2726                 /* new solo: disable all other solos, but not the group if its solo-enabled */
2727
2728                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2729                         if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2730                             (leave_group_alone && ((*i)->route_group() == rg))) {
2731                                 continue;
2732                         }
2733                         (*i)->set_solo (false, this);
2734                 }
2735         }
2736
2737         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2738
2739         solo_update_disabled = true;
2740
2741         RouteList uninvolved;
2742
2743         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2744
2745         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2746                 bool via_sends_only;
2747                 bool in_signal_flow;
2748
2749                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2750                     (leave_group_alone && ((*i)->route_group() == rg))) {
2751                         continue;
2752                 }
2753
2754                 in_signal_flow = false;
2755
2756                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2757                 
2758                 if ((*i)->feeds (route, &via_sends_only)) {
2759                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2760                         if (!via_sends_only) {
2761                                 if (!route->soloed_by_others_upstream()) {
2762                                         (*i)->mod_solo_by_others_downstream (delta);
2763                                 }
2764                         } else {
2765                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2766                         }
2767                         in_signal_flow = true;
2768                 } else {
2769                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2770                 }
2771                 
2772                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2773
2774                 if (route->feeds (*i, &via_sends_only)) {
2775                         /* propagate solo upstream only if routing other than
2776                            sends is involved, but do consider the other route
2777                            (*i) to be part of the signal flow even if only
2778                            sends are involved.
2779                         */
2780                         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2781                                                                   route->name(),
2782                                                                   (*i)->name(),
2783                                                                   via_sends_only,
2784                                                                   route->soloed_by_others_downstream(),
2785                                                                   route->soloed_by_others_upstream()));
2786                         if (!via_sends_only) {
2787                                 if (!route->soloed_by_others_downstream()) {
2788                                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2789                                         (*i)->mod_solo_by_others_upstream (delta);
2790                                 } else {
2791                                         DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2792                                 }
2793                         } else {
2794                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2795                         }
2796                         in_signal_flow = true;
2797                 } else {
2798                         DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2799                 }
2800
2801                 if (!in_signal_flow) {
2802                         uninvolved.push_back (*i);
2803                 }
2804         }
2805
2806         solo_update_disabled = false;
2807         DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2808
2809         update_route_solo_state (r);
2810
2811         /* now notify that the mute state of the routes not involved in the signal
2812            pathway of the just-solo-changed route may have altered.
2813         */
2814
2815         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2816                 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2817                 (*i)->mute_changed (this);
2818         }
2819
2820         SoloChanged (); /* EMIT SIGNAL */
2821         set_dirty();
2822 }
2823
2824 void
2825 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2826 {
2827         /* now figure out if anything that matters is soloed (or is "listening")*/
2828
2829         bool something_soloed = false;
2830         uint32_t listeners = 0;
2831         uint32_t isolated = 0;
2832
2833         if (!r) {
2834                 r = routes.reader();
2835         }
2836
2837         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2838                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2839                         something_soloed = true;
2840                 }
2841
2842                 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2843                         if (Config->get_solo_control_is_listen_control()) {
2844                                 listeners++;
2845                         } else {
2846                                 (*i)->set_listen (false, this);
2847                         }
2848                 }
2849
2850                 if ((*i)->solo_isolated()) {
2851                         isolated++;
2852                 }
2853         }
2854
2855         if (something_soloed != _non_soloed_outs_muted) {
2856                 _non_soloed_outs_muted = something_soloed;
2857                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2858         }
2859
2860         _listen_cnt = listeners;
2861
2862         if (isolated != _solo_isolated_cnt) {
2863                 _solo_isolated_cnt = isolated;
2864                 IsolatedChanged (); /* EMIT SIGNAL */
2865         }
2866
2867         DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2868                                                   something_soloed, listeners, isolated));
2869 }
2870
2871 boost::shared_ptr<RouteList>
2872 Session::get_routes_with_internal_returns() const
2873 {
2874         boost::shared_ptr<RouteList> r = routes.reader ();
2875         boost::shared_ptr<RouteList> rl (new RouteList);
2876
2877         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2878                 if ((*i)->internal_return ()) {
2879                         rl->push_back (*i);
2880                 }
2881         }
2882         return rl;
2883 }
2884
2885 bool
2886 Session::io_name_is_legal (const std::string& name)
2887 {
2888         boost::shared_ptr<RouteList> r = routes.reader ();
2889
2890         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2891                 if ((*i)->name() == name) {
2892                         return false;
2893                 }
2894
2895                 if ((*i)->has_io_processor_named (name)) {
2896                         return false;
2897                 }
2898         }
2899
2900         return true;
2901 }
2902
2903 void
2904 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2905 {
2906         RouteList rl2;
2907         vector<string> connections;
2908
2909         /* if we are passed only a single route and we're not told to turn
2910          * others off, then just do the simple thing.
2911          */
2912
2913         if (flip_others == false && rl->size() == 1) {
2914                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2915                 if (mt) {
2916                         mt->set_input_active (onoff);
2917                         return;
2918                 }
2919         }
2920
2921         for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2922
2923                 PortSet& ps ((*rt)->input()->ports());
2924                 
2925                 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2926                         p->get_connections (connections);
2927                 }
2928                 
2929                 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2930                         routes_using_input_from (*s, rl2);
2931                 }
2932                 
2933                 /* scan all relevant routes to see if others are on or off */
2934                 
2935                 bool others_are_already_on = false;
2936                 
2937                 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2938
2939                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2940
2941                         if (!mt) {
2942                                 continue;
2943                         }
2944
2945                         if ((*r) != (*rt)) {
2946                                 if (mt->input_active()) {
2947                                         others_are_already_on = true;
2948                                 }
2949                         } else {
2950                                 /* this one needs changing */
2951                                 mt->set_input_active (onoff);
2952                         }
2953                 }
2954                 
2955                 if (flip_others) {
2956
2957                         /* globally reverse other routes */
2958                         
2959                         for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2960                                 if ((*r) != (*rt)) {
2961                                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2962                                         if (mt) {
2963                                                 mt->set_input_active (!others_are_already_on);
2964                                         }
2965                                 }
2966                         }
2967                 }
2968         }
2969 }
2970
2971 void
2972 Session::routes_using_input_from (const string& str, RouteList& rl)
2973 {
2974         boost::shared_ptr<RouteList> r = routes.reader();
2975
2976         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2977                 if ((*i)->input()->connected_to (str)) {
2978                         rl.push_back (*i);
2979                 }
2980         }
2981 }
2982
2983 boost::shared_ptr<Route>
2984 Session::route_by_name (string name)
2985 {
2986         boost::shared_ptr<RouteList> r = routes.reader ();
2987
2988         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2989                 if ((*i)->name() == name) {
2990                         return *i;
2991                 }
2992         }
2993
2994         return boost::shared_ptr<Route> ((Route*) 0);
2995 }
2996
2997 boost::shared_ptr<Route>
2998 Session::route_by_id (PBD::ID id)
2999 {
3000         boost::shared_ptr<RouteList> r = routes.reader ();
3001
3002         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3003                 if ((*i)->id() == id) {
3004                         return *i;
3005                 }
3006         }
3007
3008         return boost::shared_ptr<Route> ((Route*) 0);
3009 }
3010
3011 boost::shared_ptr<Track>
3012 Session::track_by_diskstream_id (PBD::ID id)
3013 {
3014         boost::shared_ptr<RouteList> r = routes.reader ();
3015
3016         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3017                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3018                 if (t && t->using_diskstream_id (id)) {
3019                         return t;
3020                 }
3021         }
3022
3023         return boost::shared_ptr<Track> ();
3024 }
3025
3026 boost::shared_ptr<Route>
3027 Session::route_by_remote_id (uint32_t id)
3028 {
3029         boost::shared_ptr<RouteList> r = routes.reader ();
3030
3031         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3032                 if ((*i)->remote_control_id() == id) {
3033                         return *i;
3034                 }
3035         }
3036
3037         return boost::shared_ptr<Route> ((Route*) 0);
3038 }
3039
3040 void
3041 Session::playlist_region_added (boost::weak_ptr<Region> w)
3042 {
3043         boost::shared_ptr<Region> r = w.lock ();
3044         if (!r) {
3045                 return;
3046         }
3047
3048         /* These are the operations that are currently in progress... */
3049         list<GQuark> curr = _current_trans_quarks;
3050         curr.sort ();
3051
3052         /* ...and these are the operations during which we want to update
3053            the session range location markers.
3054         */
3055         list<GQuark> ops;
3056         ops.push_back (Operations::capture);
3057         ops.push_back (Operations::paste);
3058         ops.push_back (Operations::duplicate_region);
3059         ops.push_back (Operations::insert_file);
3060         ops.push_back (Operations::insert_region);
3061         ops.push_back (Operations::drag_region_brush);
3062         ops.push_back (Operations::region_drag);
3063         ops.push_back (Operations::selection_grab);
3064         ops.push_back (Operations::region_fill);
3065         ops.push_back (Operations::fill_selection);
3066         ops.push_back (Operations::create_region);
3067         ops.push_back (Operations::region_copy);
3068         ops.push_back (Operations::fixed_time_region_copy);
3069         ops.sort ();
3070
3071         /* See if any of the current operations match the ones that we want */
3072         list<GQuark> in;
3073         set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3074
3075         /* If so, update the session range markers */
3076         if (!in.empty ()) {
3077                 maybe_update_session_range (r->position (), r->last_frame ());
3078         }
3079 }
3080
3081 /** Update the session range markers if a is before the current start or
3082  *  b is after the current end.
3083  */
3084 void
3085 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3086 {
3087         if (_state_of_the_state & Loading) {
3088                 return;
3089         }
3090
3091         if (_session_range_location == 0) {
3092
3093                 add_session_range_location (a, b);
3094
3095         } else {
3096
3097                 if (a < _session_range_location->start()) {
3098                         _session_range_location->set_start (a);
3099                 }
3100
3101                 if (b > _session_range_location->end()) {
3102                         _session_range_location->set_end (b);
3103                 }
3104         }
3105 }
3106
3107 void
3108 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3109 {
3110         for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3111                 maybe_update_session_range (i->to, i->to + i->length);
3112         }
3113 }
3114
3115 void
3116 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3117 {
3118         for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3119                 maybe_update_session_range (i->from, i->to);
3120         }
3121 }
3122
3123 /* Region management */
3124
3125 boost::shared_ptr<Region>
3126 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3127 {
3128         const RegionFactory::RegionMap& regions (RegionFactory::regions());
3129         RegionFactory::RegionMap::const_iterator i;
3130         boost::shared_ptr<Region> region;
3131
3132         Glib::Threads::Mutex::Lock lm (region_lock);
3133
3134         for (i = regions.begin(); i != regions.end(); ++i) {
3135
3136                 region = i->second;
3137
3138                 if (region->whole_file()) {
3139
3140                         if (child->source_equivalent (region)) {
3141                                 return region;
3142                         }
3143                 }
3144         }
3145
3146         return boost::shared_ptr<Region> ();
3147 }
3148
3149 int
3150 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3151 {
3152         set<boost::shared_ptr<Region> > relevant_regions;
3153
3154         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3155                 RegionFactory::get_regions_using_source (*s, relevant_regions);
3156         }
3157
3158         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3159                 set<boost::shared_ptr<Region> >::iterator tmp;
3160
3161                 tmp = r;
3162                 ++tmp;
3163
3164                 playlists->destroy_region (*r);
3165                 RegionFactory::map_remove (*r);
3166
3167                 (*r)->drop_sources ();
3168                 (*r)->drop_references ();
3169
3170                 relevant_regions.erase (r);
3171
3172                 r = tmp;
3173         }
3174
3175         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3176
3177                 {
3178                         Glib::Threads::Mutex::Lock ls (source_lock);
3179                         /* remove from the main source list */
3180                         sources.erase ((*s)->id());
3181                 }
3182
3183                 (*s)->mark_for_remove ();
3184                 (*s)->drop_references ();
3185
3186                 s = srcs.erase (s);
3187         }
3188
3189         return 0;
3190 }
3191
3192 int
3193 Session::remove_last_capture ()
3194 {
3195         list<boost::shared_ptr<Source> > srcs;
3196
3197         boost::shared_ptr<RouteList> rl = routes.reader ();
3198         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3199                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3200                 if (!tr) {
3201                         continue;
3202                 }
3203
3204                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3205
3206                 if (!l.empty()) {
3207                         srcs.insert (srcs.end(), l.begin(), l.end());
3208                         l.clear ();
3209                 }
3210         }
3211
3212         destroy_sources (srcs);
3213
3214         save_state (_current_snapshot_name);
3215
3216         return 0;
3217 }
3218
3219 /* Source Management */
3220
3221 void
3222 Session::add_source (boost::shared_ptr<Source> source)
3223 {
3224         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3225         pair<SourceMap::iterator,bool> result;
3226
3227         entry.first = source->id();
3228         entry.second = source;
3229
3230         {
3231                 Glib::Threads::Mutex::Lock lm (source_lock);
3232                 result = sources.insert (entry);
3233         }
3234
3235         if (result.second) {
3236
3237                 /* yay, new source */
3238
3239                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3240                 
3241                 if (fs) {
3242                         if (!fs->within_session()) {
3243                                 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3244                         }
3245                 }
3246                 
3247                 set_dirty();
3248
3249                 boost::shared_ptr<AudioFileSource> afs;
3250
3251                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3252                         if (Config->get_auto_analyse_audio()) {
3253                                 Analyser::queue_source_for_analysis (source, false);
3254                         }
3255                 }
3256
3257                 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3258         }
3259 }
3260
3261 void
3262 Session::remove_source (boost::weak_ptr<Source> src)
3263 {
3264         if (_state_of_the_state & Deletion) {
3265                 return;
3266         }
3267
3268         SourceMap::iterator i;
3269         boost::shared_ptr<Source> source = src.lock();
3270
3271         if (!source) {
3272                 return;
3273         }
3274
3275         {
3276                 Glib::Threads::Mutex::Lock lm (source_lock);
3277
3278                 if ((i = sources.find (source->id())) != sources.end()) {
3279                         sources.erase (i);
3280                 }
3281         }
3282
3283         if (!(_state_of_the_state & InCleanup)) {
3284
3285                 /* save state so we don't end up with a session file
3286                    referring to non-existent sources.
3287                 */
3288
3289                 save_state (_current_snapshot_name);
3290         }
3291 }
3292
3293 boost::shared_ptr<Source>
3294 Session::source_by_id (const PBD::ID& id)
3295 {
3296         Glib::Threads::Mutex::Lock lm (source_lock);
3297         SourceMap::iterator i;
3298         boost::shared_ptr<Source> source;
3299
3300         if ((i = sources.find (id)) != sources.end()) {
3301                 source = i->second;
3302         }
3303
3304         return source;
3305 }
3306
3307 boost::shared_ptr<AudioFileSource>
3308 Session::source_by_path_and_channel (const string& path, uint16_t chn) const
3309 {
3310         /* Restricted to audio files because only audio sources have channel
3311            as a property.
3312         */
3313
3314         Glib::Threads::Mutex::Lock lm (source_lock);
3315
3316         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3317                 boost::shared_ptr<AudioFileSource> afs
3318                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3319
3320                 if (afs && afs->path() == path && chn == afs->channel()) {
3321                         return afs;
3322                 }
3323         }
3324
3325         return boost::shared_ptr<AudioFileSource>();
3326 }
3327
3328 boost::shared_ptr<MidiSource>
3329 Session::source_by_path (const std::string& path) const
3330 {
3331         /* Restricted to MIDI files because audio sources require a channel
3332            for unique identification, in addition to a path.
3333         */
3334
3335         Glib::Threads::Mutex::Lock lm (source_lock);
3336
3337         for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3338                 boost::shared_ptr<MidiSource> ms
3339                         = boost::dynamic_pointer_cast<MidiSource>(s->second);
3340                 boost::shared_ptr<FileSource> fs
3341                         = boost::dynamic_pointer_cast<FileSource>(s->second);
3342                 
3343                 if (ms && fs && fs->path() == path) {
3344                         return ms;
3345                 }
3346         }
3347
3348         return boost::shared_ptr<MidiSource>();
3349 }
3350
3351 uint32_t
3352 Session::count_sources_by_origin (const string& path)
3353 {
3354         uint32_t cnt = 0;
3355         Glib::Threads::Mutex::Lock lm (source_lock);
3356
3357         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3358                 boost::shared_ptr<FileSource> fs
3359                         = boost::dynamic_pointer_cast<FileSource>(i->second);
3360
3361                 if (fs && fs->origin() == path) {
3362                         ++cnt;
3363                 }
3364         }
3365
3366         return cnt;
3367 }
3368
3369 string
3370 Session::generate_new_source_path_from_name (string path, string oldname, string newname, bool destructive)
3371 {
3372         string look_for;
3373         string old_basename = PBD::basename_nosuffix (oldname);
3374         string new_legalized = legalize_for_path (newname);
3375
3376         /* note: we know (or assume) the old path is already valid */
3377
3378         if (destructive) {
3379
3380                 /* destructive file sources have a name of the form:
3381
3382                     /path/to/Tnnnn-NAME(%[LR])?.wav
3383
3384                     the task here is to replace NAME with the new name.
3385                 */
3386
3387                 string dir;
3388                 string prefix;
3389                 string::size_type dash;
3390
3391                 dir = Glib::path_get_dirname (path);
3392                 path = Glib::path_get_basename (path);
3393
3394                 /* '-' is not a legal character for the NAME part of the path */
3395
3396                 if ((dash = path.find_last_of ('-')) == string::npos) {
3397                         return "";
3398                 }
3399
3400                 prefix = path.substr (0, dash);
3401
3402                 path += prefix;
3403                 path += '-';
3404                 path += new_legalized;
3405                 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3406                 path = Glib::build_filename (dir, path);
3407
3408         } else {
3409
3410                 /* non-destructive file sources have a name of the form:
3411
3412                     /path/to/NAME-nnnnn(%[LR])?.ext
3413
3414                     the task here is to replace NAME with the new name.
3415                 */
3416
3417                 string dir;
3418                 string suffix;
3419                 string::size_type dash;
3420                 string::size_type postfix;
3421
3422                 dir = Glib::path_get_dirname (path);
3423                 path = Glib::path_get_basename (path);
3424
3425                 /* '-' is not a legal character for the NAME part of the path */
3426
3427                 if ((dash = path.find_last_of ('-')) == string::npos) {
3428                         return "";
3429                 }
3430
3431                 suffix = path.substr (dash+1);
3432
3433                 // Suffix is now everything after the dash. Now we need to eliminate
3434                 // the nnnnn part, which is done by either finding a '%' or a '.'
3435
3436                 postfix = suffix.find_last_of ("%");
3437                 if (postfix == string::npos) {
3438                         postfix = suffix.find_last_of ('.');
3439                 }
3440
3441                 if (postfix != string::npos) {
3442                         suffix = suffix.substr (postfix);
3443                 } else {
3444                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3445                         return "";
3446                 }
3447
3448                 const uint32_t limit = 10000;
3449                 char buf[PATH_MAX+1];
3450
3451                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3452
3453                         snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
3454
3455                         if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
3456                                 path = Glib::build_filename (dir, buf);
3457                                 if (!source_by_path (path)) {
3458                                         break;
3459                                 }
3460                         }
3461
3462                         path = "";
3463                 }
3464
3465                 if (path.empty()) {
3466                         fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
3467                                                  newname) << endl;
3468                         /*NOTREACHED*/
3469                 }
3470         }
3471
3472         return path;
3473 }
3474
3475 /** Return the full path (in some session directory) for a new within-session source.
3476  * \a name must be a session-unique name that does not contain slashes
3477  *         (e.g. as returned by new_*_source_name)
3478  */
3479 string
3480 Session::new_source_path_from_name (DataType type, const string& name)
3481 {
3482         assert(name.find("/") == string::npos);
3483
3484         SessionDirectory sdir(get_best_session_directory_for_new_source());
3485
3486         std::string p;
3487         if (type == DataType::AUDIO) {
3488                 p = sdir.sound_path();
3489         } else if (type == DataType::MIDI) {
3490                 p = sdir.midi_path();
3491         } else {
3492                 error << "Unknown source type, unable to create file path" << endmsg;
3493                 return "";
3494         }
3495
3496         return Glib::build_filename (p, name);
3497 }
3498
3499 string
3500 Session::peak_path (string base) const
3501 {
3502         return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3503 }
3504
3505 /** Return a unique name based on \a base for a new internal audio source */
3506 string
3507 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3508 {
3509         uint32_t cnt;
3510         char buf[PATH_MAX+1];
3511         const uint32_t limit = 10000;
3512         string legalized;
3513         string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3514
3515         buf[0] = '\0';
3516         legalized = legalize_for_path (base);
3517
3518         // Find a "version" of the base name that doesn't exist in any of the possible directories.
3519         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3520
3521                 vector<space_and_path>::iterator i;
3522                 uint32_t existing = 0;
3523
3524                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3525
3526                         if (destructive) {
3527
3528                                 if (nchan < 2) {
3529                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
3530                                                   cnt, legalized.c_str(), ext.c_str());
3531                                 } else if (nchan == 2) {
3532                                         if (chan == 0) {
3533                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3534                                                           cnt, legalized.c_str(), ext.c_str());
3535                                         } else {
3536                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3537                                                           cnt, legalized.c_str(), ext.c_str());
3538                                         }
3539                                 } else if (nchan < 26) {
3540                                         snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3541                                                   cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3542                                 } else {
3543                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
3544                                                   cnt, legalized.c_str(), ext.c_str());
3545                                 }
3546
3547                         } else {
3548
3549                                 if (nchan < 2) {
3550                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3551                                 } else if (nchan == 2) {
3552                                         if (chan == 0) {
3553                                                 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3554                                         } else {
3555                                                 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3556                                         }
3557                                 } else if (nchan < 26) {
3558                                         snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3559                                 } else {
3560                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3561                                 }
3562                         }
3563
3564                         SessionDirectory sdir((*i).path);
3565
3566                         string spath = sdir.sound_path();
3567
3568                         /* note that we search *without* the extension so that
3569                            we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3570                            in the event that this new name is required for
3571                            a file format change.
3572                         */
3573
3574                         if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3575                                 existing++;
3576                                 break;
3577                         }
3578                 }
3579
3580                 if (existing == 0) {
3581                         break;
3582                 }
3583
3584                 if (cnt > limit) {
3585                         error << string_compose(
3586                                         _("There are already %1 recordings for %2, which I consider too many."),
3587                                         limit, base) << endmsg;
3588                         destroy ();
3589                         throw failed_constructor();
3590                 }
3591         }
3592
3593         return Glib::path_get_basename (buf);
3594 }
3595
3596 /** Create a new within-session audio source */
3597 boost::shared_ptr<AudioFileSource>
3598 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3599 {
3600         const string name    = new_audio_source_name (n, n_chans, chan, destructive);
3601         const string path    = new_source_path_from_name(DataType::AUDIO, name);
3602
3603         return boost::dynamic_pointer_cast<AudioFileSource> (
3604                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3605 }
3606
3607 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3608 string
3609 Session::new_midi_source_name (const string& owner_name)
3610 {
3611         uint32_t cnt;
3612         char buf[PATH_MAX+1];
3613         const uint32_t limit = 10000;
3614         string legalized;
3615         string possible_name;
3616
3617         buf[0] = '\0';
3618         legalized = legalize_for_path (owner_name);
3619
3620         // Find a "version" of the file name that doesn't exist in any of the possible directories.
3621
3622         for (cnt = 1; cnt <= limit; ++cnt) {
3623
3624                 vector<space_and_path>::iterator i;
3625                 uint32_t existing = 0;
3626
3627                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3628
3629                         SessionDirectory sdir((*i).path);
3630                         
3631                         snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3632                         possible_name = buf;
3633
3634                         std::string possible_path = Glib::build_filename (sdir.midi_path(), possible_name);
3635                         
3636                         if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3637                                 existing++;
3638                         }
3639
3640                         if (source_by_path (possible_path)) {
3641                                 existing++;
3642                         }
3643                 }
3644
3645                 if (existing == 0) {
3646                         break;
3647                 }
3648
3649                 if (cnt > limit) {
3650                         error << string_compose(
3651                                         _("There are already %1 recordings for %2, which I consider too many."),
3652                                         limit, owner_name) << endmsg;
3653                         destroy ();
3654                         throw failed_constructor();
3655                 }
3656         }
3657
3658         return possible_name;
3659 }
3660
3661
3662 /** Create a new within-session MIDI source */
3663 boost::shared_ptr<MidiSource>
3664 Session::create_midi_source_for_session (string const & basic_name)
3665 {
3666         std::string name;
3667
3668         if (name.empty()) {
3669                 name = new_midi_source_name (basic_name);
3670         }
3671
3672         const string path = new_source_path_from_name (DataType::MIDI, name);
3673
3674         return boost::dynamic_pointer_cast<SMFSource> (
3675                 SourceFactory::createWritable (
3676                         DataType::MIDI, *this, path, false, frame_rate()));
3677 }
3678
3679 /** Create a new within-session MIDI source */
3680 boost::shared_ptr<MidiSource>
3681 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3682 {
3683         /* the caller passes in the track the source will be used in,
3684            so that we can keep the numbering sane. 
3685            
3686            Rationale: a track with the name "Foo" that has had N
3687            captures carried out so far will ALREADY have a write source
3688            named "Foo-N+1.mid" waiting to be used for the next capture.
3689            
3690            If we call new_midi_source_name() we will get "Foo-N+2". But
3691            there is no region corresponding to "Foo-N+1", so when
3692            "Foo-N+2" appears in the track, the gap presents the user
3693            with odd behaviour - why did it skip past Foo-N+1?
3694            
3695            We could explain this to the user in some odd way, but
3696            instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3697            use "Foo-N+1" here.
3698            
3699            If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3700         */
3701         
3702         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3703         assert (mt);
3704         std::string name = track->steal_write_source_name ();
3705
3706         if (name.empty()) {
3707                 return boost::shared_ptr<MidiSource>();
3708         }
3709
3710         const string path = new_source_path_from_name (DataType::MIDI, name);
3711
3712         return boost::dynamic_pointer_cast<SMFSource> (
3713                 SourceFactory::createWritable (
3714                         DataType::MIDI, *this, path, false, frame_rate()));
3715 }
3716
3717
3718 void
3719 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3720 {
3721         if (playlist->hidden()) {
3722                 return;
3723         }
3724
3725         playlists->add (playlist);
3726
3727         if (unused) {
3728                 playlist->release();
3729         }
3730
3731         set_dirty();
3732 }
3733
3734 void
3735 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3736 {
3737         if (_state_of_the_state & Deletion) {
3738                 return;
3739         }
3740
3741         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3742
3743         if (!playlist) {
3744                 return;
3745         }
3746
3747         playlists->remove (playlist);
3748
3749         set_dirty();
3750 }
3751
3752 void
3753 Session::set_audition (boost::shared_ptr<Region> r)
3754 {
3755         pending_audition_region = r;
3756         add_post_transport_work (PostTransportAudition);
3757         _butler->schedule_transport_work ();
3758 }
3759
3760 void
3761 Session::audition_playlist ()
3762 {
3763         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3764         ev->region.reset ();
3765         queue_event (ev);
3766 }
3767
3768 void
3769 Session::non_realtime_set_audition ()
3770 {
3771         assert (pending_audition_region);
3772         auditioner->audition_region (pending_audition_region);
3773         pending_audition_region.reset ();
3774         AuditionActive (true); /* EMIT SIGNAL */
3775 }
3776
3777 void
3778 Session::audition_region (boost::shared_ptr<Region> r)
3779 {
3780         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3781         ev->region = r;
3782         queue_event (ev);
3783 }
3784
3785 void
3786 Session::cancel_audition ()
3787 {
3788         if (auditioner->auditioning()) {
3789                 auditioner->cancel_audition ();
3790                 AuditionActive (false); /* EMIT SIGNAL */
3791         }
3792 }
3793
3794 bool
3795 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3796 {
3797         if (a->is_monitor()) {
3798                 return true;
3799         }
3800         if (b->is_monitor()) {
3801                 return false;
3802         }
3803         return a->order_key () < b->order_key ();
3804 }
3805
3806 bool
3807 Session::is_auditioning () const
3808 {
3809         /* can be called before we have an auditioner object */
3810         if (auditioner) {
3811                 return auditioner->auditioning();
3812         } else {
3813                 return false;
3814         }
3815 }
3816
3817 void
3818 Session::graph_reordered ()
3819 {
3820         /* don't do this stuff if we are setting up connections
3821            from a set_state() call or creating new tracks. Ditto for deletion.
3822         */
3823
3824         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3825                 return;
3826         }
3827
3828         /* every track/bus asked for this to be handled but it was deferred because
3829            we were connecting. do it now.
3830         */
3831
3832         request_input_change_handling ();
3833
3834         resort_routes ();
3835
3836         /* force all diskstreams to update their capture offset values to
3837            reflect any changes in latencies within the graph.
3838         */
3839
3840         boost::shared_ptr<RouteList> rl = routes.reader ();
3841         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3842                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3843                 if (tr) {
3844                         tr->set_capture_offset ();
3845                 }
3846         }
3847 }
3848
3849 /** @return Number of frames that there is disk space available to write,
3850  *  if known.
3851  */
3852 boost::optional<framecnt_t>
3853 Session::available_capture_duration ()
3854 {
3855         Glib::Threads::Mutex::Lock lm (space_lock);
3856
3857         if (_total_free_4k_blocks_uncertain) {
3858                 return boost::optional<framecnt_t> ();
3859         }
3860         
3861         float sample_bytes_on_disk = 4.0; // keep gcc happy
3862
3863         switch (config.get_native_file_data_format()) {
3864         case FormatFloat:
3865                 sample_bytes_on_disk = 4.0;
3866                 break;
3867
3868         case FormatInt24:
3869                 sample_bytes_on_disk = 3.0;
3870                 break;
3871
3872         case FormatInt16:
3873                 sample_bytes_on_disk = 2.0;
3874                 break;
3875
3876         default:
3877                 /* impossible, but keep some gcc versions happy */
3878                 fatal << string_compose (_("programming error: %1"),
3879                                          X_("illegal native file data format"))
3880                       << endmsg;
3881                 /*NOTREACHED*/
3882         }
3883
3884         double scale = 4096.0 / sample_bytes_on_disk;
3885
3886         if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3887                 return max_framecnt;
3888         }
3889
3890         return (framecnt_t) floor (_total_free_4k_blocks * scale);
3891 }
3892
3893 void
3894 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3895 {
3896         {
3897                 RCUWriter<BundleList> writer (_bundles);
3898                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3899                 b->push_back (bundle);
3900         }
3901
3902         BundleAdded (bundle); /* EMIT SIGNAL */
3903
3904         set_dirty();
3905 }
3906
3907 void
3908 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3909 {
3910         bool removed = false;
3911
3912         {
3913                 RCUWriter<BundleList> writer (_bundles);
3914                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3915                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3916
3917                 if (i != b->end()) {
3918                         b->erase (i);
3919                         removed = true;
3920                 }
3921         }
3922
3923         if (removed) {
3924                  BundleRemoved (bundle); /* EMIT SIGNAL */
3925         }
3926
3927         set_dirty();
3928 }
3929
3930 boost::shared_ptr<Bundle>
3931 Session::bundle_by_name (string name) const
3932 {
3933         boost::shared_ptr<BundleList> b = _bundles.reader ();
3934
3935         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3936                 if ((*i)->name() == name) {
3937                         return* i;
3938                 }
3939         }
3940
3941         return boost::shared_ptr<Bundle> ();
3942 }
3943
3944 void
3945 Session::tempo_map_changed (const PropertyChange&)
3946 {
3947         clear_clicks ();
3948
3949         playlists->update_after_tempo_map_change ();
3950
3951         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3952
3953         set_dirty ();
3954 }
3955
3956 void
3957 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3958 {
3959         for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3960                 (*i)->recompute_frames_from_bbt ();
3961         }
3962 }
3963
3964 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3965  * the given count with the current block size.
3966  */
3967 void
3968 Session::ensure_buffers (ChanCount howmany)
3969 {
3970         BufferManager::ensure_buffers (howmany);
3971 }
3972
3973 void
3974 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3975 {
3976         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3977                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3978         }
3979 }
3980
3981 uint32_t
3982 Session::next_insert_id ()
3983 {
3984         /* this doesn't really loop forever. just think about it */
3985
3986         while (true) {
3987                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3988                         if (!insert_bitset[n]) {
3989                                 insert_bitset[n] = true;
3990                                 return n;
3991
3992                         }
3993                 }
3994
3995                 /* none available, so resize and try again */
3996
3997                 insert_bitset.resize (insert_bitset.size() + 16, false);
3998         }
3999 }
4000
4001 uint32_t
4002 Session::next_send_id ()
4003 {
4004         /* this doesn't really loop forever. just think about it */
4005
4006         while (true) {
4007                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
4008                         if (!send_bitset[n]) {
4009                                 send_bitset[n] = true;
4010                                 return n;
4011
4012                         }
4013                 }
4014
4015                 /* none available, so resize and try again */
4016
4017                 send_bitset.resize (send_bitset.size() + 16, false);
4018         }
4019 }
4020
4021 uint32_t
4022 Session::next_aux_send_id ()
4023 {
4024         /* this doesn't really loop forever. just think about it */
4025
4026         while (true) {
4027                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
4028                         if (!aux_send_bitset[n]) {
4029                                 aux_send_bitset[n] = true;
4030                                 return n;
4031
4032                         }
4033                 }
4034
4035                 /* none available, so resize and try again */
4036
4037                 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
4038         }
4039 }
4040
4041 uint32_t
4042 Session::next_return_id ()
4043 {
4044         /* this doesn't really loop forever. just think about it */
4045
4046         while (true) {
4047                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
4048                         if (!return_bitset[n]) {
4049                                 return_bitset[n] = true;
4050                                 return n;
4051
4052                         }
4053                 }
4054
4055                 /* none available, so resize and try again */
4056
4057                 return_bitset.resize (return_bitset.size() + 16, false);
4058         }
4059 }
4060
4061 void
4062 Session::mark_send_id (uint32_t id)
4063 {
4064         if (id >= send_bitset.size()) {
4065                 send_bitset.resize (id+16, false);
4066         }
4067         if (send_bitset[id]) {
4068                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4069         }
4070         send_bitset[id] = true;
4071 }
4072
4073 void
4074 Session::mark_aux_send_id (uint32_t id)
4075 {
4076         if (id >= aux_send_bitset.size()) {
4077                 aux_send_bitset.resize (id+16, false);
4078         }
4079         if (aux_send_bitset[id]) {
4080                 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4081         }
4082         aux_send_bitset[id] = true;
4083 }
4084
4085 void
4086 Session::mark_return_id (uint32_t id)
4087 {
4088         if (id >= return_bitset.size()) {
4089                 return_bitset.resize (id+16, false);
4090         }
4091         if (return_bitset[id]) {
4092                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4093         }
4094         return_bitset[id] = true;
4095 }
4096
4097 void
4098 Session::mark_insert_id (uint32_t id)
4099 {
4100         if (id >= insert_bitset.size()) {
4101                 insert_bitset.resize (id+16, false);
4102         }
4103         if (insert_bitset[id]) {
4104                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4105         }
4106         insert_bitset[id] = true;
4107 }
4108
4109 void
4110 Session::unmark_send_id (uint32_t id)
4111 {
4112         if (id < send_bitset.size()) {
4113                 send_bitset[id] = false;
4114         }
4115 }
4116
4117 void
4118 Session::unmark_aux_send_id (uint32_t id)
4119 {
4120         if (id < aux_send_bitset.size()) {
4121                 aux_send_bitset[id] = false;
4122         }
4123 }
4124
4125 void
4126 Session::unmark_return_id (uint32_t id)
4127 {
4128         if (id < return_bitset.size()) {
4129                 return_bitset[id] = false;
4130         }
4131 }
4132
4133 void
4134 Session::unmark_insert_id (uint32_t id)
4135 {
4136         if (id < insert_bitset.size()) {
4137                 insert_bitset[id] = false;
4138         }
4139 }
4140
4141 void
4142 Session::reset_native_file_format ()
4143 {
4144         boost::shared_ptr<RouteList> rl = routes.reader ();
4145         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4146                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4147                 if (tr) {
4148                         /* don't save state as we do this, there's no point
4149                          */
4150
4151                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4152                         tr->reset_write_sources (false);
4153                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4154                 }
4155         }
4156 }
4157
4158 bool
4159 Session::route_name_unique (string n) const
4160 {
4161         boost::shared_ptr<RouteList> r = routes.reader ();
4162
4163         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4164                 if ((*i)->name() == n) {
4165                         return false;
4166                 }
4167         }
4168
4169         return true;
4170 }
4171
4172 bool
4173 Session::route_name_internal (string n) const
4174 {
4175         if (auditioner && auditioner->name() == n) {
4176                 return true;
4177         }
4178
4179         if (_click_io && _click_io->name() == n) {
4180                 return true;
4181         }
4182
4183         return false;
4184 }
4185
4186 int
4187 Session::freeze_all (InterThreadInfo& itt)
4188 {
4189         boost::shared_ptr<RouteList> r = routes.reader ();
4190
4191         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4192
4193                 boost::shared_ptr<Track> t;
4194
4195                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4196                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
4197                            of every track.
4198                         */
4199                         t->freeze_me (itt);
4200                 }
4201         }
4202
4203         return 0;
4204 }
4205
4206 boost::shared_ptr<Region>
4207 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4208                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4209                           InterThreadInfo& itt, 
4210                           boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4211                           bool for_export)
4212 {
4213         boost::shared_ptr<Region> result;
4214         boost::shared_ptr<Playlist> playlist;
4215         boost::shared_ptr<AudioFileSource> fsource;
4216         uint32_t x;
4217         char buf[PATH_MAX+1];
4218         ChanCount diskstream_channels (track.n_channels());
4219         framepos_t position;
4220         framecnt_t this_chunk;
4221         framepos_t to_do;
4222         BufferSet buffers;
4223         SessionDirectory sdir(get_best_session_directory_for_new_source ());
4224         const string sound_dir = sdir.sound_path();
4225         framepos_t len = end - start;
4226         bool need_block_size_reset = false;
4227         string ext;
4228         ChanCount const max_proc = track.max_processor_streams ();
4229
4230         if (end <= start) {
4231                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4232                                          end, start) << endmsg;
4233                 return result;
4234         }
4235
4236         const framecnt_t chunk_size = (256 * 1024)/4;
4237
4238         // block all process callback handling
4239
4240         block_processing ();
4241
4242         /* call tree *MUST* hold route_lock */
4243
4244         if ((playlist = track.playlist()) == 0) {
4245                 goto out;
4246         }
4247
4248         ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4249
4250         for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4251
4252                 for (x = 0; x < 99999; ++x) {
4253                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 "%s", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1, ext.c_str());
4254                         if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4255                                 break;
4256                         }
4257                 }
4258
4259                 if (x == 99999) {
4260                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4261                         goto out;
4262                 }
4263
4264                 try {
4265                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4266                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4267                 }
4268
4269                 catch (failed_constructor& err) {
4270                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4271                         goto out;
4272                 }
4273
4274                 srcs.push_back (fsource);
4275         }
4276
4277         /* tell redirects that care that we are about to use a much larger
4278          * blocksize. this will flush all plugins too, so that they are ready
4279          * to be used for this process.
4280          */
4281
4282         need_block_size_reset = true;
4283         track.set_block_size (chunk_size);
4284
4285         position = start;
4286         to_do = len;
4287
4288         /* create a set of reasonably-sized buffers */
4289         buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
4290         buffers.set_count (max_proc);
4291
4292         for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4293                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4294                 if (afs)
4295                         afs->prepare_for_peakfile_writes ();
4296         }
4297
4298         while (to_do && !itt.cancel) {
4299
4300                 this_chunk = min (to_do, chunk_size);
4301
4302                 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4303                         goto out;
4304                 }
4305
4306                 uint32_t n = 0;
4307                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4308                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4309
4310                         if (afs) {
4311                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4312                                         goto out;
4313                                 }
4314                         }
4315                 }
4316
4317                 start += this_chunk;
4318                 to_do -= this_chunk;
4319
4320                 itt.progress = (float) (1.0 - ((double) to_do / len));
4321
4322         }
4323
4324         if (!itt.cancel) {
4325
4326                 time_t now;
4327                 struct tm* xnow;
4328                 time (&now);
4329                 xnow = localtime (&now);
4330
4331                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4332                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4333
4334                         if (afs) {
4335                                 afs->update_header (position, *xnow, now);
4336                                 afs->flush_header ();
4337                         }
4338                 }
4339
4340                 /* construct a region to represent the bounced material */
4341
4342                 PropertyList plist;
4343
4344                 plist.add (Properties::start, 0);
4345                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4346                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4347
4348                 result = RegionFactory::create (srcs, plist);
4349
4350         }
4351
4352   out:
4353         if (!result) {
4354                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4355                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4356
4357                         if (afs) {
4358                                 afs->mark_for_remove ();
4359                         }
4360
4361                         (*src)->drop_references ();
4362                 }
4363
4364         } else {
4365                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4366                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4367
4368                         if (afs)
4369                                 afs->done_with_peakfile_writes ();
4370                 }
4371         }
4372
4373
4374         if (need_block_size_reset) {
4375                 track.set_block_size (get_block_size());
4376         }
4377
4378         unblock_processing ();
4379
4380         return result;
4381 }
4382
4383 gain_t*
4384 Session::gain_automation_buffer() const
4385 {
4386         return ProcessThread::gain_automation_buffer ();
4387 }
4388
4389 gain_t*
4390 Session::send_gain_automation_buffer() const
4391 {
4392         return ProcessThread::send_gain_automation_buffer ();
4393 }
4394
4395 pan_t**
4396 Session::pan_automation_buffer() const
4397 {
4398         return ProcessThread::pan_automation_buffer ();
4399 }
4400
4401 BufferSet&
4402 Session::get_silent_buffers (ChanCount count)
4403 {
4404         return ProcessThread::get_silent_buffers (count);
4405 }
4406
4407 BufferSet&
4408 Session::get_scratch_buffers (ChanCount count, bool silence)
4409 {
4410         return ProcessThread::get_scratch_buffers (count, silence);
4411 }
4412
4413 BufferSet&
4414 Session::get_route_buffers (ChanCount count, bool silence)
4415 {
4416         return ProcessThread::get_route_buffers (count, silence);
4417 }
4418
4419
4420 BufferSet&
4421 Session::get_mix_buffers (ChanCount count)
4422 {
4423         return ProcessThread::get_mix_buffers (count);
4424 }
4425
4426 uint32_t
4427 Session::ntracks () const
4428 {
4429         uint32_t n = 0;
4430         boost::shared_ptr<RouteList> r = routes.reader ();
4431
4432         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4433                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4434                         ++n;
4435                 }
4436         }
4437
4438         return n;
4439 }
4440
4441 uint32_t
4442 Session::nbusses () const
4443 {
4444         uint32_t n = 0;
4445         boost::shared_ptr<RouteList> r = routes.reader ();
4446
4447         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4448                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4449                         ++n;
4450                 }
4451         }
4452
4453         return n;
4454 }
4455
4456 void
4457 Session::add_automation_list(AutomationList *al)
4458 {
4459         automation_lists[al->id()] = al;
4460 }
4461
4462 /** @return true if there is at least one record-enabled track, otherwise false */
4463 bool
4464 Session::have_rec_enabled_track () const
4465 {
4466         return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4467 }
4468
4469 /** Update the state of our rec-enabled tracks flag */
4470 void
4471 Session::update_have_rec_enabled_track ()
4472 {
4473         boost::shared_ptr<RouteList> rl = routes.reader ();
4474         RouteList::iterator i = rl->begin();
4475         while (i != rl->end ()) {
4476
4477                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4478                 if (tr && tr->record_enabled ()) {
4479                         break;
4480                 }
4481
4482                 ++i;
4483         }
4484
4485         int const old = g_atomic_int_get (&_have_rec_enabled_track);
4486
4487         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4488
4489         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4490                 RecordStateChanged (); /* EMIT SIGNAL */
4491         }
4492 }
4493
4494 void
4495 Session::listen_position_changed ()
4496 {
4497         boost::shared_ptr<RouteList> r = routes.reader ();
4498
4499         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4500                 (*i)->listen_position_changed ();
4501         }
4502 }
4503
4504 void
4505 Session::solo_control_mode_changed ()
4506 {
4507         /* cancel all solo or all listen when solo control mode changes */
4508
4509         if (soloing()) {
4510                 set_solo (get_routes(), false);
4511         } else if (listening()) {
4512                 set_listen (get_routes(), false);
4513         }
4514 }
4515
4516 /** Called when a property of one of our route groups changes */
4517 void
4518 Session::route_group_property_changed (RouteGroup* rg)
4519 {
4520         RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4521 }
4522
4523 /** Called when a route is added to one of our route groups */
4524 void
4525 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4526 {
4527         RouteAddedToRouteGroup (rg, r);
4528 }
4529
4530 /** Called when a route is removed from one of our route groups */
4531 void
4532 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4533 {
4534         RouteRemovedFromRouteGroup (rg, r);
4535 }
4536
4537 boost::shared_ptr<RouteList>
4538 Session::get_routes_with_regions_at (framepos_t const p) const
4539 {
4540         boost::shared_ptr<RouteList> r = routes.reader ();
4541         boost::shared_ptr<RouteList> rl (new RouteList);
4542
4543         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4544                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4545                 if (!tr) {
4546                         continue;
4547                 }
4548
4549                 boost::shared_ptr<Playlist> pl = tr->playlist ();
4550                 if (!pl) {
4551                         continue;
4552                 }
4553
4554                 if (pl->has_region_at (p)) {
4555                         rl->push_back (*i);
4556                 }
4557         }
4558
4559         return rl;
4560 }
4561
4562 void
4563 Session::goto_end ()
4564 {
4565         if (_session_range_location) {
4566                 request_locate (_session_range_location->end(), false);
4567         } else {
4568                 request_locate (0, false);
4569         }
4570 }
4571
4572 void
4573 Session::goto_start ()
4574 {
4575         if (_session_range_location) {
4576                 request_locate (_session_range_location->start(), false);
4577         } else {
4578                 request_locate (0, false);
4579         }
4580 }
4581
4582 framepos_t
4583 Session::current_start_frame () const
4584 {
4585         return _session_range_location ? _session_range_location->start() : 0;
4586 }
4587
4588 framepos_t
4589 Session::current_end_frame () const
4590 {
4591         return _session_range_location ? _session_range_location->end() : 0;
4592 }
4593
4594 void
4595 Session::add_session_range_location (framepos_t start, framepos_t end)
4596 {
4597         _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4598         _locations->add (_session_range_location);
4599 }
4600
4601 void
4602 Session::step_edit_status_change (bool yn)
4603 {
4604         bool send = false;
4605
4606         bool val = false;
4607         if (yn) {
4608                 send = (_step_editors == 0);
4609                 val = true;
4610
4611                 _step_editors++;
4612         } else {
4613                 send = (_step_editors == 1);
4614                 val = false;
4615
4616                 if (_step_editors > 0) {
4617                         _step_editors--;
4618                 }
4619         }
4620
4621         if (send) {
4622                 StepEditStatusChange (val);
4623         }
4624 }
4625
4626
4627 void
4628 Session::start_time_changed (framepos_t old)
4629 {
4630         /* Update the auto loop range to match the session range
4631            (unless the auto loop range has been changed by the user)
4632         */
4633
4634         Location* s = _locations->session_range_location ();
4635         if (s == 0) {
4636                 return;
4637         }
4638
4639         Location* l = _locations->auto_loop_location ();
4640
4641         if (l && l->start() == old) {
4642                 l->set_start (s->start(), true);
4643         }
4644 }
4645
4646 void
4647 Session::end_time_changed (framepos_t old)
4648 {
4649         /* Update the auto loop range to match the session range
4650            (unless the auto loop range has been changed by the user)
4651         */
4652
4653         Location* s = _locations->session_range_location ();
4654         if (s == 0) {
4655                 return;
4656         }
4657
4658         Location* l = _locations->auto_loop_location ();
4659
4660         if (l && l->end() == old) {
4661                 l->set_end (s->end(), true);
4662         }
4663 }
4664
4665 string
4666 Session::source_search_path (DataType type) const
4667 {
4668         vector<string> s;
4669
4670         if (session_dirs.size() == 1) {
4671                 switch (type) {
4672                 case DataType::AUDIO:
4673                         s.push_back (_session_dir->sound_path());
4674                         break;
4675                 case DataType::MIDI:
4676                         s.push_back (_session_dir->midi_path());
4677                         break;
4678                 }
4679         } else {
4680                 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4681                         SessionDirectory sdir (i->path);
4682                         switch (type) {
4683                         case DataType::AUDIO:
4684                                 s.push_back (sdir.sound_path());
4685                                 break;
4686                         case DataType::MIDI:
4687                                 s.push_back (sdir.midi_path());
4688                                 break;
4689                         }
4690                 }
4691         }
4692
4693         if (type == DataType::AUDIO) {
4694                 const string sound_path_2X = _session_dir->sound_path_2X();
4695                 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4696                         if (find (s.begin(), s.end(), sound_path_2X) == s.end()) {
4697                                 s.push_back (sound_path_2X);
4698                         }
4699                 }
4700         }
4701
4702         /* now check the explicit (possibly user-specified) search path
4703          */
4704
4705         vector<string> dirs;
4706
4707         switch (type) {
4708         case DataType::AUDIO:
4709                 split (config.get_audio_search_path (), dirs, ':');
4710                 break;
4711         case DataType::MIDI:
4712                 split (config.get_midi_search_path (), dirs, ':');
4713                 break;
4714         }
4715
4716         for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4717                 if (find (s.begin(), s.end(), *i) == s.end()) {
4718                         s.push_back (*i);
4719                 }
4720         }
4721         
4722         string search_path;
4723
4724         for (vector<string>::iterator si = s.begin(); si != s.end(); ++si) {
4725                 if (!search_path.empty()) {
4726                         search_path += ':';
4727                 }
4728                 search_path += *si;
4729         }
4730
4731         return search_path;
4732 }
4733
4734 void
4735 Session::ensure_search_path_includes (const string& path, DataType type)
4736 {
4737         string search_path;
4738         vector<string> dirs;
4739
4740         if (path == ".") {
4741                 return;
4742         }
4743
4744         switch (type) {
4745         case DataType::AUDIO:
4746                 search_path = config.get_audio_search_path ();
4747                 break;
4748         case DataType::MIDI:
4749                 search_path = config.get_midi_search_path ();
4750                 break;
4751         }
4752
4753         split (search_path, dirs, ':');
4754
4755         for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4756                 /* No need to add this new directory if it has the same inode as
4757                    an existing one; checking inode rather than name prevents duplicated
4758                    directories when we are using symlinks.
4759
4760                    On Windows, I think we could just do if (*i == path) here.
4761                 */
4762                 if (PBD::equivalent_paths (*i, path)) {
4763                         return;
4764                 }
4765         }
4766
4767         if (!search_path.empty()) {
4768                 search_path += ':';
4769         }
4770
4771         search_path += path;
4772
4773         switch (type) {
4774         case DataType::AUDIO:
4775                 config.set_audio_search_path (search_path);
4776                 break;
4777         case DataType::MIDI:
4778                 config.set_midi_search_path (search_path);
4779                 break;
4780         }
4781 }
4782
4783 boost::shared_ptr<Speakers>
4784 Session::get_speakers()
4785 {
4786         return _speakers;
4787 }
4788
4789 list<string>
4790 Session::unknown_processors () const
4791 {
4792         list<string> p;
4793
4794         boost::shared_ptr<RouteList> r = routes.reader ();
4795         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4796                 list<string> t = (*i)->unknown_processors ();
4797                 copy (t.begin(), t.end(), back_inserter (p));
4798         }
4799
4800         p.sort ();
4801         p.unique ();
4802
4803         return p;
4804 }
4805
4806 void
4807 Session::update_latency (bool playback)
4808 {
4809         DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4810
4811         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4812                 return;
4813         }
4814
4815         boost::shared_ptr<RouteList> r = routes.reader ();
4816         framecnt_t max_latency = 0;
4817
4818         if (playback) {
4819                 /* reverse the list so that we work backwards from the last route to run to the first */
4820                 RouteList* rl = routes.reader().get();
4821                 r.reset (new RouteList (*rl));
4822                 reverse (r->begin(), r->end());
4823         }
4824
4825         /* compute actual latency values for the given direction and store them all in per-port
4826            structures. this will also publish the same values (to JACK) so that computation of latency
4827            for routes can consistently use public latency values.
4828         */
4829
4830         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4831                 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4832         }
4833
4834         /* because we latency compensate playback, our published playback latencies should
4835            be the same for all output ports - all material played back by ardour has
4836            the same latency, whether its caused by plugins or by latency compensation. since
4837            these may differ from the values computed above, reset all playback port latencies
4838            to the same value.
4839         */
4840
4841         DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4842
4843         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4844                 (*i)->set_public_port_latencies (max_latency, playback);
4845         }
4846
4847         if (playback) {
4848
4849                 post_playback_latency ();
4850
4851         } else {
4852
4853                 post_capture_latency ();
4854         }
4855
4856         DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4857 }
4858
4859 void
4860 Session::post_playback_latency ()
4861 {
4862         set_worst_playback_latency ();
4863
4864         boost::shared_ptr<RouteList> r = routes.reader ();
4865
4866         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4867                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4868                         _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4869                 }
4870         }
4871
4872         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4873                 (*i)->set_latency_compensation (_worst_track_latency);
4874         }
4875 }
4876
4877 void
4878 Session::post_capture_latency ()
4879 {
4880         set_worst_capture_latency ();
4881
4882         /* reflect any changes in capture latencies into capture offsets
4883          */
4884
4885         boost::shared_ptr<RouteList> rl = routes.reader();
4886         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4887                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4888                 if (tr) {
4889                         tr->set_capture_offset ();
4890                 }
4891         }
4892 }
4893
4894 void
4895 Session::initialize_latencies ()
4896 {
4897         {
4898                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4899                 update_latency (false);
4900                 update_latency (true);
4901         }
4902
4903         set_worst_io_latencies ();
4904 }
4905
4906 void
4907 Session::set_worst_io_latencies ()
4908 {
4909         set_worst_playback_latency ();
4910         set_worst_capture_latency ();
4911 }
4912
4913 void
4914 Session::set_worst_playback_latency ()
4915 {
4916         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4917                 return;
4918         }
4919
4920         _worst_output_latency = 0;
4921
4922         if (!_engine.connected()) {
4923                 return;
4924         }
4925
4926         boost::shared_ptr<RouteList> r = routes.reader ();
4927
4928         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4929                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4930         }
4931
4932         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4933 }
4934
4935 void
4936 Session::set_worst_capture_latency ()
4937 {
4938         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4939                 return;
4940         }
4941
4942         _worst_input_latency = 0;
4943
4944         if (!_engine.connected()) {
4945                 return;
4946         }
4947
4948         boost::shared_ptr<RouteList> r = routes.reader ();
4949
4950         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4951                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4952         }
4953
4954         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4955 }
4956
4957 void
4958 Session::update_latency_compensation (bool force_whole_graph)
4959 {
4960         bool some_track_latency_changed = false;
4961
4962         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4963                 return;
4964         }
4965
4966         DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4967
4968         _worst_track_latency = 0;
4969
4970         boost::shared_ptr<RouteList> r = routes.reader ();
4971
4972         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4973                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4974                         framecnt_t tl;
4975                         if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4976                                 some_track_latency_changed = true;
4977                         }
4978                         _worst_track_latency = max (tl, _worst_track_latency);
4979                 }
4980         }
4981
4982         DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4983                                                      (some_track_latency_changed ? "yes" : "no")));
4984
4985         DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4986         
4987         if (some_track_latency_changed || force_whole_graph)  {
4988                 _engine.update_latencies ();
4989         }
4990
4991
4992         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4993                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4994                 if (!tr) {
4995                         continue;
4996                 }
4997                 tr->set_capture_offset ();
4998         }
4999 }
5000
5001 char
5002 Session::session_name_is_legal (const string& path)
5003 {
5004         char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
5005
5006         for (int i = 0; illegal_chars[i]; ++i) {
5007                 if (path.find (illegal_chars[i]) != string::npos) {
5008                         return illegal_chars[i];
5009                 }
5010         }
5011
5012         return 0;
5013 }
5014
5015 uint32_t 
5016 Session::next_control_id () const
5017 {
5018         int subtract = 0;
5019
5020         /* the monitor bus remote ID is in a different
5021          * "namespace" than regular routes. its existence doesn't
5022          * affect normal (low) numbered routes.
5023          */
5024
5025         if (_monitor_out) {
5026                 subtract++;
5027         }
5028
5029         return nroutes() - subtract;
5030 }
5031
5032 void
5033 Session::notify_remote_id_change ()
5034 {
5035         if (deletion_in_progress()) {
5036                 return;
5037         }
5038
5039         switch (Config->get_remote_model()) {
5040         case MixerOrdered:
5041                 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
5042                 break;
5043         default:
5044                 break;
5045         }
5046 }
5047
5048 void
5049 Session::sync_order_keys ()
5050 {
5051         if (deletion_in_progress()) {
5052                 return;
5053         }
5054
5055         /* tell everyone that something has happened to the sort keys
5056            and let them sync up with the change(s)
5057            this will give objects that manage the sort order keys the
5058            opportunity to keep them in sync if they wish to.
5059         */
5060
5061         DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5062
5063         Route::SyncOrderKeys (); /* EMIT SIGNAL */
5064
5065         DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5066 }
5067
5068 bool
5069 Session::operation_in_progress (GQuark op) const
5070 {
5071         return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5072 }
5073
5074 boost::shared_ptr<Port>
5075 Session::ltc_input_port () const
5076 {
5077         return _ltc_input->nth (0);
5078 }
5079
5080 boost::shared_ptr<Port>
5081 Session::ltc_output_port () const
5082 {
5083         return _ltc_output->nth (0);
5084 }
5085
5086 void
5087 Session::reconnect_ltc_input ()
5088 {
5089         if (_ltc_input) {
5090
5091                 string src = Config->get_ltc_source_port();
5092
5093                 _ltc_input->disconnect (this);
5094
5095                 if (src != _("None") && !src.empty())  {
5096                         _ltc_input->nth (0)->connect (src);
5097                 }
5098         }
5099 }
5100
5101 void
5102 Session::reconnect_ltc_output ()
5103 {
5104         if (_ltc_output) {
5105
5106 #if 0
5107                 string src = Config->get_ltc_sink_port();
5108
5109                 _ltc_output->disconnect (this);
5110
5111                 if (src != _("None") && !src.empty())  {
5112                         _ltc_output->nth (0)->connect (src);
5113                 }
5114 #endif
5115         }
5116 }