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