2 Copyright (C) 1999-2004 Paul Davis
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.
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.
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.
25 #include <cstdio> /* sprintf(3) ... grrr */
31 #include <sigc++/bind.h>
32 #include <sigc++/retype.h>
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
37 #include <pbd/error.h>
38 #include <glibmm/thread.h>
39 #include <pbd/pathscanner.h>
40 #include <pbd/stl_delete.h>
41 #include <pbd/basename.h>
42 #include <pbd/stacktrace.h>
43 #include <pbd/file_utils.h>
45 #include <ardour/audioengine.h>
46 #include <ardour/configuration.h>
47 #include <ardour/session.h>
48 #include <ardour/session_directory.h>
49 #include <ardour/utils.h>
50 #include <ardour/audio_diskstream.h>
51 #include <ardour/audioplaylist.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/audiofilesource.h>
54 #include <ardour/midi_diskstream.h>
55 #include <ardour/midi_playlist.h>
56 #include <ardour/midi_region.h>
57 #include <ardour/smf_source.h>
58 #include <ardour/auditioner.h>
59 #include <ardour/recent_sessions.h>
60 #include <ardour/io_processor.h>
61 #include <ardour/send.h>
62 #include <ardour/processor.h>
63 #include <ardour/plugin_insert.h>
64 #include <ardour/port_insert.h>
65 #include <ardour/auto_bundle.h>
66 #include <ardour/slave.h>
67 #include <ardour/tempo.h>
68 #include <ardour/audio_track.h>
69 #include <ardour/midi_track.h>
70 #include <ardour/cycle_timer.h>
71 #include <ardour/named_selection.h>
72 #include <ardour/crossfade.h>
73 #include <ardour/playlist.h>
74 #include <ardour/click.h>
75 #include <ardour/data_type.h>
76 #include <ardour/buffer_set.h>
77 #include <ardour/source_factory.h>
78 #include <ardour/region_factory.h>
79 #include <ardour/filename_extensions.h>
80 #include <ardour/session_directory.h>
81 #include <ardour/tape_file_matcher.h>
84 #include <ardour/osc.h>
90 using namespace ARDOUR;
92 using boost::shared_ptr;
95 static const int CPU_CACHE_ALIGN = 64;
97 static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
100 bool Session::_disable_all_loaded_plugins = false;
102 Session::compute_peak_t Session::compute_peak = 0;
103 Session::find_peaks_t Session::find_peaks = 0;
104 Session::apply_gain_to_buffer_t Session::apply_gain_to_buffer = 0;
105 Session::mix_buffers_with_gain_t Session::mix_buffers_with_gain = 0;
106 Session::mix_buffers_no_gain_t Session::mix_buffers_no_gain = 0;
108 sigc::signal<int> Session::AskAboutPendingState;
109 sigc::signal<void> Session::SendFeedback;
111 sigc::signal<void> Session::SMPTEOffsetChanged;
112 sigc::signal<void> Session::StartTimeChanged;
113 sigc::signal<void> Session::EndTimeChanged;
115 Session::Session (AudioEngine &eng,
116 const string& fullpath,
117 const string& snapshot_name,
121 _scratch_buffers(new BufferSet()),
122 _silent_buffers(new BufferSet()),
123 _mix_buffers(new BufferSet()),
124 _mmc_port (default_mmc_port),
125 _mtc_port (default_mtc_port),
126 _midi_port (default_midi_port),
127 _session_dir (new SessionDirectory(fullpath)),
128 pending_events (2048),
129 //midi_requests (128), // the size of this should match the midi request pool size
130 _send_smpte_update (false),
131 diskstreams (new DiskstreamList),
132 routes (new RouteList),
133 auditioner ((Auditioner*) 0),
134 _bundle_xml_node (0),
140 if (!eng.connected()) {
141 throw failed_constructor();
144 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
146 n_physical_outputs = _engine.n_physical_outputs();
147 n_physical_inputs = _engine.n_physical_inputs();
149 first_stage_init (fullpath, snapshot_name);
151 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
153 if (create (new_session, mix_template, compute_initial_length())) {
155 throw failed_constructor ();
159 if (second_stage_init (new_session)) {
161 throw failed_constructor ();
164 store_recent_sessions(_name, _path);
166 bool was_dirty = dirty();
168 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
170 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
173 DirtyChanged (); /* EMIT SIGNAL */
177 Session::Session (AudioEngine &eng,
179 string snapshot_name,
180 AutoConnectOption input_ac,
181 AutoConnectOption output_ac,
182 uint32_t control_out_channels,
183 uint32_t master_out_channels,
184 uint32_t requested_physical_in,
185 uint32_t requested_physical_out,
186 nframes_t initial_length)
189 _scratch_buffers(new BufferSet()),
190 _silent_buffers(new BufferSet()),
191 _mix_buffers(new BufferSet()),
192 _mmc_port (default_mmc_port),
193 _mtc_port (default_mtc_port),
194 _midi_port (default_midi_port),
195 _session_dir ( new SessionDirectory(fullpath)),
196 pending_events (2048),
197 //midi_requests (16),
198 _send_smpte_update (false),
199 diskstreams (new DiskstreamList),
200 routes (new RouteList),
201 _bundle_xml_node (0),
207 if (!eng.connected()) {
208 throw failed_constructor();
211 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
213 n_physical_outputs = _engine.n_physical_outputs();
214 n_physical_inputs = _engine.n_physical_inputs();
216 if (n_physical_inputs) {
217 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
220 if (n_physical_outputs) {
221 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
224 first_stage_init (fullpath, snapshot_name);
226 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
229 if (create (new_session, string(), initial_length)) {
231 throw failed_constructor ();
236 /* set up Master Out and Control Out if necessary */
241 if (control_out_channels) {
242 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
243 r->set_remote_control_id (control_id++);
248 if (master_out_channels) {
249 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
250 r->set_remote_control_id (control_id);
254 /* prohibit auto-connect to master, because there isn't one */
255 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
259 add_routes (rl, false);
264 Config->set_input_auto_connect (input_ac);
265 Config->set_output_auto_connect (output_ac);
267 if (second_stage_init (new_session)) {
269 throw failed_constructor ();
272 store_recent_sessions (_name, _path);
274 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
276 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
287 /* if we got to here, leaving pending capture state around
291 remove_pending_capture_state ();
293 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
295 _engine.remove_session ();
297 GoingAway (); /* EMIT SIGNAL */
303 /* clear history so that no references to objects are held any more */
307 /* clear state tree so that no references to objects are held any more */
313 terminate_butler_thread ();
314 //terminate_midi_thread ();
316 if (click_data && click_data != default_click) {
317 delete [] click_data;
320 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
321 delete [] click_emphasis_data;
326 delete _scratch_buffers;
327 delete _silent_buffers;
330 AudioDiskstream::free_working_buffers();
332 #undef TRACK_DESTRUCTION
333 #ifdef TRACK_DESTRUCTION
334 cerr << "delete named selections\n";
335 #endif /* TRACK_DESTRUCTION */
336 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
337 NamedSelectionList::iterator tmp;
346 #ifdef TRACK_DESTRUCTION
347 cerr << "delete playlists\n";
348 #endif /* TRACK_DESTRUCTION */
349 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
350 PlaylistList::iterator tmp;
355 (*i)->drop_references ();
360 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
361 PlaylistList::iterator tmp;
366 (*i)->drop_references ();
372 unused_playlists.clear ();
374 #ifdef TRACK_DESTRUCTION
375 cerr << "delete regions\n";
376 #endif /* TRACK_DESTRUCTION */
378 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
379 RegionList::iterator tmp;
384 i->second->drop_references ();
391 #ifdef TRACK_DESTRUCTION
392 cerr << "delete routes\n";
393 #endif /* TRACK_DESTRUCTION */
395 RCUWriter<RouteList> writer (routes);
396 boost::shared_ptr<RouteList> r = writer.get_copy ();
397 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
398 (*i)->drop_references ();
401 /* writer goes out of scope and updates master */
406 #ifdef TRACK_DESTRUCTION
407 cerr << "delete diskstreams\n";
408 #endif /* TRACK_DESTRUCTION */
410 RCUWriter<DiskstreamList> dwriter (diskstreams);
411 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
412 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
413 (*i)->drop_references ();
417 diskstreams.flush ();
419 #ifdef TRACK_DESTRUCTION
420 cerr << "delete audio sources\n";
421 #endif /* TRACK_DESTRUCTION */
422 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
423 SourceMap::iterator tmp;
428 i->second->drop_references ();
435 #ifdef TRACK_DESTRUCTION
436 cerr << "delete mix groups\n";
437 #endif /* TRACK_DESTRUCTION */
438 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
439 list<RouteGroup*>::iterator tmp;
449 #ifdef TRACK_DESTRUCTION
450 cerr << "delete edit groups\n";
451 #endif /* TRACK_DESTRUCTION */
452 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
453 list<RouteGroup*>::iterator tmp;
463 if (butler_mixdown_buffer) {
464 delete [] butler_mixdown_buffer;
467 if (butler_gain_buffer) {
468 delete [] butler_gain_buffer;
471 Crossfade::set_buffer_size (0);
479 Session::set_worst_io_latencies ()
481 _worst_output_latency = 0;
482 _worst_input_latency = 0;
484 if (!_engine.connected()) {
488 boost::shared_ptr<RouteList> r = routes.reader ();
490 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
491 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
492 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
497 Session::when_engine_running ()
499 string first_physical_output;
501 /* we don't want to run execute this again */
503 set_block_size (_engine.frames_per_cycle());
504 set_frame_rate (_engine.frame_rate());
506 Config->map_parameters (mem_fun (*this, &Session::config_changed));
508 /* every time we reconnect, recompute worst case output latencies */
510 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
512 if (synced_to_jack()) {
513 _engine.transport_stop ();
516 if (Config->get_jack_time_master()) {
517 _engine.transport_locate (_transport_frame);
525 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
527 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
529 /* existing state for Click */
531 if (_click_io->set_state (*child->children().front()) == 0) {
533 _clicking = Config->get_clicking ();
537 error << _("could not setup Click I/O") << endmsg;
543 /* default state for Click */
545 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
547 if (first_physical_output.length()) {
548 if (_click_io->add_output_port (first_physical_output, this)) {
549 // relax, even though its an error
551 _clicking = Config->get_clicking ();
557 catch (failed_constructor& err) {
558 error << _("cannot setup Click I/O") << endmsg;
561 set_worst_io_latencies ();
564 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
567 /* Create a set of Bundle objects that map
568 to the physical outputs currently available
573 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
575 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
577 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
579 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
584 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
586 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
588 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
590 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
597 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
599 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
601 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
603 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
604 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
609 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
611 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
613 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
615 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
616 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
625 /* create master/control ports */
630 /* force the master to ignore any later call to this */
632 if (_master_out->pending_state_node) {
633 _master_out->ports_became_legal();
636 /* no panner resets till we are through */
638 _master_out->defer_pan_reset ();
640 while (_master_out->n_inputs().n_audio()
641 < _master_out->input_maximum().n_audio()) {
642 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
643 error << _("cannot setup master inputs")
649 while (_master_out->n_outputs().n_audio()
650 < _master_out->output_maximum().n_audio()) {
651 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
652 error << _("cannot setup master outputs")
659 _master_out->allow_pan_reset ();
663 shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
665 c->set_channels (_master_out->n_inputs().n_total());
666 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
667 c->set_port (n, _master_out->input(n)->name());
674 /* catch up on send+insert cnts */
678 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
681 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
682 if (id > insert_cnt) {
690 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
693 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
701 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
704 /* hook us up to the engine */
706 _engine.set_session (this);
711 osc->set_session (*this);
717 Session::hookup_io ()
719 /* stop graph reordering notifications from
720 causing resorts, etc.
723 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
726 if (auditioner == 0) {
728 /* we delay creating the auditioner till now because
729 it makes its own connections to ports.
730 the engine has to be running for this to work.
734 auditioner.reset (new Auditioner (*this));
737 catch (failed_constructor& err) {
738 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
742 /* Tell all IO objects to create their ports */
748 vector<string> cports;
750 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
751 if (_control_out->add_input_port ("", this)) {
752 error << _("cannot setup control inputs")
758 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
759 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
760 error << _("cannot set up master outputs")
768 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
770 for (n = 0; n < ni; ++n) {
771 cports.push_back (_control_out->input(n)->name());
774 boost::shared_ptr<RouteList> r = routes.reader ();
776 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
777 (*x)->set_control_outs (cports);
781 /* load bundles, which we may have postponed earlier on */
782 if (_bundle_xml_node) {
783 load_bundles (*_bundle_xml_node);
784 delete _bundle_xml_node;
787 /* Tell all IO objects to connect themselves together */
789 IO::enable_connecting ();
791 /* Now reset all panners */
793 IO::reset_panners ();
795 /* Anyone who cares about input state, wake up and do something */
797 IOConnectionsComplete (); /* EMIT SIGNAL */
799 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
802 /* now handle the whole enchilada as if it was one
808 /* update mixer solo state */
814 Session::playlist_length_changed ()
816 /* we can't just increase end_location->end() if pl->get_maximum_extent()
817 if larger. if the playlist used to be the longest playlist,
818 and its now shorter, we have to decrease end_location->end(). hence,
819 we have to iterate over all diskstreams and check the
820 playlists currently in use.
826 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
828 boost::shared_ptr<Playlist> playlist;
830 if ((playlist = dstream->playlist()) != 0) {
831 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
834 /* see comment in playlist_length_changed () */
839 Session::record_enabling_legal () const
841 /* this used to be in here, but survey says.... we don't need to restrict it */
842 // if (record_status() == Recording) {
846 if (Config->get_all_safe()) {
853 Session::reset_input_monitor_state ()
855 if (transport_rolling()) {
857 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
859 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
860 if ((*i)->record_enabled ()) {
861 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
862 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
866 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
868 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
869 if ((*i)->record_enabled ()) {
870 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
871 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
878 Session::auto_punch_start_changed (Location* location)
880 replace_event (Event::PunchIn, location->start());
882 if (get_record_enabled() && Config->get_punch_in()) {
883 /* capture start has been changed, so save new pending state */
884 save_state ("", true);
889 Session::auto_punch_end_changed (Location* location)
891 nframes_t when_to_stop = location->end();
892 // when_to_stop += _worst_output_latency + _worst_input_latency;
893 replace_event (Event::PunchOut, when_to_stop);
897 Session::auto_punch_changed (Location* location)
899 nframes_t when_to_stop = location->end();
901 replace_event (Event::PunchIn, location->start());
902 //when_to_stop += _worst_output_latency + _worst_input_latency;
903 replace_event (Event::PunchOut, when_to_stop);
907 Session::auto_loop_changed (Location* location)
909 replace_event (Event::AutoLoop, location->end(), location->start());
911 if (transport_rolling() && play_loop) {
913 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
915 if (_transport_frame > location->end()) {
916 // relocate to beginning of loop
917 clear_events (Event::LocateRoll);
919 request_locate (location->start(), true);
922 else if (Config->get_seamless_loop() && !loop_changing) {
924 // schedule a locate-roll to refill the diskstreams at the
926 loop_changing = true;
928 if (location->end() > last_loopend) {
929 clear_events (Event::LocateRoll);
930 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
937 last_loopend = location->end();
942 Session::set_auto_punch_location (Location* location)
946 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
947 auto_punch_start_changed_connection.disconnect();
948 auto_punch_end_changed_connection.disconnect();
949 auto_punch_changed_connection.disconnect();
950 existing->set_auto_punch (false, this);
951 remove_event (existing->start(), Event::PunchIn);
952 clear_events (Event::PunchOut);
953 auto_punch_location_changed (0);
962 if (location->end() <= location->start()) {
963 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
967 auto_punch_start_changed_connection.disconnect();
968 auto_punch_end_changed_connection.disconnect();
969 auto_punch_changed_connection.disconnect();
971 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
972 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
973 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
975 location->set_auto_punch (true, this);
976 auto_punch_location_changed (location);
980 Session::set_auto_loop_location (Location* location)
984 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
985 auto_loop_start_changed_connection.disconnect();
986 auto_loop_end_changed_connection.disconnect();
987 auto_loop_changed_connection.disconnect();
988 existing->set_auto_loop (false, this);
989 remove_event (existing->end(), Event::AutoLoop);
990 auto_loop_location_changed (0);
999 if (location->end() <= location->start()) {
1000 error << _("Session: you can't use a mark for auto loop") << endmsg;
1004 last_loopend = location->end();
1006 auto_loop_start_changed_connection.disconnect();
1007 auto_loop_end_changed_connection.disconnect();
1008 auto_loop_changed_connection.disconnect();
1010 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1011 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1012 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1014 location->set_auto_loop (true, this);
1015 auto_loop_location_changed (location);
1019 Session::locations_added (Location* ignored)
1025 Session::locations_changed ()
1027 _locations.apply (*this, &Session::handle_locations_changed);
1031 Session::handle_locations_changed (Locations::LocationList& locations)
1033 Locations::LocationList::iterator i;
1035 bool set_loop = false;
1036 bool set_punch = false;
1038 for (i = locations.begin(); i != locations.end(); ++i) {
1042 if (location->is_auto_punch()) {
1043 set_auto_punch_location (location);
1046 if (location->is_auto_loop()) {
1047 set_auto_loop_location (location);
1054 set_auto_loop_location (0);
1057 set_auto_punch_location (0);
1064 Session::enable_record ()
1066 /* XXX really atomic compare+swap here */
1067 if (g_atomic_int_get (&_record_status) != Recording) {
1068 g_atomic_int_set (&_record_status, Recording);
1069 _last_record_location = _transport_frame;
1070 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1072 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1073 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1074 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1075 if ((*i)->record_enabled ()) {
1076 (*i)->monitor_input (true);
1081 RecordStateChanged ();
1086 Session::disable_record (bool rt_context, bool force)
1090 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1092 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1093 g_atomic_int_set (&_record_status, Disabled);
1095 if (rs == Recording) {
1096 g_atomic_int_set (&_record_status, Enabled);
1100 // FIXME: timestamp correct? [DR]
1101 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1102 // does this /need/ to be sent in all cases?
1104 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1106 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1107 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1109 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1110 if ((*i)->record_enabled ()) {
1111 (*i)->monitor_input (false);
1116 RecordStateChanged (); /* emit signal */
1119 remove_pending_capture_state ();
1125 Session::step_back_from_record ()
1127 /* XXX really atomic compare+swap here */
1128 if (g_atomic_int_get (&_record_status) == Recording) {
1129 g_atomic_int_set (&_record_status, Enabled);
1131 if (Config->get_monitoring_model() == HardwareMonitoring) {
1132 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1134 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1135 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1136 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1137 (*i)->monitor_input (false);
1145 Session::maybe_enable_record ()
1147 g_atomic_int_set (&_record_status, Enabled);
1149 /* this function is currently called from somewhere other than an RT thread.
1150 this save_state() call therefore doesn't impact anything.
1153 save_state ("", true);
1155 if (_transport_speed) {
1156 if (!Config->get_punch_in()) {
1160 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1161 RecordStateChanged (); /* EMIT SIGNAL */
1168 Session::audible_frame () const
1174 /* the first of these two possible settings for "offset"
1175 mean that the audible frame is stationary until
1176 audio emerges from the latency compensation
1179 the second means that the audible frame is stationary
1180 until audio would emerge from a physical port
1181 in the absence of any plugin latency compensation
1184 offset = _worst_output_latency;
1186 if (offset > current_block_size) {
1187 offset -= current_block_size;
1189 /* XXX is this correct? if we have no external
1190 physical connections and everything is internal
1191 then surely this is zero? still, how
1192 likely is that anyway?
1194 offset = current_block_size;
1197 if (synced_to_jack()) {
1198 tf = _engine.transport_frame();
1200 tf = _transport_frame;
1203 if (_transport_speed == 0) {
1213 if (!non_realtime_work_pending()) {
1217 /* take latency into account */
1226 Session::set_frame_rate (nframes_t frames_per_second)
1228 /** \fn void Session::set_frame_size(nframes_t)
1229 the AudioEngine object that calls this guarantees
1230 that it will not be called while we are also in
1231 ::process(). Its fine to do things that block
1235 _base_frame_rate = frames_per_second;
1239 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1243 // XXX we need some equivalent to this, somehow
1244 // SndFileSource::setup_standard_crossfades (frames_per_second);
1248 /* XXX need to reset/reinstantiate all LADSPA plugins */
1252 Session::set_block_size (nframes_t nframes)
1254 /* the AudioEngine guarantees
1255 that it will not be called while we are also in
1256 ::process(). It is therefore fine to do things that block
1262 current_block_size = nframes;
1264 ensure_buffers(_scratch_buffers->available());
1266 if (_gain_automation_buffer) {
1267 delete [] _gain_automation_buffer;
1269 _gain_automation_buffer = new gain_t[nframes];
1271 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1273 boost::shared_ptr<RouteList> r = routes.reader ();
1275 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1276 (*i)->set_block_size (nframes);
1279 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1280 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1281 (*i)->set_block_size (nframes);
1284 set_worst_io_latencies ();
1289 Session::set_default_fade (float steepness, float fade_msecs)
1292 nframes_t fade_frames;
1294 /* Don't allow fade of less 1 frame */
1296 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1303 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1307 default_fade_msecs = fade_msecs;
1308 default_fade_steepness = steepness;
1311 // jlc, WTF is this!
1312 Glib::RWLock::ReaderLock lm (route_lock);
1313 AudioRegion::set_default_fade (steepness, fade_frames);
1318 /* XXX have to do this at some point */
1319 /* foreach region using default fade, reset, then
1320 refill_all_diskstream_buffers ();
1325 struct RouteSorter {
1326 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1327 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1329 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1332 if (r1->fed_by.empty()) {
1333 if (r2->fed_by.empty()) {
1334 /* no ardour-based connections inbound to either route. just use signal order */
1335 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1337 /* r2 has connections, r1 does not; run r1 early */
1341 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1348 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1350 shared_ptr<Route> r2;
1352 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1353 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1357 /* make a copy of the existing list of routes that feed r1 */
1359 set<shared_ptr<Route> > existing = r1->fed_by;
1361 /* for each route that feeds r1, recurse, marking it as feeding
1365 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1368 /* r2 is a route that feeds r1 which somehow feeds base. mark
1369 base as being fed by r2
1372 rbase->fed_by.insert (r2);
1376 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1380 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1384 /* now recurse, so that we can mark base as being fed by
1385 all routes that feed r2
1388 trace_terminal (r2, rbase);
1395 Session::resort_routes ()
1397 /* don't do anything here with signals emitted
1398 by Routes while we are being destroyed.
1401 if (_state_of_the_state & Deletion) {
1408 RCUWriter<RouteList> writer (routes);
1409 shared_ptr<RouteList> r = writer.get_copy ();
1410 resort_routes_using (r);
1411 /* writer goes out of scope and forces update */
1416 Session::resort_routes_using (shared_ptr<RouteList> r)
1418 RouteList::iterator i, j;
1420 for (i = r->begin(); i != r->end(); ++i) {
1422 (*i)->fed_by.clear ();
1424 for (j = r->begin(); j != r->end(); ++j) {
1426 /* although routes can feed themselves, it will
1427 cause an endless recursive descent if we
1428 detect it. so don't bother checking for
1436 if ((*j)->feeds (*i)) {
1437 (*i)->fed_by.insert (*j);
1442 for (i = r->begin(); i != r->end(); ++i) {
1443 trace_terminal (*i, *i);
1450 cerr << "finished route resort\n";
1452 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1453 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1460 list<boost::shared_ptr<MidiTrack> >
1461 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1463 char track_name[32];
1464 uint32_t track_id = 0;
1467 RouteList new_routes;
1468 list<boost::shared_ptr<MidiTrack> > ret;
1469 //uint32_t control_id;
1471 // FIXME: need physical I/O and autoconnect stuff for MIDI
1473 /* count existing midi tracks */
1476 shared_ptr<RouteList> r = routes.reader ();
1478 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1479 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1480 if (!(*i)->is_hidden()) {
1482 //channels_used += (*i)->n_inputs().n_midi();
1489 vector<string> physinputs;
1490 vector<string> physoutputs;
1491 uint32_t nphysical_in;
1492 uint32_t nphysical_out;
1494 _engine.get_physical_outputs (physoutputs);
1495 _engine.get_physical_inputs (physinputs);
1496 control_id = ntracks() + nbusses() + 1;
1501 /* check for duplicate route names, since we might have pre-existing
1502 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1503 save, close,restart,add new route - first named route is now
1511 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1513 if (route_by_name (track_name) == 0) {
1517 } while (track_id < (UINT_MAX-1));
1520 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1521 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1526 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1527 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1533 shared_ptr<MidiTrack> track;
1536 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1538 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1539 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1545 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1549 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1550 port = physinputs[(channels_used+x)%nphysical_in];
1553 if (port.length() && track->connect_input (track->input (x), port, this)) {
1559 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1563 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1564 port = physoutputs[(channels_used+x)%nphysical_out];
1565 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1567 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1571 if (port.length() && track->connect_output (track->output (x), port, this)) {
1576 channels_used += track->n_inputs ().n_midi();
1580 track->midi_diskstream()->non_realtime_input_change();
1582 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1583 //track->set_remote_control_id (control_id);
1585 new_routes.push_back (track);
1586 ret.push_back (track);
1589 catch (failed_constructor &err) {
1590 error << _("Session: could not create new midi track.") << endmsg;
1593 /* we need to get rid of this, since the track failed to be created */
1594 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1597 RCUWriter<DiskstreamList> writer (diskstreams);
1598 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1599 ds->remove (track->midi_diskstream());
1606 catch (AudioEngine::PortRegistrationFailure& pfe) {
1608 error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1611 /* we need to get rid of this, since the track failed to be created */
1612 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1615 RCUWriter<DiskstreamList> writer (diskstreams);
1616 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1617 ds->remove (track->midi_diskstream());
1628 if (!new_routes.empty()) {
1629 add_routes (new_routes, false);
1630 save_state (_current_snapshot_name);
1636 list<boost::shared_ptr<AudioTrack> >
1637 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1639 char track_name[32];
1640 uint32_t track_id = 0;
1642 uint32_t channels_used = 0;
1644 RouteList new_routes;
1645 list<boost::shared_ptr<AudioTrack> > ret;
1646 uint32_t control_id;
1648 /* count existing audio tracks */
1651 shared_ptr<RouteList> r = routes.reader ();
1653 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1654 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1655 if (!(*i)->is_hidden()) {
1657 channels_used += (*i)->n_inputs().n_audio();
1663 vector<string> physinputs;
1664 vector<string> physoutputs;
1665 uint32_t nphysical_in;
1666 uint32_t nphysical_out;
1668 _engine.get_physical_outputs (physoutputs);
1669 _engine.get_physical_inputs (physinputs);
1670 control_id = ntracks() + nbusses() + 1;
1674 /* check for duplicate route names, since we might have pre-existing
1675 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1676 save, close,restart,add new route - first named route is now
1684 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1686 if (route_by_name (track_name) == 0) {
1690 } while (track_id < (UINT_MAX-1));
1692 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1693 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1698 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1699 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1704 shared_ptr<AudioTrack> track;
1707 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1709 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1710 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1711 input_channels, output_channels)
1717 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1721 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1722 port = physinputs[(channels_used+x)%nphysical_in];
1725 if (port.length() && track->connect_input (track->input (x), port, this)) {
1731 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1735 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1736 port = physoutputs[(channels_used+x)%nphysical_out];
1737 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1739 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1743 if (port.length() && track->connect_output (track->output (x), port, this)) {
1748 channels_used += track->n_inputs ().n_audio();
1750 track->audio_diskstream()->non_realtime_input_change();
1752 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1753 track->set_remote_control_id (control_id);
1756 new_routes.push_back (track);
1757 ret.push_back (track);
1760 catch (failed_constructor &err) {
1761 error << _("Session: could not create new audio track.") << endmsg;
1764 /* we need to get rid of this, since the track failed to be created */
1765 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1768 RCUWriter<DiskstreamList> writer (diskstreams);
1769 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1770 ds->remove (track->audio_diskstream());
1777 catch (AudioEngine::PortRegistrationFailure& pfe) {
1779 error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1782 /* we need to get rid of this, since the track failed to be created */
1783 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1786 RCUWriter<DiskstreamList> writer (diskstreams);
1787 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1788 ds->remove (track->audio_diskstream());
1799 if (!new_routes.empty()) {
1800 add_routes (new_routes, true);
1807 Session::set_remote_control_ids ()
1809 RemoteModel m = Config->get_remote_model();
1811 shared_ptr<RouteList> r = routes.reader ();
1813 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1814 if ( MixerOrdered == m) {
1815 long order = (*i)->order_key(N_("signal"));
1816 (*i)->set_remote_control_id( order+1 );
1817 } else if ( EditorOrdered == m) {
1818 long order = (*i)->order_key(N_("editor"));
1819 (*i)->set_remote_control_id( order+1 );
1820 } else if ( UserOrdered == m) {
1821 //do nothing ... only changes to remote id's are initiated by user
1828 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1831 uint32_t bus_id = 1;
1835 uint32_t control_id;
1837 /* count existing audio busses */
1840 shared_ptr<RouteList> r = routes.reader ();
1842 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1843 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1844 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1851 vector<string> physinputs;
1852 vector<string> physoutputs;
1854 _engine.get_physical_outputs (physoutputs);
1855 _engine.get_physical_inputs (physinputs);
1856 control_id = ntracks() + nbusses() + 1;
1861 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1865 if (route_by_name (bus_name) == 0) {
1869 } while (bus_id < (UINT_MAX-1));
1872 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1874 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1875 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1876 input_channels, output_channels)
1881 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1885 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1886 port = physinputs[((n+x)%n_physical_inputs)];
1889 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1894 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1898 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1899 port = physoutputs[((n+x)%n_physical_outputs)];
1900 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1902 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1906 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1911 bus->set_remote_control_id (control_id);
1914 ret.push_back (bus);
1918 catch (failed_constructor &err) {
1919 error << _("Session: could not create new audio route.") << endmsg;
1923 catch (AudioEngine::PortRegistrationFailure& pfe) {
1924 error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1934 add_routes (ret, true);
1942 Session::add_routes (RouteList& new_routes, bool save)
1945 RCUWriter<RouteList> writer (routes);
1946 shared_ptr<RouteList> r = writer.get_copy ();
1947 r->insert (r->end(), new_routes.begin(), new_routes.end());
1948 resort_routes_using (r);
1951 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1953 boost::weak_ptr<Route> wpr (*x);
1955 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1956 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1957 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1958 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1960 if ((*x)->is_master()) {
1964 if ((*x)->is_control()) {
1965 _control_out = (*x);
1968 add_bundle ((*x)->bundle_for_inputs());
1969 add_bundle ((*x)->bundle_for_outputs());
1972 if (_control_out && IO::connecting_legal) {
1974 vector<string> cports;
1975 uint32_t ni = _control_out->n_inputs().n_audio();
1977 for (uint32_t n = 0; n < ni; ++n) {
1978 cports.push_back (_control_out->input(n)->name());
1981 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1982 (*x)->set_control_outs (cports);
1989 save_state (_current_snapshot_name);
1992 RouteAdded (new_routes); /* EMIT SIGNAL */
1996 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
1998 /* need to do this in case we're rolling at the time, to prevent false underruns */
1999 dstream->do_refill_with_alloc ();
2001 dstream->set_block_size (current_block_size);
2004 RCUWriter<DiskstreamList> writer (diskstreams);
2005 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2006 ds->push_back (dstream);
2007 /* writer goes out of scope, copies ds back to main */
2010 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2011 /* this will connect to future changes, and check the current length */
2012 diskstream_playlist_changed (dstream);
2014 dstream->prepare ();
2019 Session::remove_route (shared_ptr<Route> route)
2022 RCUWriter<RouteList> writer (routes);
2023 shared_ptr<RouteList> rs = writer.get_copy ();
2027 /* deleting the master out seems like a dumb
2028 idea, but its more of a UI policy issue
2032 if (route == _master_out) {
2033 _master_out = shared_ptr<Route> ();
2036 if (route == _control_out) {
2037 _control_out = shared_ptr<Route> ();
2039 /* cancel control outs for all routes */
2041 vector<string> empty;
2043 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2044 (*r)->set_control_outs (empty);
2048 update_route_solo_state ();
2050 /* writer goes out of scope, forces route list update */
2054 boost::shared_ptr<Diskstream> ds;
2056 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2057 ds = t->diskstream();
2063 RCUWriter<DiskstreamList> dsl (diskstreams);
2064 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2069 find_current_end ();
2071 // We need to disconnect the routes inputs and outputs
2073 route->disconnect_inputs (0);
2074 route->disconnect_outputs (0);
2076 update_latency_compensation (false, false);
2079 /* get rid of it from the dead wood collection in the route list manager */
2081 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2085 /* try to cause everyone to drop their references */
2087 route->drop_references ();
2089 /* save the new state of the world */
2091 if (save_state (_current_snapshot_name)) {
2092 save_history (_current_snapshot_name);
2097 Session::route_mute_changed (void* src)
2103 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2105 if (solo_update_disabled) {
2111 boost::shared_ptr<Route> route = wpr.lock ();
2114 /* should not happen */
2115 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2119 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2121 shared_ptr<RouteList> r = routes.reader ();
2123 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2125 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2129 /* don't mess with busses */
2131 if (dynamic_cast<Track*>((*i).get()) == 0) {
2137 /* don't mess with tracks */
2139 if (dynamic_cast<Track*>((*i).get()) != 0) {
2144 if ((*i) != route &&
2145 ((*i)->mix_group () == 0 ||
2146 (*i)->mix_group () != route->mix_group () ||
2147 !route->mix_group ()->is_active())) {
2149 if ((*i)->soloed()) {
2151 /* if its already soloed, and solo latching is enabled,
2152 then leave it as it is.
2155 if (Config->get_solo_latched()) {
2162 solo_update_disabled = true;
2163 (*i)->set_solo (false, src);
2164 solo_update_disabled = false;
2168 bool something_soloed = false;
2169 bool same_thing_soloed = false;
2170 bool signal = false;
2172 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2173 if ((*i)->soloed()) {
2174 something_soloed = true;
2175 if (dynamic_cast<Track*>((*i).get())) {
2177 same_thing_soloed = true;
2182 same_thing_soloed = true;
2190 if (something_soloed != currently_soloing) {
2192 currently_soloing = something_soloed;
2195 modify_solo_mute (is_track, same_thing_soloed);
2198 SoloActive (currently_soloing); /* EMIT SIGNAL */
2201 SoloChanged (); /* EMIT SIGNAL */
2207 Session::update_route_solo_state ()
2210 bool is_track = false;
2211 bool signal = false;
2213 /* caller must hold RouteLock */
2215 /* this is where we actually implement solo by changing
2216 the solo mute setting of each track.
2219 shared_ptr<RouteList> r = routes.reader ();
2221 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2222 if ((*i)->soloed()) {
2224 if (dynamic_cast<Track*>((*i).get())) {
2231 if (mute != currently_soloing) {
2233 currently_soloing = mute;
2236 if (!is_track && !mute) {
2238 /* nothing is soloed */
2240 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2241 (*i)->set_solo_mute (false);
2251 modify_solo_mute (is_track, mute);
2254 SoloActive (currently_soloing);
2259 Session::modify_solo_mute (bool is_track, bool mute)
2261 shared_ptr<RouteList> r = routes.reader ();
2263 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2267 /* only alter track solo mute */
2269 if (dynamic_cast<Track*>((*i).get())) {
2270 if ((*i)->soloed()) {
2271 (*i)->set_solo_mute (!mute);
2273 (*i)->set_solo_mute (mute);
2279 /* only alter bus solo mute */
2281 if (!dynamic_cast<Track*>((*i).get())) {
2283 if ((*i)->soloed()) {
2285 (*i)->set_solo_mute (false);
2289 /* don't mute master or control outs
2290 in response to another bus solo
2293 if ((*i) != _master_out &&
2294 (*i) != _control_out) {
2295 (*i)->set_solo_mute (mute);
2306 Session::catch_up_on_solo ()
2308 /* this is called after set_state() to catch the full solo
2309 state, which can't be correctly determined on a per-route
2310 basis, but needs the global overview that only the session
2313 update_route_solo_state();
2317 Session::route_by_name (string name)
2319 shared_ptr<RouteList> r = routes.reader ();
2321 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2322 if ((*i)->name() == name) {
2327 return shared_ptr<Route> ((Route*) 0);
2331 Session::route_by_id (PBD::ID id)
2333 shared_ptr<RouteList> r = routes.reader ();
2335 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2336 if ((*i)->id() == id) {
2341 return shared_ptr<Route> ((Route*) 0);
2345 Session::route_by_remote_id (uint32_t id)
2347 shared_ptr<RouteList> r = routes.reader ();
2349 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2350 if ((*i)->remote_control_id() == id) {
2355 return shared_ptr<Route> ((Route*) 0);
2359 Session::find_current_end ()
2361 if (_state_of_the_state & Loading) {
2365 nframes_t max = get_maximum_extent ();
2367 if (max > end_location->end()) {
2368 end_location->set_end (max);
2370 DurationChanged(); /* EMIT SIGNAL */
2375 Session::get_maximum_extent () const
2380 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2382 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2383 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2384 if ((me = pl->get_maximum_extent()) > max) {
2392 boost::shared_ptr<Diskstream>
2393 Session::diskstream_by_name (string name)
2395 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2397 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2398 if ((*i)->name() == name) {
2403 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2406 boost::shared_ptr<Diskstream>
2407 Session::diskstream_by_id (const PBD::ID& id)
2409 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2411 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2412 if ((*i)->id() == id) {
2417 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2420 /* Region management */
2423 Session::new_region_name (string old)
2425 string::size_type last_period;
2427 string::size_type len = old.length() + 64;
2430 if ((last_period = old.find_last_of ('.')) == string::npos) {
2432 /* no period present - add one explicitly */
2435 last_period = old.length() - 1;
2440 number = atoi (old.substr (last_period+1).c_str());
2444 while (number < (UINT_MAX-1)) {
2446 RegionList::const_iterator i;
2451 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2454 for (i = regions.begin(); i != regions.end(); ++i) {
2455 if (i->second->name() == sbuf) {
2460 if (i == regions.end()) {
2465 if (number != (UINT_MAX-1)) {
2469 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2474 Session::region_name (string& result, string base, bool newlevel) const
2479 assert(base.find("/") == string::npos);
2483 Glib::Mutex::Lock lm (region_lock);
2485 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2493 /* XXX this is going to be slow. optimize me later */
2498 string::size_type pos;
2500 pos = base.find_last_of ('.');
2502 /* pos may be npos, but then we just use entire base */
2504 subbase = base.substr (0, pos);
2508 bool name_taken = true;
2511 Glib::Mutex::Lock lm (region_lock);
2513 for (int n = 1; n < 5000; ++n) {
2516 snprintf (buf, sizeof (buf), ".%d", n);
2521 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2522 if (i->second->name() == result) {
2535 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2543 Session::add_region (boost::shared_ptr<Region> region)
2545 boost::shared_ptr<Region> other;
2549 Glib::Mutex::Lock lm (region_lock);
2551 RegionList::iterator x;
2553 for (x = regions.begin(); x != regions.end(); ++x) {
2557 if (region->region_list_equivalent (other)) {
2562 if (x == regions.end()) {
2564 pair<RegionList::key_type,RegionList::mapped_type> entry;
2566 entry.first = region->id();
2567 entry.second = region;
2569 pair<RegionList::iterator,bool> x = regions.insert (entry);
2581 /* mark dirty because something has changed even if we didn't
2582 add the region to the region list.
2588 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2589 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2590 RegionAdded (region); /* EMIT SIGNAL */
2595 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2597 boost::shared_ptr<Region> region (weak_region.lock ());
2603 if (what_changed & Region::HiddenChanged) {
2604 /* relay hidden changes */
2605 RegionHiddenChange (region);
2610 Session::remove_region (boost::weak_ptr<Region> weak_region)
2612 RegionList::iterator i;
2613 boost::shared_ptr<Region> region (weak_region.lock ());
2619 bool removed = false;
2622 Glib::Mutex::Lock lm (region_lock);
2624 if ((i = regions.find (region->id())) != regions.end()) {
2630 /* mark dirty because something has changed even if we didn't
2631 remove the region from the region list.
2637 RegionRemoved(region); /* EMIT SIGNAL */
2641 boost::shared_ptr<Region>
2642 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2644 RegionList::iterator i;
2645 boost::shared_ptr<Region> region;
2647 Glib::Mutex::Lock lm (region_lock);
2649 for (i = regions.begin(); i != regions.end(); ++i) {
2653 if (region->whole_file()) {
2655 if (child->source_equivalent (region)) {
2661 return boost::shared_ptr<Region> ();
2665 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2667 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2668 (*i)->get_region_list_equivalent_regions (region, result);
2672 Session::destroy_region (boost::shared_ptr<Region> region)
2674 vector<boost::shared_ptr<Source> > srcs;
2677 boost::shared_ptr<AudioRegion> aregion;
2679 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2683 if (aregion->playlist()) {
2684 aregion->playlist()->destroy_region (region);
2687 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2688 srcs.push_back (aregion->source (n));
2692 region->drop_references ();
2694 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2696 if (!(*i)->used()) {
2697 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2700 (afs)->mark_for_remove ();
2703 (*i)->drop_references ();
2705 cerr << "source was not used by any playlist\n";
2713 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2715 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2716 destroy_region (*i);
2722 Session::remove_last_capture ()
2724 list<boost::shared_ptr<Region> > r;
2726 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2728 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2729 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2732 r.insert (r.end(), l.begin(), l.end());
2737 destroy_regions (r);
2739 save_state (_current_snapshot_name);
2745 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2751 /* Source Management */
2753 Session::add_source (boost::shared_ptr<Source> source)
2755 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2756 pair<SourceMap::iterator,bool> result;
2758 entry.first = source->id();
2759 entry.second = source;
2762 Glib::Mutex::Lock lm (source_lock);
2763 result = sources.insert (entry);
2766 if (result.second) {
2767 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2773 Session::remove_source (boost::weak_ptr<Source> src)
2775 SourceMap::iterator i;
2776 boost::shared_ptr<Source> source = src.lock();
2783 Glib::Mutex::Lock lm (source_lock);
2785 if ((i = sources.find (source->id())) != sources.end()) {
2790 if (!_state_of_the_state & InCleanup) {
2792 /* save state so we don't end up with a session file
2793 referring to non-existent sources.
2796 save_state (_current_snapshot_name);
2800 boost::shared_ptr<Source>
2801 Session::source_by_id (const PBD::ID& id)
2803 Glib::Mutex::Lock lm (source_lock);
2804 SourceMap::iterator i;
2805 boost::shared_ptr<Source> source;
2807 if ((i = sources.find (id)) != sources.end()) {
2815 boost::shared_ptr<Source>
2816 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2818 Glib::Mutex::Lock lm (source_lock);
2820 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2821 cerr << "comparing " << path << " with " << i->second->name() << endl;
2822 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2824 if (afs && afs->path() == path && chn == afs->channel()) {
2829 return boost::shared_ptr<Source>();
2833 Session::peak_path (Glib::ustring base) const
2835 sys::path peakfile_path(_session_dir->peak_path());
2836 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2837 return peakfile_path.to_string();
2841 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2844 string old_basename = PBD::basename_nosuffix (oldname);
2845 string new_legalized = legalize_for_path (newname);
2847 /* note: we know (or assume) the old path is already valid */
2851 /* destructive file sources have a name of the form:
2853 /path/to/Tnnnn-NAME(%[LR])?.wav
2855 the task here is to replace NAME with the new name.
2858 /* find last slash */
2862 string::size_type slash;
2863 string::size_type dash;
2865 if ((slash = path.find_last_of ('/')) == string::npos) {
2869 dir = path.substr (0, slash+1);
2871 /* '-' is not a legal character for the NAME part of the path */
2873 if ((dash = path.find_last_of ('-')) == string::npos) {
2877 prefix = path.substr (slash+1, dash-(slash+1));
2882 path += new_legalized;
2883 path += ".wav"; /* XXX gag me with a spoon */
2887 /* non-destructive file sources have a name of the form:
2889 /path/to/NAME-nnnnn(%[LR])?.wav
2891 the task here is to replace NAME with the new name.
2896 string::size_type slash;
2897 string::size_type dash;
2898 string::size_type postfix;
2900 /* find last slash */
2902 if ((slash = path.find_last_of ('/')) == string::npos) {
2906 dir = path.substr (0, slash+1);
2908 /* '-' is not a legal character for the NAME part of the path */
2910 if ((dash = path.find_last_of ('-')) == string::npos) {
2914 suffix = path.substr (dash+1);
2916 // Suffix is now everything after the dash. Now we need to eliminate
2917 // the nnnnn part, which is done by either finding a '%' or a '.'
2919 postfix = suffix.find_last_of ("%");
2920 if (postfix == string::npos) {
2921 postfix = suffix.find_last_of ('.');
2924 if (postfix != string::npos) {
2925 suffix = suffix.substr (postfix);
2927 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2931 const uint32_t limit = 10000;
2932 char buf[PATH_MAX+1];
2934 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2936 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2938 if (access (buf, F_OK) != 0) {
2946 error << "FATAL ERROR! Could not find a " << endl;
2955 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2959 char buf[PATH_MAX+1];
2960 const uint32_t limit = 10000;
2964 legalized = legalize_for_path (name);
2966 /* find a "version" of the file name that doesn't exist in
2967 any of the possible directories.
2970 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2972 vector<space_and_path>::iterator i;
2973 uint32_t existing = 0;
2975 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2977 SessionDirectory sdir((*i).path);
2979 spath = sdir.sound_path().to_string();
2983 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2984 } else if (nchan == 2) {
2986 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2988 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2990 } else if (nchan < 26) {
2991 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2993 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3002 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3003 } else if (nchan == 2) {
3005 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3007 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3009 } else if (nchan < 26) {
3010 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3012 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3016 if (sys::exists(buf)) {
3022 if (existing == 0) {
3027 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3029 throw failed_constructor();
3033 /* we now have a unique name for the file, but figure out where to
3039 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3041 spath = sdir.sound_path().to_string();
3044 string::size_type pos = foo.find_last_of ('/');
3046 if (pos == string::npos) {
3049 spath += foo.substr (pos + 1);
3055 boost::shared_ptr<AudioFileSource>
3056 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3058 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3059 return boost::dynamic_pointer_cast<AudioFileSource> (
3060 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3063 // FIXME: _terrible_ code duplication
3065 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3068 string old_basename = PBD::basename_nosuffix (oldname);
3069 string new_legalized = legalize_for_path (newname);
3071 /* note: we know (or assume) the old path is already valid */
3075 /* destructive file sources have a name of the form:
3077 /path/to/Tnnnn-NAME(%[LR])?.wav
3079 the task here is to replace NAME with the new name.
3082 /* find last slash */
3086 string::size_type slash;
3087 string::size_type dash;
3089 if ((slash = path.find_last_of ('/')) == string::npos) {
3093 dir = path.substr (0, slash+1);
3095 /* '-' is not a legal character for the NAME part of the path */
3097 if ((dash = path.find_last_of ('-')) == string::npos) {
3101 prefix = path.substr (slash+1, dash-(slash+1));
3106 path += new_legalized;
3107 path += ".mid"; /* XXX gag me with a spoon */
3111 /* non-destructive file sources have a name of the form:
3113 /path/to/NAME-nnnnn(%[LR])?.wav
3115 the task here is to replace NAME with the new name.
3120 string::size_type slash;
3121 string::size_type dash;
3122 string::size_type postfix;
3124 /* find last slash */
3126 if ((slash = path.find_last_of ('/')) == string::npos) {
3130 dir = path.substr (0, slash+1);
3132 /* '-' is not a legal character for the NAME part of the path */
3134 if ((dash = path.find_last_of ('-')) == string::npos) {
3138 suffix = path.substr (dash+1);
3140 // Suffix is now everything after the dash. Now we need to eliminate
3141 // the nnnnn part, which is done by either finding a '%' or a '.'
3143 postfix = suffix.find_last_of ("%");
3144 if (postfix == string::npos) {
3145 postfix = suffix.find_last_of ('.');
3148 if (postfix != string::npos) {
3149 suffix = suffix.substr (postfix);
3151 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3155 const uint32_t limit = 10000;
3156 char buf[PATH_MAX+1];
3158 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3160 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3162 if (access (buf, F_OK) != 0) {
3170 error << "FATAL ERROR! Could not find a " << endl;
3179 Session::midi_path_from_name (string name)
3183 char buf[PATH_MAX+1];
3184 const uint32_t limit = 10000;
3188 legalized = legalize_for_path (name);
3190 /* find a "version" of the file name that doesn't exist in
3191 any of the possible directories.
3194 for (cnt = 1; cnt <= limit; ++cnt) {
3196 vector<space_and_path>::iterator i;
3197 uint32_t existing = 0;
3199 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3201 SessionDirectory sdir((*i).path);
3203 sys::path p = sdir.midi_path();
3207 spath = p.to_string();
3209 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3211 if (sys::exists (buf)) {
3216 if (existing == 0) {
3221 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3222 throw failed_constructor();
3226 /* we now have a unique name for the file, but figure out where to
3232 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3234 spath = sdir.midi_path().to_string();
3237 string::size_type pos = foo.find_last_of ('/');
3239 if (pos == string::npos) {
3242 spath += foo.substr (pos + 1);
3248 boost::shared_ptr<MidiSource>
3249 Session::create_midi_source_for_session (MidiDiskstream& ds)
3251 string mpath = midi_path_from_name (ds.name());
3253 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3257 /* Playlist management */
3259 boost::shared_ptr<Playlist>
3260 Session::playlist_by_name (string name)
3262 Glib::Mutex::Lock lm (playlist_lock);
3263 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3264 if ((*i)->name() == name) {
3268 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3269 if ((*i)->name() == name) {
3274 return boost::shared_ptr<Playlist>();
3278 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3280 if (playlist->hidden()) {
3285 Glib::Mutex::Lock lm (playlist_lock);
3286 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3287 playlists.insert (playlists.begin(), playlist);
3288 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3289 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3295 PlaylistAdded (playlist); /* EMIT SIGNAL */
3299 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3302 Glib::Mutex::Lock lm (playlist_lock);
3303 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3306 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3313 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3315 boost::shared_ptr<Playlist> pl(wpl.lock());
3321 PlaylistList::iterator x;
3324 /* its not supposed to be visible */
3329 Glib::Mutex::Lock lm (playlist_lock);
3333 unused_playlists.insert (pl);
3335 if ((x = playlists.find (pl)) != playlists.end()) {
3336 playlists.erase (x);
3342 playlists.insert (pl);
3344 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3345 unused_playlists.erase (x);
3352 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3354 if (_state_of_the_state & Deletion) {
3358 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3365 Glib::Mutex::Lock lm (playlist_lock);
3367 PlaylistList::iterator i;
3369 i = find (playlists.begin(), playlists.end(), playlist);
3370 if (i != playlists.end()) {
3371 playlists.erase (i);
3374 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3375 if (i != unused_playlists.end()) {
3376 unused_playlists.erase (i);
3383 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3387 Session::set_audition (boost::shared_ptr<Region> r)
3389 pending_audition_region = r;
3390 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3391 schedule_butler_transport_work ();
3395 Session::audition_playlist ()
3397 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3398 ev->region.reset ();
3403 Session::non_realtime_set_audition ()
3405 if (!pending_audition_region) {
3406 auditioner->audition_current_playlist ();
3408 auditioner->audition_region (pending_audition_region);
3409 pending_audition_region.reset ();
3411 AuditionActive (true); /* EMIT SIGNAL */
3415 Session::audition_region (boost::shared_ptr<Region> r)
3417 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3423 Session::cancel_audition ()
3425 if (auditioner->active()) {
3426 auditioner->cancel_audition ();
3427 AuditionActive (false); /* EMIT SIGNAL */
3432 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3434 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3438 Session::remove_empty_sounds ()
3440 vector<string> audio_filenames;
3442 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3444 Glib::Mutex::Lock lm (source_lock);
3446 TapeFileMatcher tape_file_matcher;
3448 remove_if (audio_filenames.begin(), audio_filenames.end(),
3449 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3451 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3453 sys::path audio_file_path (_session_dir->sound_path());
3455 audio_file_path /= *i;
3457 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3461 sys::remove (audio_file_path);
3462 const string peakfile = peak_path (audio_file_path.to_string());
3463 sys::remove (peakfile);
3465 catch (const sys::filesystem_error& err)
3467 error << err.what() << endmsg;
3474 Session::is_auditioning () const
3476 /* can be called before we have an auditioner object */
3478 return auditioner->active();
3485 Session::set_all_solo (bool yn)
3487 shared_ptr<RouteList> r = routes.reader ();
3489 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3490 if (!(*i)->is_hidden()) {
3491 (*i)->set_solo (yn, this);
3499 Session::set_all_mute (bool yn)
3501 shared_ptr<RouteList> r = routes.reader ();
3503 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3504 if (!(*i)->is_hidden()) {
3505 (*i)->set_mute (yn, this);
3513 Session::n_diskstreams () const
3517 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3519 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3520 if (!(*i)->hidden()) {
3528 Session::graph_reordered ()
3530 /* don't do this stuff if we are setting up connections
3531 from a set_state() call or creating new tracks.
3534 if (_state_of_the_state & InitialConnecting) {
3538 /* every track/bus asked for this to be handled but it was deferred because
3539 we were connecting. do it now.
3542 request_input_change_handling ();
3546 /* force all diskstreams to update their capture offset values to
3547 reflect any changes in latencies within the graph.
3550 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3552 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3553 (*i)->set_capture_offset ();
3558 Session::record_disenable_all ()
3560 record_enable_change_all (false);
3564 Session::record_enable_all ()
3566 record_enable_change_all (true);
3570 Session::record_enable_change_all (bool yn)
3572 shared_ptr<RouteList> r = routes.reader ();
3574 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3577 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3578 at->set_record_enable (yn, this);
3582 /* since we don't keep rec-enable state, don't mark session dirty */
3586 Session::add_processor (Processor* processor)
3589 PortInsert* port_insert;
3590 PluginInsert* plugin_insert;
3592 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3593 _port_inserts.insert (_port_inserts.begin(), port_insert);
3594 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3595 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3596 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3597 _sends.insert (_sends.begin(), send);
3599 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3603 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3609 Session::remove_processor (Processor* processor)
3612 PortInsert* port_insert;
3613 PluginInsert* plugin_insert;
3615 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3616 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3617 if (x != _port_inserts.end()) {
3618 insert_bitset[port_insert->bit_slot()] = false;
3619 _port_inserts.erase (x);
3621 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3622 _plugin_inserts.remove (plugin_insert);
3623 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3624 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3625 if (x != _sends.end()) {
3626 send_bitset[send->bit_slot()] = false;
3630 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3638 Session::available_capture_duration ()
3640 float sample_bytes_on_disk = 4.0; // keep gcc happy
3642 switch (Config->get_native_file_data_format()) {
3644 sample_bytes_on_disk = 4.0;
3648 sample_bytes_on_disk = 3.0;
3652 sample_bytes_on_disk = 2.0;
3656 /* impossible, but keep some gcc versions happy */
3657 fatal << string_compose (_("programming error: %1"),
3658 X_("illegal native file data format"))
3663 double scale = 4096.0 / sample_bytes_on_disk;
3665 if (_total_free_4k_blocks * scale > (double) max_frames) {
3669 return (nframes_t) floor (_total_free_4k_blocks * scale);
3673 Session::add_bundle (shared_ptr<Bundle> bundle)
3676 Glib::Mutex::Lock guard (bundle_lock);
3677 _bundles.push_back (bundle);
3680 BundleAdded (bundle); /* EMIT SIGNAL */
3686 Session::remove_bundle (shared_ptr<Bundle> bundle)
3688 bool removed = false;
3691 Glib::Mutex::Lock guard (bundle_lock);
3692 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3694 if (i != _bundles.end()) {
3701 BundleRemoved (bundle); /* EMIT SIGNAL */
3708 Session::bundle_by_name (string name) const
3710 Glib::Mutex::Lock lm (bundle_lock);
3712 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3713 if ((*i)->name() == name) {
3718 return boost::shared_ptr<Bundle> ();
3722 Session::tempo_map_changed (Change ignored)
3728 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3729 * the given count with the current block size.
3732 Session::ensure_buffers (ChanCount howmany)
3734 if (current_block_size == 0)
3735 return; // too early? (is this ok?)
3737 // We need at least 2 MIDI scratch buffers to mix/merge
3738 if (howmany.n_midi() < 2)
3739 howmany.set_midi(2);
3741 // FIXME: JACK needs to tell us maximum MIDI buffer size
3742 // Using nasty assumption (max # events == nframes) for now
3743 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3744 _mix_buffers->ensure_buffers(howmany, current_block_size);
3745 _silent_buffers->ensure_buffers(howmany, current_block_size);
3747 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3751 Session::next_insert_id ()
3753 /* this doesn't really loop forever. just think about it */
3756 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3757 if (!insert_bitset[n]) {
3758 insert_bitset[n] = true;
3764 /* none available, so resize and try again */
3766 insert_bitset.resize (insert_bitset.size() + 16, false);
3771 Session::next_send_id ()
3773 /* this doesn't really loop forever. just think about it */
3776 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3777 if (!send_bitset[n]) {
3778 send_bitset[n] = true;
3784 /* none available, so resize and try again */
3786 send_bitset.resize (send_bitset.size() + 16, false);
3791 Session::mark_send_id (uint32_t id)
3793 if (id >= send_bitset.size()) {
3794 send_bitset.resize (id+16, false);
3796 if (send_bitset[id]) {
3797 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3799 send_bitset[id] = true;
3803 Session::mark_insert_id (uint32_t id)
3805 if (id >= insert_bitset.size()) {
3806 insert_bitset.resize (id+16, false);
3808 if (insert_bitset[id]) {
3809 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3811 insert_bitset[id] = true;
3814 /* Named Selection management */
3817 Session::named_selection_by_name (string name)
3819 Glib::Mutex::Lock lm (named_selection_lock);
3820 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3821 if ((*i)->name == name) {
3829 Session::add_named_selection (NamedSelection* named_selection)
3832 Glib::Mutex::Lock lm (named_selection_lock);
3833 named_selections.insert (named_selections.begin(), named_selection);
3836 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3842 NamedSelectionAdded (); /* EMIT SIGNAL */
3846 Session::remove_named_selection (NamedSelection* named_selection)
3848 bool removed = false;
3851 Glib::Mutex::Lock lm (named_selection_lock);
3853 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3855 if (i != named_selections.end()) {
3857 named_selections.erase (i);
3864 NamedSelectionRemoved (); /* EMIT SIGNAL */
3869 Session::reset_native_file_format ()
3871 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3873 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3874 (*i)->reset_write_sources (false);
3879 Session::route_name_unique (string n) const
3881 shared_ptr<RouteList> r = routes.reader ();
3883 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3884 if ((*i)->name() == n) {
3893 Session::n_playlists () const
3895 Glib::Mutex::Lock lm (playlist_lock);
3896 return playlists.size();
3900 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3902 if (!force && howmany <= _npan_buffers) {
3906 if (_pan_automation_buffer) {
3908 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3909 delete [] _pan_automation_buffer[i];
3912 delete [] _pan_automation_buffer;
3915 _pan_automation_buffer = new pan_t*[howmany];
3917 for (uint32_t i = 0; i < howmany; ++i) {
3918 _pan_automation_buffer[i] = new pan_t[nframes];
3921 _npan_buffers = howmany;
3925 Session::freeze (InterThreadInfo& itt)
3927 shared_ptr<RouteList> r = routes.reader ();
3929 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3933 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3934 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3945 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3946 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3949 boost::shared_ptr<Playlist> playlist;
3950 boost::shared_ptr<AudioFileSource> fsource;
3952 char buf[PATH_MAX+1];
3953 ChanCount nchans(track.audio_diskstream()->n_channels());
3955 nframes_t this_chunk;
3958 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3959 const string sound_dir = sdir.sound_path().to_string();
3961 // any bigger than this seems to cause stack overflows in called functions
3962 const nframes_t chunk_size = (128 * 1024)/4;
3964 g_atomic_int_set (&processing_prohibited, 1);
3966 /* call tree *MUST* hold route_lock */
3968 if ((playlist = track.diskstream()->playlist()) == 0) {
3972 /* external redirects will be a problem */
3974 if (track.has_external_redirects()) {
3978 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3980 for (x = 0; x < 99999; ++x) {
3981 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3982 if (access (buf, F_OK) != 0) {
3988 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3993 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3994 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3997 catch (failed_constructor& err) {
3998 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4002 srcs.push_back (fsource);
4005 /* XXX need to flush all redirects */
4010 /* create a set of reasonably-sized buffers */
4011 buffers.ensure_buffers(nchans, chunk_size);
4012 buffers.set_count(nchans);
4014 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4015 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4017 afs->prepare_for_peakfile_writes ();
4020 while (to_do && !itt.cancel) {
4022 this_chunk = min (to_do, chunk_size);
4024 if (track.export_stuff (buffers, start, this_chunk)) {
4029 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4030 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4033 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4039 start += this_chunk;
4040 to_do -= this_chunk;
4042 itt.progress = (float) (1.0 - ((double) to_do / len));
4051 xnow = localtime (&now);
4053 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4054 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4057 afs->update_header (position, *xnow, now);
4058 afs->flush_header ();
4062 /* construct a region to represent the bounced material */
4064 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4065 region_name_from_path (srcs.front()->name(), true));
4072 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4073 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4076 afs->mark_for_remove ();
4079 (*src)->drop_references ();
4083 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4084 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4087 afs->done_with_peakfile_writes ();
4091 g_atomic_int_set (&processing_prohibited, 0);
4097 Session::get_silent_buffers (ChanCount count)
4099 assert(_silent_buffers->available() >= count);
4100 _silent_buffers->set_count(count);
4102 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4103 for (size_t i=0; i < count.get(*t); ++i) {
4104 _silent_buffers->get(*t, i).clear();
4108 return *_silent_buffers;
4112 Session::get_scratch_buffers (ChanCount count)
4114 assert(_scratch_buffers->available() >= count);
4115 _scratch_buffers->set_count(count);
4116 return *_scratch_buffers;
4120 Session::get_mix_buffers (ChanCount count)
4122 assert(_mix_buffers->available() >= count);
4123 _mix_buffers->set_count(count);
4124 return *_mix_buffers;
4128 Session::ntracks () const
4131 shared_ptr<RouteList> r = routes.reader ();
4133 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4134 if (dynamic_cast<Track*> ((*i).get())) {
4143 Session::nbusses () const
4146 shared_ptr<RouteList> r = routes.reader ();
4148 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4149 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4158 Session::add_automation_list(AutomationList *al)
4160 automation_lists[al->id()] = al;
4164 Session::compute_initial_length ()
4166 return _engine.frame_rate() * 60 * 5;
4170 Session::sync_order_keys ()
4172 if (!Config->get_sync_all_route_ordering()) {
4173 /* leave order keys as they are */
4177 boost::shared_ptr<RouteList> r = routes.reader ();
4179 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4180 (*i)->sync_order_keys ();
4183 Route::SyncOrderKeys (); // EMIT SIGNAL
4187 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4189 Glib::Mutex::Lock lm (bundle_lock);
4190 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {