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