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