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